当前位置: 首页>>代码示例>>Golang>>正文


Golang doc.New函数代码示例

本文整理汇总了Golang中go/doc.New函数的典型用法代码示例。如果您正苦于以下问题:Golang New函数的具体用法?Golang New怎么用?Golang New使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了New函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: ParseDocs

//ParseDocs parses the Package's documentation with go/doc.
//
//If you do not need a particular doc.Mode call this with 0.
//
//If the package directory contains a file of package documentation
//(and the package is not itself named documentation), it is parsed
//and its doc.Package.Doc string replaces the string generated
//by the package itself.
//
//Note that the go/doc package munges the AST so this method parses the AST
//again, regardless of the value in p.AST. As a consequence, it is valid
//to call this even if you have not called the Parse method or if you have
//called the Parse method and told it not to parse comments.
func (p *Package) ParseDocs(mode doc.Mode) error {
	if p.Doc != nil {
		return nil
	}
	pkg, _, err := p.parse(true)
	if err != nil {
		return err
	}

	p.Doc = doc.New(pkg, p.Build.ImportPath, mode)

	//we don't want the below running if we happen to be importing a package
	//whose name happens to be documentation.
	if p.Build.Name == "documentation" {
		return nil
	}

	//check ignored files for any package named documentation.
	//assume there is only one such file.
	//We ignore errors here as the ignored files may not be meant to parse.
	var docfile string
	for _, u := range p.Build.IgnoredGoFiles {
		path := filepath.Join(p.Build.Dir)
		fs := token.NewFileSet()
		f, err := parser.ParseFile(fs, path, nil, parser.PackageClauseOnly)
		if err != nil {
			continue
		}
		if f.Name.Name == "documentation" {
			docfile = u
			break
		}
	}

	//there's an ignored file of package documentation,
	//parse it and replace the package doc string with this doc string.
	if docfile != "" {
		fs := token.NewFileSet()
		f := func(fi os.FileInfo) bool {
			return !fi.IsDir() && fi.Name() == docfile
		}
		pkgs, err := parser.ParseDir(fs, p.Build.Dir, f, parser.ParseComments)
		if err != nil {
			return err
		}
		d := doc.New(pkgs["documentation"], p.Build.ImportPath, 0)
		p.Doc.Doc = d.Doc
	}

	return nil
}
开发者ID:jimmyfrasche,项目名称:goutil,代码行数:64,代码来源:package.go

示例2: getPageInfo

func getPageInfo(pkgName, diskPath string) (pi PageInfo, err error) {
	bpkg, err := build.ImportDir(diskPath, 0)
	if err != nil {
		return
	}
	inSet := make(map[string]bool)
	for _, name := range bpkg.GoFiles {
		inSet[filepath.Base(name)] = true
	}

	pi.FSet = token.NewFileSet()
	filter := func(fi os.FileInfo) bool {
		return inSet[fi.Name()]
	}
	aPkgMap, err := parser.ParseDir(pi.FSet, diskPath, filter, 0)
	if err != nil {
		return
	}
	aPkg := aPkgMap[pathpkg.Base(pkgName)]
	if aPkg == nil {
		for _, v := range aPkgMap {
			aPkg = v
			break
		}
		if aPkg == nil {
			err = errors.New("no apkg found?")
			return
		}
	}

	pi.Dirname = diskPath
	pi.PDoc = doc.New(aPkg, pkgName, 0)
	pi.IsMain = strings.Contains(pkgName, "camlistore.org/cmd/")
	return
}
开发者ID:ngerakines,项目名称:camlistore,代码行数:35,代码来源:godoc.go

示例3: packageComment

func packageComment(pkg, pkgpath string) (info string, err error) {
	fset := token.NewFileSet()
	pkgs, err := parser.ParseDir(fset, pkgpath, isGoFile, parser.PackageClauseOnly|parser.ParseComments)
	if err != nil {
		return
	}
	for name := range pkgs {
		if name == "main" {
			continue
		}
		pdoc := doc.New(pkgs[name], pkg, doc.AllDecls)
		if pdoc.Doc == "" {
			continue
		}
		if info != "" {
			return "", errors.New("multiple packages with docs")
		}
		info = pdoc.Doc
	}
	// grab only first paragraph
	if parts := strings.SplitN(info, "\n\n", 2); len(parts) > 1 {
		info = parts[0]
	}
	// replace newlines with spaces
	info = strings.Replace(info, "\n", " ", -1)
	// truncate
	if len(info) > MaxCommentLength {
		info = info[:MaxCommentLength]
	}
	return
}
开发者ID:joninvski,项目名称:go,代码行数:31,代码来源:package.go

