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


Golang build.IsLocalImport函数代码示例

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


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

示例1: loadPackage

// loadPackage is like loadImport but is used for command-line arguments,
// not for paths found in import statements.  In addition to ordinary import paths,
// loadPackage accepts pseudo-paths beginning with cmd/ to denote commands
// in the Go command directory, as well as paths to those directories.
func loadPackage(arg string, stk *importStack) *Package {
	if build.IsLocalImport(arg) {
		dir := arg
		if !filepath.IsAbs(dir) {
			if abs, err := filepath.Abs(dir); err == nil {
				// interpret relative to current directory
				dir = abs
			}
		}
		if sub, ok := hasSubdir(gorootSrc, dir); ok && strings.HasPrefix(sub, "cmd/") && !strings.Contains(sub[4:], "/") {
			arg = sub
		}
	}
	if strings.HasPrefix(arg, "cmd/") && !strings.Contains(arg[4:], "/") {
		if p := cmdCache[arg]; p != nil {
			return p
		}
		stk.push(arg)
		defer stk.pop()

		bp, err := buildContext.ImportDir(filepath.Join(gorootSrc, arg), 0)
		bp.ImportPath = arg
		bp.Goroot = true
		bp.BinDir = gorootBin
		if gobin != "" {
			bp.BinDir = gobin
		}
		bp.Root = goroot
		bp.SrcRoot = gorootSrc
		p := new(Package)
		cmdCache[arg] = p
		p.load(stk, bp, err)
		if p.Error == nil && p.Name != "main" {
			p.Error = &PackageError{
				ImportStack: stk.copy(),
				Err:         fmt.Sprintf("expected package main but found package %s in %s", p.Name, p.Dir),
			}
		}
		return p
	}

	// Wasn't a command; must be a package.
	// If it is a local import path but names a standard package,
	// we treat it as if the user specified the standard package.
	// This lets you run go test ./ioutil in package io and be
	// referring to io/ioutil rather than a hypothetical import of
	// "./ioutil".
	if build.IsLocalImport(arg) {
		bp, _ := buildContext.ImportDir(filepath.Join(cwd, arg), build.FindOnly)
		if bp.ImportPath != "" && bp.ImportPath != "." {
			arg = bp.ImportPath
		}
	}

	return loadImport(arg, cwd, stk, nil)
}
开发者ID:glycerine,项目名称:llgo,代码行数:60,代码来源:pkg.go

示例2: instrumentPatchable

func (i *Instrumentable) instrumentPatchable(outdir, relpath string, pkg *patch.PatchablePkg, f func(file *patch.PatchableFile) patch.Patches) error {
	path := ""
	if build.IsLocalImport(relpath) {
		path = filepath.Join("locals", relpath)
		path = strings.Replace(path, "..", "__", -1)
	} else if relpath != "" {
		path = filepath.Join("gopath", i.pkg.ImportPath)
	}
	if err := os.MkdirAll(filepath.Join(outdir, path), 0755); err != nil {
		return err
	}
	for filename, file := range pkg.Files {
		if outfile, err := os.Create(filepath.Join(outdir, path, filepath.Base(filename))); err != nil {
			return err
		} else {
			patches := f(file)
			// TODO(elazar): check the relative path from current location (aka relpath, path), to the import path
			// (aka v)
			for _, imp := range file.File.Imports {
				switch v := imp.Path.Value[1 : len(imp.Path.Value)-1]; {
				case v == i.pkg.ImportPath:
					patches = appendNoContradict(patches, patch.Replace(imp.Path, `"."`))
				case !i.relevantImport(v):
					continue
				case build.IsLocalImport(v):
					rel, err := filepath.Rel(path, filepath.Join("locals", v))
					if err != nil {
						return err
					}
					patches = appendNoContradict(patches, patch.Replace(imp.Path, `"./`+rel+`"`))
				default:
					if v == i.name {
						v = ""
					} else {
						v = filepath.Join("gopath", v)
					}
					rel, err := filepath.Rel(path, v)
					if err != nil {
						return err
					}
					patches = appendNoContradict(patches, patch.Replace(imp.Path, `"./`+rel+`"`))
				}
			}
			file.FprintPatched(outfile, file.File, patches)
			if err := outfile.Close(); err != nil {
				return err
			}
		}
	}
	return nil
}
开发者ID:soniah,项目名称:gosloppy,代码行数:51,代码来源:instrument.go

