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


Golang Context.Import方法代码示例

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


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

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

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

示例3: ContainingPackage

// ContainingPackage returns the package containing filename.
//
// If filename is not absolute, it is interpreted relative to working directory dir.
// All I/O is via the build context's file system interface, if any.
//
// The '...Files []string' fields of the resulting build.Package are not
// populated (build.FindOnly mode).
//
// TODO(adonovan): call this from oracle when the tree thaws.
//
func ContainingPackage(ctxt *build.Context, dir, filename string) (*build.Package, error) {
	if !IsAbsPath(ctxt, filename) {
		filename = JoinPath(ctxt, dir, filename)
	}

	// We must not assume the file tree uses
	// "/" always,
	// `\` always,
	// or os.PathSeparator (which varies by platform),
	// but to make any progress, we are forced to assume that
	// paths will not use `\` unless the PathSeparator
	// is also `\`, thus we can rely on filepath.ToSlash for some sanity.

	dirSlash := path.Dir(filepath.ToSlash(filename)) + "/"

	// We assume that no source root (GOPATH[i] or GOROOT) contains any other.
	for _, srcdir := range ctxt.SrcDirs() {
		srcdirSlash := filepath.ToSlash(srcdir) + "/"
		if dirHasPrefix(dirSlash, srcdirSlash) {
			importPath := dirSlash[len(srcdirSlash) : len(dirSlash)-len("/")]
			return ctxt.Import(importPath, dir, build.FindOnly)
		}
	}

	return nil, fmt.Errorf("can't find package containing %s", filename)
}
开发者ID:ColourboxDevelopment,项目名称:aws-sdk-go,代码行数:36,代码来源:util.go

示例4: subpackages

// subpackages returns the set of packages in the given srcDir whose
// import paths start with dir.
func subpackages(ctxt *build.Context, srcDir string, dir string) map[string]bool {
	subs := map[string]bool{dir: true}

	// Find all packages under srcDir whose import paths start with dir.
	buildutil.ForEachPackage(ctxt, func(pkg string, err error) {
		if err != nil {
			log.Fatalf("unexpected error in ForEachPackage: %v", err)
		}

		if !strings.HasPrefix(pkg, path.Join(dir, "")) {
			return
		}

		p, err := ctxt.Import(pkg, "", build.FindOnly)
		if err != nil {
			log.Fatalf("unexpected: package %s can not be located by build context: %s", pkg, err)
		}
		if p.SrcRoot == "" {
			log.Fatalf("unexpected: could not determine srcDir for package %s: %s", pkg, err)
		}
		if p.SrcRoot != srcDir {
			return
		}

		subs[pkg] = true
	})

	return subs
}
开发者ID:Lane391,项目名称:golangdemo,代码行数:31,代码来源:mvpkg.go

示例5: Import

