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


Golang Context.ImportDir方法代码示例

本文整理汇总了Golang中go/build.Context.ImportDir方法的典型用法代码示例。如果您正苦于以下问题:Golang Context.ImportDir方法的具体用法?Golang Context.ImportDir怎么用?Golang Context.ImportDir使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在go/build.Context的用法示例。


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

示例1: resolvePackageSpec

func resolvePackageSpec(ctx *build.Context, cwd string, src io.Reader, spec string) string {
	if strings.HasSuffix(spec, ".go") {
		d := path.Dir(spec)
		if !buildutil.IsAbsPath(ctx, d) {
			d = buildutil.JoinPath(ctx, cwd, d)
		}
		if bpkg, err := ctx.ImportDir(d, build.FindOnly); err == nil {
			return bpkg.ImportPath
		}
	}
	path := spec
	switch {
	case strings.HasPrefix(spec, "."):
		if bpkg, err := ctx.Import(spec, cwd, build.FindOnly); err == nil {
			path = bpkg.ImportPath
		}
	case strings.HasPrefix(spec, "/"):
		path = spec[1:]
	default:
		if p, ok := readImports(cwd, src)[spec]; ok {
			path = p
		}
	}
	return strings.TrimSuffix(path, "/")
}
开发者ID:garyburd,项目名称:vigor,代码行数:25,代码来源:args.go

示例2: imports

// imports returns a map of all import directories (recursively) used by the app.
// The return value maps full directory names to original import names.
func imports(ctxt *build.Context, srcDir string, gopath []string) (map[string]string, error) {
	pkg, err := ctxt.ImportDir(srcDir, 0)
	if err != nil {
		return nil, fmt.Errorf("unable to analyze source: %v", err)
	}

	// Resolve all non-standard-library imports
	result := make(map[string]string)
	for _, v := range pkg.Imports {
		if !strings.Contains(v, ".") {
			continue
		}
		src, err := findInGopath(v, gopath)
		if err != nil {
			return nil, fmt.Errorf("unable to find import %v in gopath %v: %v", v, gopath, err)
		}
		result[src] = v
		im, err := imports(ctxt, src, gopath)
		if err != nil {
			return nil, fmt.Errorf("unable to parse package %v: %v", src, err)
		}
		for k, v := range im {
			result[k] = v
		}
	}
	return result, nil
}
开发者ID:Celluliodio,项目名称:flannel,代码行数:29,代码来源:aebundler.go

示例3: generate_target

func generate_target(srcdir string, pkgdir string, prefix string, ctx build.Context) string {
	pkg, _ := ctx.ImportDir(srcdir+pkgdir, 0)
	name := pkg.Name
	var deps []string
	for _, imp := range pkg.Imports {
		if strings.HasPrefix(imp, prefix) {
			imp = strings.TrimPrefix(imp, prefix)
			if packages[imp] == "" {
				packages[imp] = generate_target(srcdir, imp, prefix, ctx)
			}
			deps = append(deps, "$(LIBS_"+packages[imp]+")")
		}
	}
	if pkgdir != "" {
		fmt.Printf("SRCDIR_%s := $(SRCDIR)%s/\n", name, pkgdir)
	} else {
		fmt.Printf("SRCDIR_%s := $(SRCDIR)\n", name)
	}
	fmt.Printf("SRC_%s := $(addprefix $(SRCDIR_%s), %s)\n", name, name, strings.Join(pkg.GoFiles, " "))
	fmt.Printf("DEPS_%s := %s\n", name, strings.Join(deps, " "))
	if pkgdir != "" {
		fmt.Printf("OBJ_%s := $(LIBDIR)/%s.o\n", name, pkgdir)
		fmt.Printf("LIB_%s := $(LIBDIR)/%s.a\n", name, pkgdir)
		fmt.Printf("LIBS_%s := $(LIB_%s) $(DEPS_%s)\n", name, name, name)
		fmt.Printf("$(OBJ_%s) : $(SRC_%s) $(DEPS_%s)\n", name, name, name)
		fmt.Printf("\[email protected] -p $(dir [email protected])\n")
		fmt.Printf("\t$(GOC) $(GOFLAGS) -c -o [email protected] $(SRC_%s)\n", name)
	}
	return name
}
开发者ID:zhaohaiyi,项目名称:git-lfs,代码行数:30,代码来源:genmakefile.go

示例4: build