示例3: Import

// Import imports a gc-generated package given its import path, adds the
// corresponding package object to the packages map, and returns the object.
// Local import paths are interpreted relative to the current working directory.
// The packages map must contain all packages already imported.
//
func Import(packages map[string]*types.Package, path string) (pkg *types.Package, err error) {
	// package "unsafe" is handled by the type checker
	if path == "unsafe" {
		panic(`gcimporter.Import called for package "unsafe"`)
	}

	srcDir := "."
	if build.IsLocalImport(path) {
		srcDir, err = os.Getwd()
		if err != nil {
			return
		}
	}

	filename, id := FindPkg(path, srcDir)
	if filename == "" {
		err = fmt.Errorf("can't find import: %s", id)
		return
	}

	// no need to re-import if the package was imported completely before
	if pkg = packages[id]; pkg != nil && pkg.Complete() {
		return
	}

	// open file
	f, err := os.Open(filename)
	if err != nil {
		return
	}
	defer func() {
		f.Close()
		if err != nil {
			// add file name to error
			err = fmt.Errorf("reading export data: %s: %v", filename, err)
		}
	}()

	var hdr string
	buf := bufio.NewReader(f)
	if hdr, err = FindExportData(buf); err != nil {
		return
	}

	switch hdr {
	case "$$\n":
		return ImportData(packages, filename, id, buf)
	case "$$B\n":
		var data []byte
		data, err = ioutil.ReadAll(buf)
		if err == nil {
			_, pkg, err = BImportData(packages, data, path)
			return
		}
	default:
		err = fmt.Errorf("unknown export data header: %q", hdr)
	}

	return
}
开发者ID:danny8002,项目名称:go,代码行数:65,代码来源:gcimporter.go

示例4: importPkg

func (imp *Importer) importPkg(imports map[string]*types.Package, path string) (*types.Package, error) {
	if path == "unsafe" {
		return types.Unsafe, nil
	}

	var (
		srcDir string
		err    error
	)

	if build.IsLocalImport(path) {
		srcDir, err = os.Getwd()
		if err != nil {
			return nil, err
		}
	}

	bp, err := buildCtx.Import(path, srcDir, build.AllowBinary)
	if err != nil {
		return nil, err
	}

	if pkg := imports[path]; pkg != nil && pkg.Complete() {
		return pkg, nil
	}

	buf, err := loadExports(bp)
	if err != nil {
		return nil, err
	}
	_, pkg, err := importer.ImportData(imports, buf)
	return pkg, err
}
开发者ID:rjammala,项目名称:emgo,代码行数:33,代码来源:importer.go

示例5: retrieveImport

func retrieveImport(importMap map[string]bool, path string, dir string) error {
	build.Default.SrcDirs()
	pkg, err := build.Import(path, dir, build.AllowBinary)
	if err != nil {
		if _, ok := err.(*build.NoGoError); ok {
			return nil
		} else {
			return err
		}
	}

	for _, path := range pkg.Imports {
		if isStandardImport(path) {
			continue
		}
		if importMap[path] {
			continue
		}

		if !build.IsLocalImport(path) {
			importMap[path] = true
		}

		err := retrieveImport(importMap, path, pkg.Dir)
		if err != nil {
			return err
		}
	}
	return nil
}
开发者ID:okzk,项目名称:gopathing,代码行数:30,代码来源:main.go

示例6: ImportPaths