//Import imports a package.
//
//path is run through ToImport.
//
//If ctx is nil, the default context is used.
//
//N.B. we require a pointer to a build.Context for caching.
//Two build contexts with identical values that are not represented
//by the same pointer will have all packages imported by them
//cached separately.
func Import(ctx *build.Context, path string) (*Package, error) {
	if ctx == nil {
		ctx = defaultctx
	}
	root, path, err := ToImport(path)
	if err != nil {
		return nil, err
	}

	ident := ident{ctx, path}
	if pkg := pkgget(ident); pkg != nil {
		return pkg, nil
	}

	p, err := ctx.Import(path, root, 0)
	if err != nil {
		return nil, err
	}

	pkg := &Package{
		Context: ctx,
		Build:   p,
	}
	pkgset(ident, pkg)

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

示例6: defaultFindPackage

// defaultFindPackage locates the specified (possibly empty) package
// using go/build logic.  It returns an error if not found.
func defaultFindPackage(ctxt *build.Context, path string) (*build.Package, error) {
	// Import(srcDir="") disables local imports, e.g. import "./foo".
	bp, err := ctxt.Import(path, "", 0)
	if _, ok := err.(*build.NoGoError); ok {
		return bp, nil // empty directory is not an error
	}
	return bp, err
}
开发者ID:Lane391,项目名称:golangdemo,代码行数:10,代码来源:loader.go

示例7: find_global_file

// find_global_file returns the file path of the compiled package corresponding to the specified
// import, and a boolean stating whether such path is valid.
// TODO: Return only one value, possibly empty string if not found.
func find_global_file(imp string, context build.Context) (string, bool) {
	// gocode synthetically generates the builtin package
	// "unsafe", since the "unsafe.a" package doesn't really exist.
	// Thus, when the user request for the package "unsafe" we
	// would return synthetic global file that would be used
	// just as a key name to find this synthetic package
	if imp == "unsafe" {
		return "unsafe", true
	}

	pkgfile := fmt.Sprintf("%s.a", imp)

	// if lib-path is defined, use it
	if g_config.LibPath != "" {
		for _, p := range filepath.SplitList(g_config.LibPath) {
			pkg_path := filepath.Join(p, pkgfile)
			if file_exists(pkg_path) {
				log_found_package_maybe(imp, pkg_path)
				return pkg_path, true
			}
			// Also check the relevant pkg/OS_ARCH dir for the libpath, if provided.
			pkgdir := fmt.Sprintf("%s_%s", context.GOOS, context.GOARCH)
			pkg_path = filepath.Join(p, "pkg", pkgdir, pkgfile)
			if file_exists(pkg_path) {
				log_found_package_maybe(imp, pkg_path)
				return pkg_path, true
			}
			// Also check the relevant pkg/OS/ARCH dir for the libpath, if provided.
			pkg_path = filepath.Join(p, "pkg", context.GOOS, context.GOARCH, pkgfile)
			if file_exists(pkg_path) {
				log_found_package_maybe(imp, pkg_path)
				return pkg_path, true
			}
		}
	}

	p, err := context.Import(imp, "", build.AllowBinary|build.FindOnly)
	if err == nil {
		if g_config.Autobuild {
			err = autobuild(p)
			if err != nil && *g_debug {
				log.Printf("Autobuild error: %s\n", err)
			}
		}
		if file_exists(p.PkgObj) {
			log_found_package_maybe(imp, p.PkgObj)
			return p.PkgObj, true
		}
	}

	if *g_debug {
		log.Printf("Import path %q was not resolved\n", imp)
		log.Println("Gocode's build context is:")
		log_build_context(context)
	}
	return "", false
}
开发者ID:JasonOldWoo,项目名称:gocode,代码行数:60,代码来源:declcache.go

示例8: parseRuntime

// importRuntime locates the the runtime package and parses its files
// to *ast.Files. This is used to generate runtime type structures.
func parseRuntime(buildctx *build.Context, fset *token.FileSet) ([]*ast.File, error) {
	buildpkg, err := buildctx.Import("github.com/go-llvm/llgo/pkg/runtime", "", 0)
	if err != nil {
		return nil, err
	}
	filenames := make([]string, len(buildpkg.GoFiles))
	for i, f := range buildpkg.GoFiles {
		filenames[i] = path.Join(buildpkg.Dir, f)
	}
	return parseFiles(fset, filenames)
}
开发者ID:rvedam,项目名称:llgo,代码行数:13,代码来源:runtime.go

示例9: findPackageMember

// findPackageMember returns the type and position of the declaration of
// pkg.member by loading and parsing the files of that package.
// srcdir is the directory in which the import appears.
func findPackageMember(ctxt *build.Context, fset *token.FileSet, srcdir, pkg, member string) (token.Token, token.Pos, error) {
	bp, err := ctxt.Import(pkg, srcdir, 0)
	if err != nil {
		return 0, token.NoPos, err // no files for package
	}

	// TODO(adonovan): opt: parallelize.
	for _, fname := range bp.GoFiles {
		filename := filepath.Join(bp.Dir, fname)

		// Parse the file, opening it the file via the build.Context
		// so that we observe the effects of the -modified flag.
		f, _ := buildutil.ParseFile(fset, ctxt, nil, ".", filename, parser.Mode(0))
		if f == nil {
			continue
		}

		// Find a package-level decl called 'member'.
		for _, decl := range f.Decls {
			switch decl := decl.(type) {
			case *ast.GenDecl:
				for _, spec := range decl.Specs {
					switch spec := spec.(type) {
					case *ast.ValueSpec:
						// const or var
						for _, id := range spec.Names {
							if id.Name == member {
								return decl.Tok, id.Pos(), nil
							}
						}
					case *ast.TypeSpec:
						if spec.Name.Name == member {
							return token.TYPE, spec.Name.Pos(), nil
						}
					case *ast.AliasSpec:
						if spec.Name.Name == member {
							return decl.Tok, spec.Name.Pos(), nil
						}
					}
				}
			case *ast.FuncDecl:
				if decl.Recv == nil && decl.Name.Name == member {
					return token.FUNC, decl.Name.Pos(), nil
				}
			}
		}
	}

	return 0, token.NoPos, fmt.Errorf("couldn't find declaration of %s in %q", member, pkg)
}
开发者ID:syreclabs,项目名称:go-tools,代码行数:53,代码来源:definition18.go

示例10: explort

func explort(ctx build.Context, pkg *build.Package, visited map[string]bool) {
	for _, packageName := range pkg.Imports {
		if !visited[packageName] {
			visited[packageName] = true
			if *verbose || strings.Contains(packageName, ".") {
				fmt.Printf("%s\n", packageName)
			}
			if ! (packageName == "C") {
				child, err := ctx.Import(packageName, pkg.Dir, build.AllowBinary)
				if err != nil {
					log.Fatalf("error on import: %s", err);
				}					
				explort(ctx, child, visited)
			}
		}
	}
}
开发者ID:brianm,项目名称:godeps,代码行数:17,代码来源:main.go

示例11: completePackageArg

func completePackageArg(ctx *build.Context, cwd string, src io.Reader, arg string) (completions []string) {
	switch {
	case arg == ".":
		completions = []string{"./", "../"}
	case arg == "..":
		completions = []string{"../"}
	case strings.HasPrefix(arg, "."):
		// Complete using relative directory.
		bpkg, err := ctx.Import(".", cwd, build.FindOnly)
		if err != nil {
			return nil
		}
		dir, name := path.Split(arg)
		fis, err := buildutil.ReadDir(ctx, buildutil.JoinPath(ctx, bpkg.Dir, dir))
		if err != nil {
			return nil
		}
		for _, fi := range fis {
			if !fi.IsDir() || strings.HasPrefix(fi.Name(), ".") {
				continue
			}
			if strings.HasPrefix(fi.Name(), name) {
				completions = append(completions, path.Join(dir, fi.Name())+"/")
			}
		}
	case strings.HasPrefix(arg, "/"):
		// Complete using full import path.
		completions = completePackageArgByPath(ctx, cwd, arg)
	default:
		// Complete with package names imported in current file.
		for n := range readImports(cwd, src) {
			if strings.HasPrefix(n, arg) {
				completions = append(completions, n)
			}
		}
	}
	if len(completions) == 0 {
		completions = []string{arg}
	}
	sort.Strings(completions)
	return completions
}
开发者ID:garyburd,项目名称:vigor,代码行数:42,代码来源:args.go

示例12: importer

func importer(ctx *build.Context, srcDir string, vendor map[string]string) ast.Importer {
	return func(imports map[string]*ast.Object, importPath string) (*ast.Object, error) {
		pkg := imports[importPath]
		if pkg != nil {
			return pkg, nil
		}

		var name string
		bpkg, err := ctx.Import(importPath, srcDir, 0)
		if err != nil {
			name = guessPackageNameFromPath(importPath)
		} else {
			name = bpkg.Name
			vendor[importPath] = bpkg.ImportPath
		}

		pkg = ast.NewObj(ast.Pkg, name)
		pkg.Data = ast.NewScope(nil)
		imports[importPath] = pkg
		return pkg, nil
	}
}
开发者ID:garyburd,项目名称:vigor,代码行数:22,代码来源:loader.go

示例13: MakeGoBuildLoader

// MakeGoBuildLoader returns an implementation of the SourceLoader
// function prototype that locates packages using the go/build
// libraries.  It may return nil upon gross misconfiguration
// (e.g. os.Getwd() failed).
//
// ctxt specifies the go/build.Context to use; if nil, the default
// Context is used.
//
func MakeGoBuildLoader(ctxt *build.Context) SourceLoader {
	srcDir, err := os.Getwd()
	if err != nil {
		return nil // serious misconfiguration
	}
	if ctxt == nil {
		ctxt = &build.Default
	}
	return func(fset *token.FileSet, path string) (files []*ast.File, err error) {
		// TODO(adonovan): fix: Do we need cwd? Shouldn't
		// ImportDir(path) / $GOROOT suffice?
		bp, err := ctxt.Import(path, srcDir, 0)
		if err != nil {
			return // import failed
		}
		files, err = ParseFiles(fset, bp.Dir, bp.GoFiles...)
		if err != nil {
			return nil, err
		}
		return
	}
}
开发者ID:pombredanne,项目名称:go.tools,代码行数:30,代码来源:importer.go

示例14: Build

// Build scans the specified Go workspace and builds the forward and
// reverse import dependency graphs for all its packages.
// It also returns a mapping from canonical import paths to errors for packages
// whose loading was not entirely successful.
// A package may appear in the graph and in the errors mapping.
// All package paths are canonical and may contain "/vendor/".
func Build(ctxt *build.Context) (forward, reverse Graph, errors map[string]error) {
	type importEdge struct {
		from, to string
	}
	type pathError struct {
		path string
		err  error
	}

	ch := make(chan interface{})

	go func() {
		sema := make(chan int, 20) // I/O concurrency limiting semaphore
		var wg sync.WaitGroup
		buildutil.ForEachPackage(ctxt, func(path string, err error) {
			if err != nil {
				ch <- pathError{path, err}
				return
			}

			wg.Add(1)
			go func() {
				defer wg.Done()

				sema <- 1
				bp, err := ctxt.Import(path, "", 0)
				<-sema

				if err != nil {
					if _, ok := err.(*build.NoGoError); ok {
						// empty directory is not an error
					} else {
						ch <- pathError{path, err}
					}
					// Even in error cases, Import usually returns a package.
				}

				// absolutize resolves an import path relative
				// to the current package bp.
				// The absolute form may contain "vendor".
				//
				// The vendoring feature slows down Build by 3×.
				// Here are timings from a 1400 package workspace:
				//    1100ms: current code (with vendor check)
				//     880ms: with a nonblocking cache around ctxt.IsDir
				//     840ms: nonblocking cache with duplicate suppression
				//     340ms: original code (no vendor check)
				// TODO(adonovan): optimize, somehow.
				memo := make(map[string]string)
				absolutize := func(path string) string {
					canon, ok := memo[path]
					if !ok {
						sema <- 1
						bp2, _ := ctxt.Import(path, bp.Dir, build.FindOnly)
						<-sema

						if bp2 != nil {
							canon = bp2.ImportPath
						} else {
							canon = path
						}
						memo[path] = canon
					}
					return canon
				}

				if bp != nil {
					for _, imp := range bp.Imports {
						ch <- importEdge{path, absolutize(imp)}
					}
					for _, imp := range bp.TestImports {
						ch <- importEdge{path, absolutize(imp)}
					}
					for _, imp := range bp.XTestImports {
						ch <- importEdge{path, absolutize(imp)}
					}
				}

			}()
		})
		wg.Wait()
		close(ch)
	}()

	forward = make(Graph)
	reverse = make(Graph)

	for e := range ch {
		switch e := e.(type) {
		case pathError:
			if errors == nil {
				errors = make(map[string]error)
			}
			errors[e.path] = e.err
//.........这里部分代码省略.........
开发者ID:ChloeTigre,项目名称:golang-tools,代码行数:101,代码来源:graph.go

示例15: loadPackage

// loadPackage returns details about the Go package named by the import
// path, interpreting local import paths relative to the srcDir directory.
func loadPackage(ctx *build.Context, importPath string, srcDir string, flags int) (*pkg, error) {
	bpkg, err := ctx.Import(importPath, srcDir, build.ImportComment)
	if _, ok := err.(*build.NoGoError); ok {
		return &pkg{Build: bpkg}, nil
	}
	if err != nil {
		return nil, err
	}

	pkg := &pkg{
		FSet:  token.NewFileSet(),
		Build: bpkg,
	}

	files := make(map[string]*ast.File)
	for _, name := range append(pkg.Build.GoFiles, pkg.Build.CgoFiles...) {
		file, err := pkg.parseFile(ctx, name)
		if err != nil {
			pkg.Errors = append(pkg.Errors, err)
			continue
		}
		files[name] = file
	}

	vendor := make(map[string]string)
	pkg.AST, _ = ast.NewPackage(pkg.FSet, files, importer(ctx, bpkg.Dir, vendor), nil)

	if flags&loadPackageFixVendor != 0 {
		for _, f := range pkg.AST.Files {
			for _, i := range f.Imports {
				if lit := i.Path; lit != nil {
					if s, err := strconv.Unquote(lit.Value); err != nil {
						if p, ok := vendor[s]; ok {
							lit.Value = strconv.Quote(p)
						}
					}
				}
			}
		}
	}

	if flags&loadPackageDoc != 0 {
		mode := godoc.Mode(0)
		if pkg.Build.ImportPath == "builtin" || flags&loadPackageUnexported != 0 {
			mode |= godoc.AllDecls
		}
		pkg.GoDoc = godoc.New(pkg.AST, pkg.Build.ImportPath, mode)
		if pkg.Build.ImportPath == "builtin" {
			for _, t := range pkg.GoDoc.Types {
				pkg.GoDoc.Funcs = append(pkg.GoDoc.Funcs, t.Funcs...)
				t.Funcs = nil
			}
			sort.Sort(byFuncName(pkg.GoDoc.Funcs))
		}
	}

	if flags&loadPackageExamples != 0 {
		for _, name := range append(pkg.Build.TestGoFiles, pkg.Build.XTestGoFiles...) {
			file, err := pkg.parseFile(ctx, name)
			if err != nil {
				pkg.Errors = append(pkg.Errors, err)
				continue
			}
			pkg.Examples = append(pkg.Examples, godoc.Examples(file)...)
		}
	}

	return pkg, nil
}
开发者ID:garyburd,项目名称:vigor,代码行数:71,代码来源:loader.go


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