示例4: ReflectDefs

func ReflectDefs() (names map[string][]byte, err error) {
	b, err := build.Import("reflect", "", 0)
	if err != nil {
		return nil, err
	}

	ts := token.NewFileSet()

	p, err := parser.ParseDir(ts, b.Dir, gofiles, 0)
	if err != nil {
		return nil, err
	}

	pkg := doc.New(p["reflect"], "reflect", doc.AllMethods)

	acc := []string{}
	acc = values(pkg.Consts, acc)
	acc = values(pkg.Vars, acc)
	acc = funcs(pkg.Funcs, "reflect.", acc)
	acc = types(pkg.Types, acc)

	names = map[string][]byte{}
	for _, name := range acc {
		names[name] = []byte(name)
	}
	return names, nil
}
开发者ID:jimmyfrasche,项目名称:go-reflection-codex,代码行数:27,代码来源:reflect.go

示例5: main

func main() {
	pkg, err := build.Import("robpike.io/ivy", "", build.ImportComment)
	if err != nil {
		log.Fatal(err)
	}
	fs := token.NewFileSet()
	pkgs, err := parser.ParseDir(fs, pkg.Dir, nil, parser.ParseComments)
	if err != nil {
		log.Fatal(err)
	}
	astPkg := pkgs[pkg.Name]
	if astPkg == nil {
		log.Fatalf("failed to locate %s package", pkg.Name)
	}

	docPkg := doc.New(astPkg, pkg.ImportPath, doc.AllDecls)

	htmlBuf := new(bytes.Buffer)
	fmt.Fprintln(htmlBuf, `<!-- auto-generated from robpike.io/ivy package doc -->`)
	fmt.Fprintln(htmlBuf, head)
	fmt.Fprintln(htmlBuf, `<body>`)
	doc.ToHTML(htmlBuf, docPkg.Doc, nil)
	fmt.Fprintln(htmlBuf, `</body></html>`)

	goBuf := new(bytes.Buffer)
	fmt.Fprintf(goBuf, "package mobile\n\n")
	fmt.Fprintf(goBuf, "// GENERATED; DO NOT EDIT\n")
	fmt.Fprintf(goBuf, "const help = `%s`\n", sanitize(htmlBuf.Bytes()))

	buf, err := format.Source(goBuf.Bytes())
	if err != nil {
		log.Fatalf("failed to gofmt: %v", err)
	}
	os.Stdout.Write(buf)
}
开发者ID:zzn01,项目名称:ivy,代码行数:35,代码来源:help_gen.go

示例6: PackageDoc

// PackageDoc gets the documentation for the package with the specified import
// path and writes it to out.
func PackageDoc(ctxt *build.Context, fset *token.FileSet, srcDir string, importPath string) (*Doc, error) {
	buildPkg, err := ctxt.Import(importPath, srcDir, build.ImportComment)
	if err != nil {
		return nil, err
	}
	// only parse .go files in the specified package
	filter := func(info os.FileInfo) bool {
		for _, fname := range buildPkg.GoFiles {
			if fname == info.Name() {
				return true
			}
		}
		return false
	}
	// TODO we've already parsed the files via go/loader...can we avoid doing it again?
	pkgs, err := parser.ParseDir(fset, buildPkg.Dir, filter, parser.PackageClauseOnly|parser.ParseComments)
	if err != nil {
		return nil, err
	}
	if astPkg, ok := pkgs[buildPkg.Name]; ok {
		docPkg := doc.New(astPkg, importPath, 0)
		// TODO: we could also include package-level constants, vars, and functions (like the go doc command)
		return &Doc{
			Name: buildPkg.Name,
			Decl: "package " + buildPkg.Name, // TODO: add '// import "pkg"' (like godoc)
			Doc:  docPkg.Doc,
		}, nil
	}
	return nil, errors.New("No documentation found for " + buildPkg.Name)
}
开发者ID:zmb3,项目名称:gogetdoc,代码行数:32,代码来源:pkg.go

