• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Golang build.ImportDir函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: rewriteSubcommand

func rewriteSubcommand(args []string, opts *rewriteOptions) {
	st := new(rewriteState)
	if len(args) > 0 {
		for _, v := range args {
			if pkg, err := build.ImportDir(v, 0); err == nil {
				rewritePackage(pkg, st, opts)
				continue
			}
			pkg, err := build.Import(v, "", 0)
			if err != nil {
				log.Printf("error importing %s: %s", v, err)
				continue
			}
			rewritePackage(pkg, st, opts)
		}
	} else {
		abs, err := filepath.Abs(".")
		if err != nil {
			panic(err)
		}
		pkg, err := build.ImportDir(abs, 0)
		if err != nil {
			log.Fatalf("error importing %s: %s", abs, err)
		}
		rewritePackage(pkg, st, opts)
	}
}
开发者ID:rainycape,项目名称:gopkgs,代码行数:27,代码来源:rewrite.go


示例2: 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) { // TODO Call to build.
		dir := arg
		if !filepath.IsAbs(dir) {
			if abs, err := filepath.Abs(dir); err == nil {
				// interpret relative to current directory
				dir = abs
			}
		}
		// Map gorootSrc to Odoo
		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 := build.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, _ := build.ImportDir(filepath.Join(cwd, arg), build.FindOnly)
		if bp.ImportPath != "" && bp.ImportPath != "." {
			arg = bp.ImportPath
		}
	}

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


示例3: ImportDir

// ImportDir gives a single instrumentable golang package. See Import.
func ImportDir(basepkg, pkgname string) (*Instrumentable, error) {
	pkg, err := build.ImportDir(pkgname, 0)
	if err != nil {
		return nil, err
	}
	return &Instrumentable{pkg, basepkg, pkgname}, nil
}
开发者ID:soniah,项目名称:gosloppy,代码行数:8,代码来源:instrument.go


示例4: FindRepos

func FindRepos(from string) ([]Dependency, error) {
	pkg, err := build.ImportDir(from, 0)
	if err != nil {
		return nil, fmt.Errorf("unable to load package at %s: %s", from, err)
	}

	imports := make(map[string]*build.Package)
	err = findAllImports(pkg, imports)
	if err != nil {
		return nil, err
	}
	delete(imports, pkg.Dir)

	repos := make(map[string]Dependency)
	for _, val := range imports {
		if !val.Goroot {
			repo, err := FindRepo(val)
			if err != nil {
				return nil, err
			}
			repos[repo.Root()] = repo
		}
	}

	rs := make([]Dependency, 0, 0)
	for _, val := range repos {
		rs = append(rs, val)
	}

	return rs, nil
}
开发者ID:CadeLaRen,项目名称:gov,代码行数:31,代码来源:core.go


示例5: loadExportsGoPath

func loadExportsGoPath(dir string) map[string]bool {
	exports := make(map[string]bool)
	buildPkg, err := build.ImportDir(dir, 0)
	if err != nil {
		if strings.Contains(err.Error(), "no buildable Go source files in") {
			return nil
		}
		fmt.Fprintf(os.Stderr, "could not import %q: %v", dir, err)
		return nil
	}
	fset := token.NewFileSet()
	for _, file := range buildPkg.GoFiles {
		f, err := parser.ParseFile(fset, filepath.Join(dir, file), nil, 0)
		if err != nil {
			fmt.Fprintf(os.Stderr, "could not parse %q: %v", file, err)
			continue
		}
		for name := range f.Scope.Objects {
			if ast.IsExported(name) {
				exports[name] = true
			}
		}
	}
	return exports
}
开发者ID:Karthikvb,项目名称:15640_projects,代码行数:25,代码来源:fix.go


示例6: DirToImport

// DirToImport converts a directory path on the local machine to a
// Go import path (usually relative to the $GOPATH/src directory)
//
// For example,
//     /Users/user/workspace/Go/github.com/momchil-atanasov/gostub
// will be converted to
//     github.com/momchil-atanasov/gostub
// should GOPATH include the location
//     /Users/user/workspace/Go
func DirToImport(p string) (string, error) {
	pkg, err := build.ImportDir(p, build.FindOnly)
	if err != nil {
		return "", err
	}
	return pkg.ImportPath, nil
}
开发者ID:momchil-atanasov,项目名称:gostub,代码行数:16,代码来源:gopath.go