// ImportPaths returns the import paths to use for the given command line.
func ImportPaths(args []string) ([]string, []error) {
	args = ImportPathsNoDotExpansion(args)
	var out []string
	var errs []error
	for _, a := range args {
		if strings.Contains(a, "...") {
			if build.IsLocalImport(a) {
				all, err := AllPackagesInFS(a)
				out = append(out, all...)
				if err != nil {
					errs = append(errs, err)
				}
			} else {
				all, err := AllPackages(a)
				out = append(out, all...)
				if err != nil {
					errs = append(errs, err)
				}
			}
			continue
		}
		out = append(out, a)
	}
	return out, errs
}
开发者ID:tcard,项目名称:sgo,代码行数:26,代码来源:importpaths.go

示例7: scanDirectory

func scanDirectory(path, srcDir string) (ret []string, err error) {
	pkg, err := build.Import(path, srcDir, build.AllowBinary)
	if err != nil {
		return ret, err
	}

	for _, imp := range pkg.Imports {
		switch {
		case isStandardImport(imp):
			// Ignore standard packages
		case !build.IsLocalImport(imp):
			// Add the external package
			ret = appendPkg(ret, imp)
			fallthrough
		default:
			// Does the recursive walk
			pkgs, err := scanDirectory(imp, pkg.Dir)
			if err != nil {
				return ret, err
			}
			ret = appendPkgs(ret, pkgs)
		}
	}

	return ret, err
}
开发者ID:wingdog,项目名称:gom,代码行数:26,代码来源:gen.go

示例8: localize

func localize(pkg string) string {
	if build.IsLocalImport(pkg) {
		// TODO(elazar): check if `import "./a/../a"` is equivalent to "./a"
		pkg := filepath.Clean(pkg)
		return filepath.Join(".", "locals", strings.Replace(pkg, ".", "_", -1))
	}
	return filepath.Join("gopath", pkg)
}
开发者ID:soniah,项目名称:gosloppy,代码行数:8,代码来源:instrument.go

示例9: relevantImport

// relevantImport will determine whether this import should be instrumented as well
func (i *Instrumentable) relevantImport(imp string) bool {
	if i.basepkg == "*" || build.IsLocalImport(imp) {
		return true
	} else if i.IsInGopath() || i.basepkg != "" {
		return filepath.HasPrefix(imp, i.basepkg) || filepath.HasPrefix(i.basepkg, imp)
	}
	return false
}
开发者ID:soniah,项目名称:gosloppy,代码行数:9,代码来源:instrument.go

示例10: loadPackage

// loadPackage recursively resolves path and its imports and if successful
// stores those packages in the Context's internal package cache.
func loadPackage(c *Context, stack []string, path string) (*Package, error) {
	if build.IsLocalImport(path) {
		// sanity check
		return nil, fmt.Errorf("%q is not a valid import path", path)
	}
	if pkg, ok := c.pkgs[path]; ok {
		// already loaded, just return
		return pkg, nil
	}

	push := func(path string) {
		stack = append(stack, path)
	}
	pop := func(path string) {
		stack = stack[:len(stack)-1]
	}
	onStack := func(path string) bool {
		for _, p := range stack {
			if p == path {
				return true
			}
		}
		return false
	}

	p, err := c.Context.Import(path, c.Projectdir(), 0)
	if err != nil {
		return nil, err
	}

	standard := p.Goroot && p.ImportPath != "" && !strings.Contains(p.ImportPath, ".")
	push(path)
	var stale bool
	for _, i := range p.Imports {
		if c.shouldignore(i) {
			continue
		}
		if onStack(i) {
			push(i)
			return nil, fmt.Errorf("import cycle detected: %s", strings.Join(stack, " -> "))
		}
		pkg, err := loadPackage(c, stack, i)
		if err != nil {
			return nil, err
		}
		stale = stale || pkg.Stale
	}
	pop(path)

	pkg := Package{
		Context:  c,
		Package:  p,
		Standard: standard,
	}
	pkg.Stale = stale || isStale(&pkg)
	c.pkgs[path] = &pkg
	return &pkg, nil
}
开发者ID:kalafut,项目名称:gb,代码行数:60,代码来源:package.go

示例11: loadPackage