示例7: main

func main() {
	flag.Parse()
	if len(flag.Args()) != 1 {
		log.Fatal("Usage: go run goprint.go path")
	}
	bpkg, err := build.Default.Import(flag.Args()[0], ".", 0)
	if err != nil {
		log.Fatal(err)
	}
	fset := token.NewFileSet()
	files := make(map[string]*ast.File)
	for _, fname := range bpkg.GoFiles {
		p, err := ioutil.ReadFile(filepath.Join(bpkg.SrcRoot, bpkg.ImportPath, fname))
		if err != nil {
			log.Fatal(err)
		}
		file, err := parser.ParseFile(fset, fname, p, parser.ParseComments)
		if err != nil {
			log.Fatal(err)
		}
		files[fname] = file
	}
	c := spew.NewDefaultConfig()
	c.DisableMethods = true
	apkg, _ := ast.NewPackage(fset, files, importer, nil)
	c.Dump(apkg)
	ast.Print(fset, apkg)
	dpkg := doc.New(apkg, bpkg.ImportPath, 0)
	c.Dump(dpkg)
}
开发者ID:maddyonline,项目名称:gddo,代码行数:30,代码来源:goprint.go

示例8: NewPackageView

func NewPackageView(pkg *ast.Package, fset *token.FileSet, expr bool) (*PackageView, error) {
	p := new(PackageView)
	p.fset = fset
	p.pkg = pkg
	p.pdoc = doc.New(pkg, pkg.Name, doc.AllDecls)
	p.expr = expr
	return p, nil
}
开发者ID:RavenZZ,项目名称:liteide,代码行数:8,代码来源:astview.go

示例9: ExtractStructs

func ExtractStructs(inputPath string) (string, []*StructInfo, error) {
	fset := token.NewFileSet()

	f, err := parser.ParseFile(fset, inputPath, nil, parser.ParseComments)

	if err != nil {
		return "", nil, err
	}

	packageName := f.Name.String()
	structs := make(map[string]*StructInfo)

	for k, d := range f.Scope.Objects {
		if d.Kind == ast.Typ {
			incl, err := shouldInclude(d)
			if err != nil {
				return "", nil, err
			}
			if incl {
				stobj := NewStructInfo(k)

				structs[k] = stobj
			}
		}
	}

	files := map[string]*ast.File{
		inputPath: f,
	}

	pkg, _ := ast.NewPackage(fset, files, nil, nil)

	d := doc.New(pkg, f.Name.String(), doc.AllDecls)
	for _, t := range d.Types {
		if skipre.MatchString(t.Doc) {
			delete(structs, t.Name)
		} else {
			if skipdec.MatchString(t.Doc) {
				s, ok := structs[t.Name]
				if ok {
					s.Options.SkipDecoder = true
				}
			}
			if skipenc.MatchString(t.Doc) {
				s, ok := structs[t.Name]
				if ok {
					s.Options.SkipEncoder = true
				}
			}
		}
	}

	rv := make([]*StructInfo, 0)
	for _, v := range structs {
		rv = append(rv, v)
	}
	return packageName, rv, nil
}
开发者ID:nolenroyalty,项目名称:bangarang,代码行数:58,代码来源:parser.go

示例10: build