示例7: bakeCommand

func bakeCommand(_ *command.Args, opts *bakeOptions) error {
	extensions := []string{".html", ".css", ".js"}
	if opts.Dir == "" {
		return errors.New("dir can't be empty")
	}
	if opts.Name == "" {
		base := filepath.Base(opts.Dir)
		if opts.VFS {
			opts.Name = base + "FS"
		} else {
			opts.Name = base + "Data"
		}
	}
	if opts.Out == "" {
		opts.Out = filepath.Base(opts.Dir) + "_baked.go"
	}
	// go ignores files starting with _
	opts.Out = strings.TrimLeft(opts.Out, "_")
	extensions = append(extensions, strings.Split(opts.Extensions, ",")...)
	var buf bytes.Buffer
	odir := filepath.Dir(opts.Out)
	p, err := build.ImportDir(odir, 0)
	if err == nil {
		buf.WriteString(fmt.Sprintf("package %s\n", p.Name))
	}
	buf.WriteString(genutil.AutogenString())
	if err := writeBakedFSCode(&buf, opts, extensions); err != nil {
		return err
	}
	if err := genutil.WriteAutogen(opts.Out, buf.Bytes()); err != nil {
		return err
	}
	log.Debugf("Assets written to %s (%d bytes)", opts.Out, buf.Len())
	return nil
}
开发者ID:rainycape,项目名称:gondola,代码行数:35,代码来源:bake.go


示例8: ListenForever

func (self *Packager) ListenForever() {
	for {
		incoming := <-self.in
		packages := map[string]*Package{} // key: Folder path

		for file := range incoming {
			pkg, found := packages[file.ParentFolder]
			if !found {
				pkg = &Package{}
				var err error
				pkg.Info, err = build.ImportDir(file.ParentFolder, build.AllowBinary)
				if err != nil {
					// TODO: Need to handle this. It happens when a .go file is blank (and doesn't have a package declaration)...
					continue
				}
				packages[file.ParentFolder] = pkg
			}
			if file.IsModified && file.IsGoTestFile {
				pkg.IsModifiedTest = true
			} else if file.IsModified && !file.IsGoTestFile && file.IsGoFile {
				pkg.IsModifiedCode = true
			}
		}

		outgoing := make(chan *Package)
		self.out <- outgoing
		for _, pkg := range packages {
			outgoing <- pkg
		}
		close(outgoing)
	}
}
开发者ID:mdwhatcott,项目名称:scantest,代码行数:32,代码来源:main.go


示例9: packageFromDir

func packageFromDir(t *testing.T, dir string) *build.Package {
	pkg, err := build.ImportDir(dir, build.ImportComment)
	if err != nil {
		t.Fatalf("build.ImportDir(%q, build.ImportComment) failed with %v; want success", dir, err)
	}
	return pkg
}
开发者ID:yugui,项目名称:gazel,代码行数:7,代码来源:generator_test.go


示例10: fullPackageInDir

// returns the package in dir either from a cache or by importing it and then caching it
func fullPackageInDir(dir string) (*build.Package, error) {
	var err error
	pkg, ok := pkgCache[dir]
	if !ok {
		pkg, err = build.ImportDir(dir, build.FindOnly)
		if pkg.Goroot {
			pkg, err = build.ImportDir(pkg.Dir, 0)
		} else {
			fillPackage(pkg)
		}
		if err == nil {
			pkgCache[dir] = pkg
		}
	}
	return pkg, err
}
开发者ID:spenczar,项目名称:godep,代码行数:17,代码来源:list.go


示例11: main

func main() {
	flag.Parse()
	if build.Default.GOARCH == "amd64" {
		ptrKind = "Q"
		ptrSize = 8
		if *useInt64 {
			intSize = 8
			newIntSize = intSize
			intKind = "Q"
		}
		if *fixInt64 {
			newIntSize = 8
			*fixOffset = true
		}
	}
	args := flag.Args()
	if len(args) == 0 {
		p, err := build.ImportDir(".", 0)
		if err != nil {
			log.Fatal(err)
		}
		check(p)
	} else {
		for _, arg := range args {
			p, err := build.Import(arg, "", 0)
			if err != nil {
				log.Print(err)
				continue
			}
			check(p)
		}
	}
}
开发者ID:0x7cc,项目名称:rsc,代码行数:33,代码来源:main.go