// loadPackage recursively resolves path and its imports and if successful
// stores those packages in the Context's internal package cache.
func (c *Context) loadPackage(stack []string, path string) (*Package, error) {
	if build.IsLocalImport(path) {
		// sanity check
		return nil, fmt.Errorf("%q is not a valid import path", path)
	}
	if pkg, ok := c.pkgs[path]; ok {
		// already loaded, just return
		return pkg, nil
	}

	push := func(path string) {
		stack = append(stack, path)
	}
	pop := func(path string) {
		stack = stack[:len(stack)-1]
	}
	onStack := func(path string) bool {
		for _, p := range stack {
			if p == path {
				return true
			}
		}
		return false
	}

	p, err := c.Context.Import(path, c.Projectdir(), 0)
	if err != nil {
		return nil, err
	}
	push(path)
	var stale bool
	for _, i := range p.Imports {
		if Stdlib[i] {
			continue
		}
		if onStack(i) {
			push(i)
			return nil, fmt.Errorf("import cycle detected: %s", strings.Join(stack, " -> "))
		}
		pkg, err := c.loadPackage(stack, i)
		if err != nil {
			return nil, err
		}
		stale = stale || pkg.Stale
	}
	pop(path)

	pkg := Package{
		Context: c,
		Package: p,
	}
	pkg.Stale = stale || isStale(&pkg)
	Debugf("loadPackage: %v %v (%v)", path, pkg.Stale, pkg.Dir)
	c.pkgs[path] = &pkg
	return &pkg, nil
}
开发者ID:acasajus,项目名称:gb,代码行数:58,代码来源:context.go

示例12: main

func main() {
	_ = go11tag
	flag.Usage = usage
	flag.Parse()
	log.SetFlags(0)

	args := flag.Args()
	if len(args) < 1 {
		usage()
	}

	if args[0] == "help" {
		help(args[1:])
		return
	}

	// Diagnose common mistake: GOPATH==GOROOT.
	// This setting is equivalent to not setting GOPATH at all,
	// which is not what most people want when they do it.
	if gopath := os.Getenv("GOPATH"); gopath == runtime.GOROOT() {
		fmt.Fprintf(os.Stderr, "warning: GOPATH set to GOROOT (%s) has no effect\n", gopath)
	} else {
		for _, p := range filepath.SplitList(gopath) {
			// Note: using HasPrefix instead of Contains because a ~ can appear
			// in the middle of directory elements, such as /tmp/git-1.8.2~rc3
			// or C:\PROGRA~1. Only ~ as a path prefix has meaning to the shell.
			if strings.HasPrefix(p, "~") {
				fmt.Fprintf(os.Stderr, "go: GOPATH entry cannot start with shell metacharacter '~': %q\n", p)
				os.Exit(2)
			}
			if build.IsLocalImport(p) {
				fmt.Fprintf(os.Stderr, "go: GOPATH entry is relative; must be absolute path: %q.\nRun 'go help gopath' for usage.\n", p)
				os.Exit(2)
			}
		}
	}

	for _, cmd := range commands {
		if cmd.Name() == args[0] && cmd.Run != nil {
			cmd.Flag.Usage = func() { cmd.Usage() }
			if cmd.CustomFlags {
				args = args[1:]
			} else {
				cmd.Flag.Parse(args[1:])
				args = cmd.Flag.Args()
			}
			cmd.Run(cmd, args)
			exit()
			return
		}
	}

	fmt.Fprintf(os.Stderr, "go: unknown subcommand %q\nRun 'go help' for usage.\n", args[0])
	setExitStatus(2)
	exit()
}
开发者ID:hfeeki,项目名称:golang,代码行数:56,代码来源:main.go

示例13: doimport

func (i *Instrumentable) doimport(pkg string) (*Instrumentable, error) {
	if build.IsLocalImport(pkg) {
		return ImportDir(i.basepkg, filepath.Join(i.pkg.Dir, pkg))
	}
	// TODO: A bit hackish
	r, err := Import(i.basepkg, pkg)
	if err != nil {
		return r, err
	}
	r.name = i.name
	return r, nil
}
开发者ID:soniah,项目名称:gosloppy,代码行数:12,代码来源:instrument.go