// build gets imports from source files.
func (w *walker) build(srcs []*source) ([]string, 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 := build.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.ImportPath, 0)
	// Continue if there are no Go source files; we still want the directory info.
	_, nogo := err.(*build.NoGoError)
	if err != nil {
		if nogo {
			err = nil
		} else {
			return nil, errors.New("doc.walker.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 {
			//beego.Error("doc.walker.build():", err)
			continue
		}
		files[name] = file
	}

	w.ImportPath = strings.Replace(w.ImportPath, "\\", "/", -1)
	var imports []string
	for _, v := range bpkg.Imports {
		// Skip strandard library.
		if !utils.IsGoRepoPath(v) &&
			(utils.GetProjectPath(v) != utils.GetProjectPath(w.ImportPath)) {
			imports = append(imports, v)
		}
	}

	return imports, err
}
开发者ID:jmcvetta,项目名称:gopm,代码行数:60,代码来源:walker.go

示例5: 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

示例6: ImportStdPkg

func ImportStdPkg(context *build.Context, path string, mode build.ImportMode) (*build.Package, error) {
	realpath := filepath.Join(context.GOROOT, "src", "pkg", path)
	if _, err := os.Stat(realpath); err != nil {
		realpath = filepath.Join(context.GOROOT, "src", path)
	}
	pkg, err := context.ImportDir(realpath, 0)
	pkg.ImportPath = path
	return pkg, err
}
开发者ID:kissthink,项目名称:ide_stub,代码行数:9,代码来源:go13.go

示例7: Import

// Import returns details about the package in the directory.
func (dir *Directory) Import(ctx *build.Context, mode build.ImportMode) (*build.Package, error) {
	safeCopy := *ctx
	ctx = &safeCopy
	ctx.JoinPath = path.Join
	ctx.IsAbsPath = path.IsAbs
	ctx.SplitPathList = func(list string) []string { return strings.Split(list, ":") }
	ctx.IsDir = func(path string) bool { return false }
	ctx.HasSubdir = func(root, dir string) (rel string, ok bool) { return "", false }
	ctx.ReadDir = dir.readDir
	ctx.OpenFile = dir.openFile
	return ctx.ImportDir(".", mode)
}
开发者ID:maddyonline,项目名称:gddo,代码行数:13,代码来源:build.go

示例8: appFiles

// appFiles returns a list of all Go source files in the app.
func appFiles(ctxt *build.Context) ([]string, error) {
	pkg, err := ctxt.ImportDir(".", 0)
	if err != nil {
		return nil, err
	}
	if !pkg.IsCommand() {
		return nil, fmt.Errorf(`the root of your app needs to be package "main" (currently %q). Please see https://cloud.google.com/appengine/docs/go/managed-vms for more details on structuring your app.`, pkg.Name)
	}
	var appFiles []string
	for _, f := range pkg.GoFiles {
		n := filepath.Join(".", f)
		appFiles = append(appFiles, n)
	}
	return appFiles, nil
}
开发者ID:suau,项目名称:appengine,代码行数:16,代码来源:aedeploy.go

示例9: FindImports

/*
Scan basepath and find the import'able paths relative to it
*/
func FindImports(basepath string) (Imports, error) {
	set := map[string]bool{} // unique keys
	findImportFn := func(path string, info os.FileInfo, err error) error {
		if err != nil {
			return err
		}
		if info.Mode().IsRegular() && isSourceFile(path) {
			lib := strings.TrimPrefix(filepath.Dir(path), basepath)
			if strings.HasPrefix(lib, "/") {
				lib = strings.TrimPrefix(lib, "/")
			}

			// if the lib string is _not_ in our set and import path is sane
			if _, found := set[lib]; !found && isImportablePath(lib) {
				set[lib] = true
			}
		}
		return nil
	}

	pkgs := Imports{}
	err := filepath.Walk(basepath, findImportFn)
	if err != nil {
		return pkgs, err
	}

	var ctx build.Context = build.Default
	if !strings.HasPrefix(basepath, build.Default.GOROOT) && !strings.HasPrefix(basepath, build.Default.GOPATH) {
		// rather than messing with the build.Default
		ctx = build.Context{
			GOROOT:   build.Default.GOROOT,
			GOPATH:   basepath,
			Compiler: build.Default.Compiler,
			JoinPath: build.Default.JoinPath,
		}
	}

	for lib, _ := range set {
		if pkg, err := ctx.ImportDir(filepath.Join(basepath, lib), 0); err == nil {
			pkgs = append(pkgs, pkg)
		}
	}
	sort.Sort(byImportPath{pkgs})
	return pkgs, nil
}
开发者ID:vbatts,项目名称:golang2pkg,代码行数:48,代码来源:imports.go

示例10: FindAll