示例12: FindJujuCoreImports

// FindJujuCoreImports returns a sorted list of juju-core packages that are
// imported by the packageName parameter.  The resulting list removes the
// common prefix "launchpad.net/juju-core/" leaving just the short names.
func FindJujuCoreImports(c *gc.C, packageName string) []string {
	var imports []string

	for _, root := range build.Default.SrcDirs() {
		fullpath := filepath.Join(root, packageName)
		pkg, err := build.ImportDir(fullpath, 0)
		if err == nil {
			imports = pkg.Imports
			break
		}
	}
	if imports == nil {
		c.Fatalf(packageName + " not found")
	}

	var result []string
	const prefix = "launchpad.net/juju-core/"
	for _, name := range imports {
		if strings.HasPrefix(name, prefix) {
			result = append(result, name[len(prefix):])
		}
	}
	sort.Strings(result)
	return result
}
开发者ID:johnvilsack,项目名称:golang-stuff,代码行数:28,代码来源:imports.go


示例13: importDir

// importDir is just an error-catching wrapper for build.ImportDir.
func importDir(dir string) *build.Package {
	pkg, err := build.ImportDir(dir, build.ImportComment)
	if err != nil {
		log.Fatal(err)
	}
	return pkg
}
开发者ID:CiscoCloud,项目名称:go,代码行数:8,代码来源:main.go


示例14: dotPackage

func dotPackage() (*build.Package, error) {
	dir, err := filepath.Abs(".")
	if err != nil {
		return nil, err
	}
	return build.ImportDir(dir, build.FindOnly)
}
开发者ID:Cepave,项目名称:lvs-metrics,代码行数:7,代码来源:save.go


示例15: ImportDir

// ImportDir gives a single instrumentable golang package. See Import.
func ImportDir(basepkg, pkgname string) (*Instrumentable, error) {
	pkg, err := build.ImportDir(pkgname, 0)
	if err != nil {
		return nil, err
	}
	return &Instrumentable{pkg, basepkg, pkgname, false, make(map[string]bool)}, nil
}
开发者ID:elazarl,项目名称:gosloppy,代码行数:8,代码来源:instrument.go


示例16: Compile

func Compile(filename string, translations []*po.Po, opts *CompileOptions) error {
	var buf bytes.Buffer
	dir := filepath.Dir(filename)
	p, err := build.ImportDir(dir, 0)
	if err == nil {
		fmt.Fprintf(&buf, "package %s\n", p.Name)
	}
	buf.WriteString("import \"gnd.la/i18n/table\"\n")
	buf.WriteString(genutil.AutogenString())
	buf.WriteString("func init() {\n")
	var defaultContext string
	if opts != nil {
		defaultContext = opts.DefaultContext
	}
	for _, v := range translations {
		table := poToTable(v, defaultContext)
		form, err := funcFromFormula(v.Attrs["Plural-Forms"])
		if err != nil {
			return err
		}
		data, err := table.Encode()
		if err != nil {
			return err
		}
		fmt.Fprintf(&buf, "table.Register(%q, func (n int) int {\n%s\n}, %q)\n", v.Attrs["Language"], form, data)
	}
	buf.WriteString("\n}\n")
	return genutil.WriteAutogen(filename, buf.Bytes())
}
开发者ID:rainycape,项目名称:gondola,代码行数:29,代码来源:compile.go


示例17: generateTypes

func generateTypes(input, constraint string) []byte {
	// Get working directory
	currentFolder, err := os.Getwd()
	if err != nil {
		log.Fatalf("Unable to obtain current working directory: %s", err)
	}
	// Read current package
	pkg, err := build.ImportDir(currentFolder, build.AllowBinary)
	if err != nil {
		log.Fatalf("Failed to determine go package inside directory '%s' - is your GOPATH set correctly ('%s')? Error: %s", currentFolder, os.Getenv("GOPATH"), err)
	}
	file, err := filepath.Abs(input)
	if err != nil {
		log.Fatalf("Hit error: %v", err)
	}
	job := jsonschema2go.Job{
		Package:           pkg.Name,
		ExportTypes:       true,
		HideStructMembers: false,
		URLs:              []string{"file://" + file},
		SkipCodeGen:       false,
	}
	result, err := job.Execute()
	if err != nil {
		log.Fatalf("Failed to generate source code: %v", err)
	}
	source := result.SourceCode
	if len(constraint) > 0 {
		source = append([]byte("// +build "+constraint+"\n"), result.SourceCode...)
	}
	return source
}
开发者ID:petemoore,项目名称:generic-worker,代码行数:32,代码来源:main.go