// build generates data from source files.
func (w *routerWalker) build(srcs []*source) (*Package, error) {
	// Add source files to walker, I skipped references here.
	w.srcs = make(map[string]*source)
	for _, src := range srcs {
		w.srcs[src.name] = src
	}

	w.fset = token.NewFileSet()

	// Find the package and associated files.
	ctxt := gobuild.Context{
		GOOS:          runtime.GOOS,
		GOARCH:        runtime.GOARCH,
		CgoEnabled:    true,
		JoinPath:      path.Join,
		IsAbsPath:     path.IsAbs,
		SplitPathList: func(list string) []string { return strings.Split(list, ":") },
		IsDir:         func(path string) bool { panic("unexpected") },
		HasSubdir:     func(root, dir string) (rel string, ok bool) { panic("unexpected") },
		ReadDir:       func(dir string) (fi []os.FileInfo, err error) { return w.readDir(dir) },
		OpenFile:      func(path string) (r io.ReadCloser, err error) { return w.openFile(path) },
		Compiler:      "gc",
	}

	bpkg, err := ctxt.ImportDir(w.pdoc.ImportPath, 0)
	// Continue if there are no Go source files; we still want the directory info.
	_, nogo := err.(*gobuild.NoGoError)
	if err != nil {
		if nogo {
			err = nil
		} else {
			return nil, errors.New("routerWalker.build -> " + err.Error())
		}
	}

	// Parse the Go files
	files := make(map[string]*ast.File)
	for _, name := range append(bpkg.GoFiles, bpkg.CgoFiles...) {
		file, err := parser.ParseFile(w.fset, name, w.srcs[name].data, parser.ParseComments)
		if err != nil {
			return nil, errors.New("routerWalker.build -> parse go files: " + err.Error())
		}
		files[name] = file
	}

	apkg, _ := ast.NewPackage(w.fset, files, simpleImporter, nil)

	mode := doc.Mode(0)
	if w.pdoc.ImportPath == "builtin" {
		mode |= doc.AllDecls
	}

	pdoc := doc.New(apkg, w.pdoc.ImportPath, mode)

	w.pdoc.Types = w.types(pdoc.Types)

	return w.pdoc, err
}
开发者ID:Linvas,项目名称:ant,代码行数:59,代码来源:autorouter.go

示例11: getDoc

func getDoc(dir string) (Doc, error) {
	bi, err := build.ImportDir(dir, 0)
	if err != nil {
		return Doc{}, nil
	}

	ip, err := importPath(dir)
	if err != nil {
		return Doc{}, err
	}

	filter := func(fi os.FileInfo) bool {
		if fi.IsDir() {
			return false
		}
		nm := fi.Name()
		for _, f := range append(bi.GoFiles, bi.CgoFiles...) {
			if nm == f {
				return true
			}
		}
		return false
	}

	pkgs, err := parser.ParseDir(token.NewFileSet(), bi.Dir, filter, parser.ParseComments)
	if err != nil {
		return Doc{}, err
	}

	pkg := pkgs[bi.Name]
	docs := doc.New(pkg, bi.ImportPath, 0)

	bugs := []string{}
	for _, bug := range docs.Notes["BUG"] {
		bugs = append(bugs, bug.Body)
	}

	name := bi.Name
	if name == "main" {
		name = filepath.Base(bi.Dir)
	}

	//get import path without the github.com/
	pathelms := strings.Split(ip, "/")[1:]
	repo := path.Join(pathelms...)

	return Doc{
		Name:     name,
		Import:   ip,
		Synopsis: bi.Doc,
		Doc:      fmtDoc(docs.Doc),
		Today:    today(),
		RepoPath: repo,
		Bugs:     bugs,
		Library:  bi.Name != "main",
		Command:  bi.Name == "main",
	}, nil
}
开发者ID:jimmyfrasche,项目名称:autoreadme,代码行数:58,代码来源:autoreadme.go

示例12: run

func run() error {
	pkg, err := build.Import("euphoria.io/heim/proto", "", build.FindOnly)
	if err != nil {
		return fmt.Errorf("import error: %s", err)
	}

	if pkg.SrcRoot == "" {
		return fmt.Errorf("error: can't find source for package euphoria.io/heim/proto")
	}

	pkgs, err := parser.ParseDir(
		token.NewFileSet(), filepath.Join(pkg.SrcRoot, "euphoria.io/heim/proto"), nil,
		parser.ParseComments)
	if err != nil {
		return fmt.Errorf("parse error: %s", err)
	}

	obs := (*objects)(doc.New(pkgs["proto"], "euphoria.io/heim/proto", 0))
	ps := sortObjects(obs)
	ts := types{}
	t := template.New("api.md").Funcs(template.FuncMap{
		"object": obs.tmplObject,
		"others": ps.tmplOthers,
		"packet": ps.tmplPacket,

		"linkType":     ts.linkType,
		"registerType": ts.registerType,
	})

	ts.registerType("bool")
	ts.registerType("int")
	ts.registerType("object")
	ts.registerType("string")
	ts.registerType("AccountView")
	ts.registerType("AuthOption")
	ts.registerType("Message")
	ts.registerType("PacketType")
	ts.registerType("PersonalAccountView")
	ts.registerType("SessionView")
	ts.registerType("Snowflake")
	ts.registerType("Time")
	ts.registerType("UserID")

	gendir := filepath.Join(pkg.SrcRoot, "euphoria.io/heim/doc/gen")
	if err := os.Chdir(gendir); err != nil {
		return fmt.Errorf("chdir error: %s: %s", gendir, err)
	}

	if _, err := t.ParseGlob("*.md"); err != nil {
		return fmt.Errorf("template parse error: %s", err)
	}
	if err := t.Execute(os.Stdout, nil); err != nil {
		return fmt.Errorf("template render error: %s", err)
	}

	return nil
}
开发者ID:logan,项目名称:heim,代码行数:57,代码来源:gen.go