// FindAll returns a list of all packages in all of the GOPATH trees
// in the given build context. If prefix is non-empty, only packages
// whose import paths begin with prefix are returned.
func FindAll(prefix string, buildContext build.Context, mode FindMode) (pkgs []*build.Package, err error) {
	have := map[string]bool{
		"builtin": true, // ignore pseudo-package that exists only for documentation
	}
	if !buildContext.CgoEnabled {
		have["runtime/cgo"] = true // ignore during walk
	}

	// TODO(sqs): find cmd packages as well

	var gorootSrcPkg = filepath.Join(buildContext.GOROOT, "src/pkg")

	for _, src := range buildContext.SrcDirs() {
		if src == gorootSrcPkg && mode&IncludeStdlib == 0 {
			continue // skip stdlib
		}
		src = filepath.Clean(src) + string(filepath.Separator)
		start := filepath.Join(src, prefix)
		filepath.Walk(start, func(path string, fi os.FileInfo, err error) error {
			if err != nil || !fi.IsDir() || path == src {
				return nil
			}

			// Avoid .foo, _foo, and testdata directory trees.
			_, elem := filepath.Split(path)
			if strings.HasPrefix(elem, ".") || strings.HasPrefix(elem, "_") || elem == "testdata" {
				return filepath.SkipDir
			}

			name := filepath.ToSlash(path[len(start):])
			if have[name] {
				return nil
			}
			have[name] = true

			pkg, err := buildContext.ImportDir(path, 0)
			if err != nil && strings.Contains(err.Error(), "no Go source files") {
				return nil
			}
			pkgs = append(pkgs, pkg)
			return nil
		})
	}
	return pkgs, nil
}
开发者ID:sourcegraph,项目名称:go-pkgs,代码行数:48,代码来源:pkgs.go

示例11: checkMain

// checkMain verifies that there is a single "main" function.
// It also returns a list of all Go source files in the app.
func checkMain(ctxt *build.Context) (bool, []string, error) {
	pkg, err := ctxt.ImportDir(*rootDir, 0)
	if err != nil {
		return false, nil, fmt.Errorf("unable to analyze source: %v", err)
	}
	if !pkg.IsCommand() {
		errorf("Your app's package needs to be changed from %q to \"main\".\n", pkg.Name)
	}
	// Search for a "func main"
	var hasMain bool
	var appFiles []string
	for _, f := range pkg.GoFiles {
		n := filepath.Join(*rootDir, f)
		appFiles = append(appFiles, n)
		if hasMain, err = readFile(n); err != nil {
			return false, nil, fmt.Errorf("error parsing %q: %v", n, err)
		}
	}
	return hasMain, appFiles, nil
}
开发者ID:Celluliodio,项目名称:flannel,代码行数:22,代码来源:aebundler.go

示例12: imports

// imports returns a map of all import directories (recursively) used by the app.
// The return value maps full directory names to original import names.
func imports(ctxt *build.Context, srcDir string, gopath []string) (map[string]string, error) {
	pkg, err := ctxt.ImportDir(srcDir, 0)
	if err != nil {
		return nil, err
	}

	// Resolve imports, preferring vendored packages, then packages in the GOPATH.
	// Any package that could not be resolved and does not contain a "."
	// is assumed to be part of the standard libarry and therefore ignored.
	// Otherwise, unresolved packages will return an error.
	result := make(map[string]string)
	for _, v := range pkg.Imports {
		src, verr := findVendored(srcDir, v, gopath)
		if verr != nil {
			var perr error
			src, perr = findInGopath(v, gopath)
			if perr != nil {
				if !strings.Contains(v, ".") {
					continue
				}
				return nil, fmt.Errorf("unable to find import %v: %v, %v", v, perr, verr)
			}
		}

		if _, ok := result[src]; ok { // Already processed
			continue
		}
		result[src] = v
		im, err := imports(ctxt, src, gopath)
		if err != nil {
			return nil, fmt.Errorf("unable to parse package %v: %v", src, err)
		}
		for k, v := range im {
			result[k] = v
		}
	}
	return result, nil
}
开发者ID:trythings,项目名称:trythings,代码行数:40,代码来源:aedeploy.go

示例13: build

func (b *builder) build(srcs []*source) (*Package, error) {

	b.pkg.Updated = time.Now().UTC()

	references := make(map[string]bool)
	b.srcs = make(map[string]*source)
	for _, src := range srcs {
		if strings.HasSuffix(src.name, ".go") {
			b.srcs[src.name] = src
		} else {
			addReferences(references, src.data)
		}
	}

	for r := range references {
		b.pkg.References = append(b.pkg.References, r)
	}

	if len(b.srcs) == 0 {
		return b.pkg, nil
	}

	b.fset = token.NewFileSet()
	b.importPaths = make(map[string]map[string]string)

	// Find the package and associated files.

	ctxt := build.Context{
		GOOS:          "linux",
		GOARCH:        "amd64",
		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 b.readDir(dir) },
		OpenFile:      func(path string) (r io.ReadCloser, err error) { return b.openFile(path) },
		Compiler:      "gc",
	}
	pkg, err := ctxt.ImportDir(b.pkg.ImportPath, 0)
	if _, ok := err.(*build.NoGoError); ok {
		return b.pkg, nil
	} else if err != nil {
		b.pkg.Errors = append(b.pkg.Errors, err.Error())
		return b.pkg, nil
	}

	// Parse the Go files

	b.ast = &ast.Package{Name: pkg.Name, Files: make(map[string]*ast.File)}
	if pkg.IsCommand() && b.srcs["doc.go"] != nil {
		file, err := parser.ParseFile(b.fset, "doc.go", b.srcs["doc.go"].data, parser.ParseComments)
		if err == nil && file.Name.Name == "documentation" {
			b.ast.Files["doc.go"] = file
		}
	}
	if len(b.ast.Files) == 0 {
		for _, name := range append(pkg.GoFiles, pkg.CgoFiles...) {
			file, err := parser.ParseFile(b.fset, name, b.srcs[name].data, parser.ParseComments)
			if err != nil {
				b.pkg.Errors = append(b.pkg.Errors, err.Error())
				continue
			}
			b.pkg.Files = append(b.pkg.Files, &File{Name: name, URL: b.srcs[name].browseURL})
			b.pkg.SourceSize += len(b.srcs[name].data)
			b.ast.Files[name] = file
		}
	}

	// Find examples in the test files.

	for _, name := range append(pkg.TestGoFiles, pkg.XTestGoFiles...) {
		file, err := parser.ParseFile(b.fset, name, b.srcs[name].data, parser.ParseComments)
		if err != nil {
			b.pkg.Errors = append(b.pkg.Errors, err.Error())
			continue
		}
		b.pkg.TestFiles = append(b.pkg.TestFiles, &File{Name: name, URL: b.srcs[name].browseURL})
		b.pkg.TestSourceSize += len(b.srcs[name].data)
		b.examples = append(b.examples, doc.Examples(file)...)
	}

	b.vetPackage()

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

	pdoc := doc.New(b.ast, b.pkg.ImportPath, mode)

	b.pkg.Name = pdoc.Name
	b.pkg.Doc = strings.TrimRight(pdoc.Doc, " \t\n\r")
	b.pkg.Synopsis = synopsis(b.pkg.Doc)

	b.pkg.Examples = b.getExamples("")
	b.pkg.IsCmd = pkg.IsCommand()

	b.pkg.Consts = b.values(pdoc.Consts)
//.........这里部分代码省略.........
开发者ID:sbryant,项目名称:gopkgdoc,代码行数:101,代码来源:builder.go

示例14: build

// build generates data from source files.
func (w *walker) build(srcs []*source) (*Package, error) {
	// Set created time.
	w.pdoc.Created = time.Now().UTC()

	// Add source files to walker, I skipped references here.
	w.srcs = make(map[string]*source)
	for _, src := range srcs {
		srcName := strings.ToLower(src.name) // For readme comparation.
		switch {
		case strings.HasSuffix(src.name, ".go"):
			w.srcs[src.name] = src
		case len(w.pdoc.Tag) > 0:
			continue // Only save latest readme.
		case strings.HasPrefix(srcName, "readme_zh") || strings.HasPrefix(srcName, "readme_cn"):
			models.SavePkgDoc(w.pdoc.ImportPath, "zh", src.data)
		case strings.HasPrefix(srcName, "readme"):
			models.SavePkgDoc(w.pdoc.ImportPath, "en", src.data)
		}
	}

	w.fset = token.NewFileSet()

	// Find the package and associated files.
	ctxt := build.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.(*build.NoGoError)
	if err != nil {
		if nogo {
			err = nil
			beego.Info("doc.walker.build -> No Go Source file")
		} else {
			return w.pdoc, errors.New("doc.walker.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 {
			beego.Error("doc.walker.build -> parse go files:", err)
			continue
		}
		w.pdoc.Files = append(w.pdoc.Files, name)
		//w.pdoc.SourceSize += len(w.srcs[name].data)
		files[name] = file
	}

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

	// Find examples in the test files.
	for _, name := range append(bpkg.TestGoFiles, bpkg.XTestGoFiles...) {
		file, err := parser.ParseFile(w.fset, name, w.srcs[name].data, parser.ParseComments)
		if err != nil {
			beego.Error("doc.walker.build -> find examples:", err)
			continue
		}
		//w.pdoc.TestFiles = append(w.pdoc.TestFiles, &File{Name: name, URL: w.srcs[name].browseURL})
		//w.pdoc.TestSourceSize += len(w.srcs[name].data)
		w.examples = append(w.examples, doc.Examples(file)...)
	}

	//w.vetPackage(apkg)

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

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

	w.pdoc.Synopsis = utils.Synopsis(pdoc.Doc)
	pdoc.Doc = strings.TrimRight(pdoc.Doc, " \t\n\r")
	var buf bytes.Buffer
	doc.ToHTML(&buf, pdoc.Doc, nil)
	w.pdoc.Doc = w.pdoc.Doc + "<br />" + buf.String()
	w.pdoc.Doc = strings.Replace(w.pdoc.Doc, "<p>", "<p><b>", 1)
	w.pdoc.Doc = strings.Replace(w.pdoc.Doc, "</p>", "</b></p>", 1)
	w.pdoc.Doc = base32.StdEncoding.EncodeToString([]byte(w.pdoc.Doc))

	w.pdoc.Examples = w.getExamples("")
	w.pdoc.IsCmd = bpkg.IsCommand()
	w.srcLines = make(map[string][]string)
	w.pdoc.Consts = w.values(pdoc.Consts)
	w.pdoc.Funcs = w.funcs(pdoc.Funcs)
//.........这里部分代码省略.........
开发者ID:seacoastboy,项目名称:gowalker,代码行数:101,代码来源:walker.go

示例15: build

// build generates data from source files.
func (w *walker) build(srcs []*source) (*Package, error) {
	// Set created time.
	w.pdoc.Created = time.Now().UTC()

	// Add source files to walker, I skipped references here.
	w.srcs = make(map[string]*source)
	for _, src := range srcs {
		if strings.HasSuffix(src.name, ".go") {
			w.srcs[src.name] = src
		} else if src.name == "doc_zh.md" {
			// Multi-language documentation.
			w.mldocs[src.name] = src
		}
	}

	// Check number of source files.
	if len(w.srcs) == 0 {
		// No source file.
		return w.pdoc, nil
	}

	w.fset = token.NewFileSet()

	// Find the package and associated files.
	ctxt := build.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.
	if _, nogo := err.(*build.NoGoError); err != nil && !nogo {
		return w.pdoc, errors.New("doc.walker.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 {
			beego.Error("doc.walker.build():", err)
			continue
		}
		w.pdoc.Files = append(w.pdoc.Files, name)
		//w.pdoc.SourceSize += len(w.srcs[name].data)
		files[name] = file
	}

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

	// Find examples in the test files.

	/*for _, name := range append(bpkg.TestGoFiles, bpkg.XTestGoFiles...) {
		file, err := parser.ParseFile(w.fset, name, w.srcs[name].data, parser.ParseComments)
		if err != nil {
			w.pdoc.Errors = append(w.pdoc.Errors, err.Error())
			continue
		}
		w.pdoc.TestFiles = append(w.pdoc.TestFiles, &File{Name: name, URL: w.srcs[name].browseURL})
		w.pdoc.TestSourceSize += len(w.srcs[name].data)
		w.examples = append(w.examples, doc.Examples(file)...)
	}*/

	//w.vetPackage(apkg)

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

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

	w.pdoc.Doc = strings.TrimRight(pdoc.Doc, " \t\n\r")
	w.pdoc.Synopsis = utils.Synopsis(w.pdoc.Doc)

	//w.pdoc.Examples = w.getExamples("")
	//w.pdoc.IsCmd = bpkg.IsCommand()
	w.pdoc.GOOS = ctxt.GOOS
	w.pdoc.GOARCH = ctxt.GOARCH

	w.srcLines = make(map[string][]string)
	w.pdoc.Consts = w.values(pdoc.Consts)
	w.pdoc.Funcs = w.funcs(pdoc.Funcs)
	w.pdoc.Types = w.types(pdoc.Types)
	w.pdoc.Vars = w.values(pdoc.Vars)
	//w.pdoc.Notes = w.notes(pdoc.Notes)

	w.pdoc.Imports = bpkg.Imports
	w.pdoc.TestImports = bpkg.TestImports
//.........这里部分代码省略.........
开发者ID:sywxf,项目名称:gowalker,代码行数:101,代码来源:walker.go


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