示例14: loadImport

// loadImport scans the directory named by path, which must be an import path,
// but possibly a local import path (an absolute file system path or one beginning
// with ./ or ../).  A local relative path is interpreted relative to srcDir.
// It returns a *Package describing the package found in that directory.
func loadImport(path string, srcDir string, stk *importStack, importPos []token.Position) *Package {
	stk.push(path)
	defer stk.pop()

	// Determine canonical identifier for this package.
	// For a local import the identifier is the pseudo-import path
	// we create from the full directory to the package.
	// Otherwise it is the usual import path.
	importPath := path
	isLocal := build.IsLocalImport(path)
	if isLocal {
		importPath = dirToImportPath(filepath.Join(srcDir, path))
	}
	if p := packageCache[importPath]; p != nil {
		if perr := disallowInternal(srcDir, p, stk); perr != p {
			return perr
		}
		return reusePackage(p, stk)
	}

	p := new(Package)
	p.local = isLocal
	p.ImportPath = importPath
	packageCache[importPath] = p

	// Load package.
	// Import always returns bp != nil, even if an error occurs,
	// in order to return partial information.
	//
	// TODO: After Go 1, decide when to pass build.AllowBinary here.
	// See issue 3268 for mistakes to avoid.
	bp, err := buildContext.Import(path, srcDir, build.ImportComment)
	bp.ImportPath = importPath
	if gobin != "" {
		bp.BinDir = gobin
	}
	if err == nil && !isLocal && bp.ImportComment != "" && bp.ImportComment != path {
		err = fmt.Errorf("code in directory %s expects import %q", bp.Dir, bp.ImportComment)
	}
	p.load(stk, bp, err)
	if p.Error != nil && len(importPos) > 0 {
		pos := importPos[0]
		pos.Filename = shortPath(pos.Filename)
		p.Error.Pos = pos.String()
	}

	if perr := disallowInternal(srcDir, p, stk); perr != p {
		return perr
	}

	return p
}
开发者ID:glycerine,项目名称:llgo,代码行数:56,代码来源:pkg.go

示例15: main

func main() {
	flag.Usage = usage
	flag.Parse()
	log.SetFlags(0)

	args := flag.Args()
	if len(args) < 1 {
		usage()
	}

	if args[0] == "help" {
		help(args[1:])
		return
	}

	// Diagnose common mistake: GOPATH==GOROOT.
	// This setting is equivalent to not setting GOPATH at all,
	// which is not what most people want when they do it.
	if gopath := os.Getenv("GOPATH"); gopath == runtime.GOROOT() {
		fmt.Fprintf(os.Stderr, "warning: GOPATH set to GOROOT (%s) has no effect\n", gopath)
	} else {
		for _, p := range filepath.SplitList(gopath) {
			if strings.Contains(p, "~") && runtime.GOOS != "windows" {
				fmt.Fprintf(os.Stderr, "go: GOPATH entry cannot contain shell metacharacter '~': %q\n", p)
				os.Exit(2)
			}
			if build.IsLocalImport(p) {
				fmt.Fprintf(os.Stderr, "go: GOPATH entry is relative; must be absolute path: %q.\nRun 'go help gopath' for usage.\n", p)
				os.Exit(2)
			}
		}
	}

	for _, cmd := range commands {
		if cmd.Name() == args[0] && cmd.Run != nil {
			cmd.Flag.Usage = func() { cmd.Usage() }
			if cmd.CustomFlags {
				args = args[1:]
			} else {
				cmd.Flag.Parse(args[1:])
				args = cmd.Flag.Args()
			}
			cmd.Run(cmd, args)
			exit()
			return
		}
	}

	fmt.Fprintf(os.Stderr, "go: unknown subcommand %q\nRun 'go help' for usage.\n", args[0])
	setExitStatus(2)
	exit()
}
开发者ID:serge-hulne,项目名称:golang,代码行数:52,代码来源:main.go


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