示例13: NewPackageDeclFromAstPackage

func NewPackageDeclFromAstPackage(astPkg *ast.Package, fullImportPath string) *PackageDecl {
	output := &PackageDecl{TypeMap: make(map[string]*TypeDecl)}

	docPkg := doc.New(astPkg, fullImportPath, doc.AllMethods)
	for _, t := range docPkg.Types {
		output.TypeMap[t.Name] = NewTypeDeclFromDocType(t)
	}
	return output
}
开发者ID:iizotop,项目名称:kmg,代码行数:9,代码来源:PackageDecl.go

示例14: tryImport

func tryImport(root, relpath string) error {
	path := filepath.Join(root, relpath)
	ctx := build.Default
	dir, err := ctx.ImportDir(path, 0)
	if _, nogo := err.(*build.NoGoError); nogo {
		return nil
	}
	if err != nil {
		return fmt.Errorf("ImportDir failed: %v", err)
	}

	pkgFiles := append(dir.GoFiles, dir.CgoFiles...)
	fullPkgsFiles := make([]string, 0, len(pkgFiles))

	for _, p := range pkgFiles {
		fullPkgsFiles = append(fullPkgsFiles, filepath.Join(path, p))
	}

	pkg, err := parseFiles(fullPkgsFiles)
	if err != nil {
		if err == errNoPackagesFound {
			// that error is eaten silently
			return nil
		}
		return fmt.Errorf("Failed to parse pkg %s/%s: %v", root, relpath, err)
	}

	pdoc := doc.New(pkg, relpath, 0)

	outputValues(relpath, pdoc.Consts, "#pkg-constants", "const")
	outputValues(relpath, pdoc.Vars, "#pkg-variables", "var")

	for _, tp := range pdoc.Types {
		outputCDB(relpath+"/"+tp.Name+" "+ppType(tp)+maybeDoc(tp.Doc, tp.Name),
			"godoc:"+relpath+"#"+tp.Name)
		for _, fun := range tp.Methods {
			typename := fun.Recv
			if typename[0] == '*' {
				typename = typename[1:]
			}
			outputCDB(buildFuncKey(relpath, fun),
				"godoc:"+relpath+"#"+typename+"."+fun.Name)
		}
		for _, fun := range tp.Funcs {
			outputCDB(buildFuncKey(relpath, fun),
				"godoc:"+relpath+"#"+fun.Name)
		}
	}

	for _, fun := range pdoc.Funcs {
		outputCDB(buildFuncKey(relpath, fun),
			"godoc:"+relpath+"#"+fun.Name)
	}

	return nil
}
开发者ID:alk,项目名称:supermegadoc,代码行数:56,代码来源:go-indexer.go

示例15: getDocPackageMode

func getDocPackageMode(bpkg *build.Package, err error, mode doc.Mode) (dpkg *doc.Package, err2 error) {
	if err != nil {
		return nil, err
	}
	apkg, err := AstPackageFromBuildPackage(bpkg)
	if err != nil {
		return nil, err
	}
	return doc.New(apkg, bpkg.ImportPath, mode), nil
}
开发者ID:rexposadas,项目名称:gx,代码行数:10,代码来源:main.go


注:本文中的go/doc.New函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。