示例18: runGenerate

func runGenerate(cmd *Command) {
	action := "updated"
	var err error
	var spec *Spec
	var pack *build.Package

	// read spec
	if _, err = os.Stat(SpecFileName); os.IsNotExist(err) {
		action = "generated"
		spec = new(Spec)
	} else {
		spec = ReadSpec()
	}

	// read package
	pack, err = build.ImportDir(".", 0)
	PanicIfErr(err)

	// add example author
	if len(spec.Authors) == 0 {
		spec.Authors = []Person{{FullName: ExampleFullName, Email: ExampleEmail}}
	}

	// some extra files
	if len(spec.ExtraFiles) == 0 {
		var globs []string
		for _, glob := range []string{"read*", "licen?e*", "copying*", "contrib*", "author*",
			"thank*", "news*", "change*", "install*", "bug*", "todo*"} {
			globs = append(globs, glob, strings.ToUpper(glob), strings.Title(glob))
		}

		for _, glob := range globs {
			files, err := filepath.Glob(glob)
			PanicIfErr(err)
			spec.ExtraFiles = append(spec.ExtraFiles, files...)
		}
	}

	// write spec
	f, err := os.OpenFile(SpecFileName, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, SpecFilePerm)
	PanicIfErr(err)
	defer f.Close()
	_, err = spec.WriteTo(f)
	PanicIfErr(err)

	if generateV {
		log.Printf("%s %s.", SpecFileName, action)
	}

	// check spec and package
	errors := spec.Check()
	errors = append(errors, CheckPackage(pack)...)
	if len(errors) != 0 {
		log.Print("\nYou should fix following issues:")
		for _, e := range errors {
			log.Printf("    %s", e)
		}
		log.Print("\nAfter that run 'nut check' to check spec again.")
	}
}
开发者ID:SohoStudio,项目名称:nut,代码行数:60,代码来源:generate.go


示例19: GetImports

// GetImports returns package denpendencies.
func GetImports(absPath, importPath string, example bool) []string {
	pkg, err := build.ImportDir(absPath, build.AllowBinary)
	if err != nil {
		if _, ok := err.(*build.NoGoError); !ok {
			log.Error("", "Fail to get imports")
			log.Fatal("", err.Error())
		}
	}

	fis := GetDirsInfo(absPath)
	absPath += "/"

	dirs := make([]string, 0)
	for _, fi := range fis {
		if fi.IsDir() && !strings.Contains(fi.Name(), VENDOR) {
			dirs = append(dirs, absPath+fi.Name())
		}
	}

	imports := make([]string, 0, len(pkg.Imports))
	for _, p := range pkg.Imports {
		if !IsGoRepoPath(p) && !strings.HasPrefix(p, importPath) {
			imports = append(imports, p)
		}
	}
	if len(dirs) > 0 {
		imports = append(imports, GetAllImports(dirs, importPath, example)...)
	}
	return imports
}
开发者ID:nashtsai,项目名称:gopm,代码行数:31,代码来源:utils.go


示例20: Parse

func (l *parser) Parse(dir string) (taskSet *tasking.TaskSet, err error) {
	dir, err = expandDir(dir)
	if err != nil {
		return
	}

	p, e := build.ImportDir(dir, 0)
	taskFiles := append(p.GoFiles, p.IgnoredGoFiles...)
	taskFiles = append(taskFiles, p.CgoFiles...)
	if e != nil {
		// task files may be ignored for build
		if _, ok := e.(*build.NoGoError); !ok || len(taskFiles) == 0 {
			err = e
			return
		}
	}

	tasks, err := loadTasks(dir, taskFiles)
	if err != nil {
		return
	}

	taskSet = &tasking.TaskSet{Name: p.Name, Dir: p.Dir, ImportPath: p.ImportPath, Tasks: tasks}

	return
}
开发者ID:sbinet,项目名称:gotask,代码行数:26,代码来源:parser.go



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang build.IsLocalImport函数代码示例发布时间:2022-05-28
下一篇:
Golang build.Import函数代码示例发布时间:2022-05-28
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap