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


Golang gotool.ImportPaths函数代码示例

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


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

示例1: parseFlags

func parseFlags(checker *errcheck.Checker, args []string) ([]string, int) {
	flags := flag.NewFlagSet(args[0], flag.ContinueOnError)
	flags.BoolVar(&checker.Blank, "blank", false, "if true, check for errors assigned to blank identifier")
	flags.BoolVar(&checker.Asserts, "asserts", false, "if true, check for ignored type assertion results")
	flags.BoolVar(&checker.Verbose, "verbose", false, "produce more verbose logging")

	tags := tagsFlag{}
	flags.Var(&tags, "tags", "space-separated list of build tags to include")
	ignorePkg := flags.String("ignorepkg", "", "comma-separated list of package paths to ignore")
	ignore := ignoreFlag(map[string]*regexp.Regexp{
		"fmt": dotStar,
	})
	flags.Var(ignore, "ignore", "comma-separated list of pairs of the form pkg:regex\n"+
		"            the regex is used to ignore names within pkg")

	if err := flags.Parse(args[1:]); err != nil {
		return nil, exitFatalError
	}

	checker.Tags = tags
	for _, pkg := range strings.Split(*ignorePkg, ",") {
		if pkg != "" {
			ignore[pkg] = dotStar
		}
	}
	checker.Ignore = ignore

	ctx := gotool.Context{
		BuildContext: build.Default,
	}
	ctx.BuildContext.BuildTags = tags

	// ImportPaths normalizes paths and expands '...'
	return gotool.ImportPaths(flags.Args()), exitCodeOk
}
开发者ID:dominikh,项目名称:errcheck,代码行数:35,代码来源:main.go

示例2: main

func main() {
	ignore := ignoreFlag(map[string]*regexp.Regexp{
		"fmt": dotStar,
	})
	flag.Var(ignore, "ignore", "comma-separated list of pairs of the form pkg:regex\n"+
		"            the regex is used to ignore names within pkg")
	ignorePkg := flag.String("ignorepkg", "", "comma-separated list of package paths to ignore")
	blank := flag.Bool("blank", false, "if true, check for errors assigned to blank identifier")
	flag.Parse()

	for _, pkg := range strings.Split(*ignorePkg, ",") {
		if pkg != "" {
			ignore[pkg] = dotStar
		}
	}

	var pkgPaths = gotool.ImportPaths(flag.Args())
	if err := errcheck.CheckPackages(pkgPaths, ignore, *blank); err != nil {
		if e, ok := err.(errcheck.UncheckedErrors); ok {
			for _, uncheckedError := range e.Errors {
				fmt.Println(uncheckedError)
			}
			os.Exit(1)
		} else if err == errcheck.ErrNoGoFiles {
			fmt.Fprintln(os.Stderr, err)
			os.Exit(0)
		}
		Fatalf("failed to check package: %s", err)
	}
	os.Exit(0)
}
开发者ID:robfig,项目名称:errcheck,代码行数:31,代码来源:main.go

示例3: main

func main() {
	flag.Parse()

	importPaths := gotool.ImportPaths(flag.Args())
	if len(importPaths) == 0 {
		return
	}

	var conf loader.Config
	conf.Fset = fset
	for _, importPath := range importPaths {
		conf.Import(importPath)
	}
	prog, err := conf.Load()
	if err != nil {
		log.Fatal(err)
	}

	for _, pkg := range prog.InitialPackages() {
		for _, file := range pkg.Files {
			ast.Inspect(file, func(node ast.Node) bool {
				if s, ok := node.(*ast.StructType); ok {
					malign(node.Pos(), pkg.Types[s].Type.(*types.Struct))
				}
				return true
			})
		}
	}
}
开发者ID:mdempsky,项目名称:maligned,代码行数:29,代码来源:maligned.go

示例4: main

func main() {
	flag.Parse()

	username, ok := os.LookupEnv(teamcityAPIUserEnv)
	if !ok {
		log.Fatalf("teamcity API username environment variable %s is not set", teamcityAPIUserEnv)
	}
	password, ok := os.LookupEnv(teamcityAPIPasswordEnv)
	if !ok {
		log.Fatalf("teamcity API password environment variable %s is not set", teamcityAPIPasswordEnv)
	}
	importPaths := gotool.ImportPaths([]string{"github.com/cockroachdb/cockroach/..."})

	client := teamcity.New("teamcity.cockroachdb.com", username, password)
	// Queue a build per configuration per package.
	for _, params := range []map[string]string{
		{}, // uninstrumented
		{"env.GOFLAGS": "-race"},
		{"env.TAGS": "deadlock"},
	} {
		for _, importPath := range importPaths {
			params["env.PKG"] = importPath
			build, err := client.QueueBuild(*buildTypeID, *branchName, params)
			if err != nil {
				log.Fatalf("failed to create teamcity build (*buildTypeID=%s *branchName=%s, params=%+v): %s", *buildTypeID, *branchName, params, err)
			}
			log.Printf("created teamcity build (*buildTypeID=%s *branchName=%s, params=%+v): %s", *buildTypeID, *branchName, params, build)
		}
	}
}
开发者ID:bdarnell,项目名称:cockroach,代码行数:30,代码来源:main.go

示例5: runTC

func runTC(queueBuildFn func(map[string]string)) {
	importPaths := gotool.ImportPaths([]string{"github.com/cockroachdb/cockroach/pkg/..."})

	// Queue a build per configuration per package.
	for _, properties := range []map[string]string{
		{}, // uninstrumented
		{"env.GOFLAGS": "-race"},
		{tagsKey: "deadlock"},
	} {
		if tags, ok := properties[tagsKey]; ok {
			properties[tagsKey] = strings.Join([]string{tags, stressTag}, " ")
		} else {
			properties[tagsKey] = stressTag
		}

		for _, propEvalKV := range []bool{true, false} {
			properties["env.COCKROACH_PROPOSER_EVALUATED_KV"] = strconv.FormatBool(propEvalKV)

			for _, importPath := range importPaths {
				properties["env.PKG"] = importPath

				queueBuildFn(properties)
			}
		}
	}
}
开发者ID:jmptrader,项目名称:cockroach,代码行数:26,代码来源:main.go

示例6: main

func main() {
	flag.Usage = func() {
		fmt.Fprintf(os.Stderr, "%s\n", usage)
		flag.PrintDefaults()
		os.Exit(2)
	}
	flag.Parse()

	var err error
	cwd, err = os.Getwd()
	if err != nil {
		cwd = "."
	}
	pkgs := flag.Args()
	if len(pkgs) == 0 {
		pkgs = []string{"."}
	}
	exitStatus := 0
	pkgs = gotool.ImportPaths(pkgs)
	for _, pkg := range pkgs {
		if err := writeImports(pkg); err != nil {
			fmt.Fprintf(os.Stderr, "error: %v", err)
			exitStatus = 1
		}
	}
	os.Exit(exitStatus)
}
开发者ID:rogpeppe,项目名称:misc,代码行数:27,代码来源:importcomment.go

示例7: main

func main() {
	flag.Parse()
	exitStatus := 0
	importPaths := gotool.ImportPaths(flag.Args())
	if len(importPaths) == 0 {
		importPaths = []string{"."}
	}
	for _, pkgPath := range importPaths {
		visitor := &visitor{
			info: types.Info{
				Types:      make(map[ast.Expr]types.TypeAndValue),
				Defs:       make(map[*ast.Ident]types.Object),
				Selections: make(map[*ast.SelectorExpr]*types.Selection),
			},

			m:    make(map[types.Type]map[string]int),
			skip: make(map[types.Type]struct{}),
		}
		fset, astFiles := check.ASTFilesForPackage(pkgPath, *loadTestFiles)
		imp := importer.New()
		// Preliminary cgo support.
		imp.Config = importer.Config{UseGcFallback: true}
		config := types.Config{Import: imp.Import}
		var err error
		visitor.pkg, err = config.Check(pkgPath, fset, astFiles, &visitor.info)
		if err != nil {
			fmt.Fprintf(os.Stderr, "%s: %v\n", pkgPath, err)
			continue
		}
		for _, f := range astFiles {
			ast.Walk(visitor, f)
		}
		for t := range visitor.m {
			if _, skip := visitor.skip[t]; skip {
				continue
			}
			for fieldName, v := range visitor.m[t] {
				if !*reportExported && ast.IsExported(fieldName) {
					continue
				}
				if v == 0 {
					field, _, _ := types.LookupFieldOrMethod(t, false, visitor.pkg, fieldName)
					if fieldName == "XMLName" {
						if named, ok := field.Type().(*types.Named); ok && named.Obj().Pkg().Path() == "encoding/xml" {
							continue
						}
					}
					pos := fset.Position(field.Pos())
					fmt.Printf("%s: %s:%d:%d: %s.%s\n",
						pkgPath, pos.Filename, pos.Line, pos.Column,
						types.TypeString(t, nil), fieldName,
					)
					exitStatus = 1
				}
			}
		}
	}
	os.Exit(exitStatus)
}
开发者ID:aganno2,项目名称:check,代码行数:59,代码来源:structcheck.go

示例8: main

func main() {
	// TODO(kaneda): Add a commandline flag for specifying a target type.
	targetPkg := "github.com/cockroachdb/cockroach/roachpb"
	targetTypeName := "Error"
	if err := returncheck.Run(gotool.ImportPaths(os.Args[1:]), targetPkg, targetTypeName); err != nil {
		os.Exit(1)
	}
}
开发者ID:kkaneda,项目名称:returncheck,代码行数:8,代码来源:main.go

示例9: main

func main() {
	if len(packages) == 0 {
		fmt.Fprintln(os.Stderr, "Need to specify at least one package to check.")
		flag.Usage()
		os.Exit(1)
	}

	if len(arguments)+len(returns) == 0 {
		fmt.Fprintln(os.Stderr, "Need at least one type to search for.")
		flag.Usage()
		os.Exit(1)
	}

	var typesToCheck []string
	typesToCheck = append(typesToCheck, arguments...)
	typesToCheck = append(typesToCheck, returns...)

	ctx := NewContext()
	funcs, errs := ctx.getFunctions(gotool.ImportPaths(packages))
	listErrors(errs)

	signatures := make(map[string][]string)

	for _, fnc := range funcs {
		sig, ok := fnc.Type().(*types.Signature)
		if !ok {
			// Skipping over builtins
			continue
		}

		anyArg, allArg := checkTypes(sig.Params(), arguments)
		anyRet, allRet := checkTypes(sig.Results(), returns)

		if (!and && (anyArg || anyRet)) || (and && allArg && allRet) {
			prefix := ""
			if sig.Recv() != nil {
				prefix = fmt.Sprintf("(%s %s) ", noDot(sig.Recv().Name()), sig.Recv().Type().String())
			}

			signatures[fnc.Pkg.Path()] = append(signatures[fnc.Pkg.Path()],
				fmt.Sprintf("%s%s(%s) (%s)",
					prefix,
					fnc.Name(),
					argsToString(sig.Params()),
					argsToString(sig.Results())))
		}
	}

	for _, path := range sortedKeys(signatures) {
		sigs := signatures[path]
		fmt.Println(path + ":")
		for _, sig := range sigs {
			fmt.Println("\t" + sig)
		}
		fmt.Println()
	}
}
开发者ID:kisielk,项目名称:uses,代码行数:57,代码来源:main.go

示例10: parseFlags

func parseFlags(checker *errcheck.Checker, args []string) ([]string, int) {
	flags := flag.NewFlagSet(args[0], flag.ContinueOnError)
	flags.BoolVar(&checker.Blank, "blank", false, "if true, check for errors assigned to blank identifier")
	flags.BoolVar(&checker.Asserts, "asserts", false, "if true, check for ignored type assertion results")
	flags.BoolVar(&checker.WithoutTests, "ignoretests", false, "if true, checking of _test.go files is disabled")
	flags.BoolVar(&checker.Verbose, "verbose", false, "produce more verbose logging")

	flags.BoolVar(&abspath, "abspath", false, "print absolute paths to files")

	tags := tagsFlag{}
	flags.Var(&tags, "tags", "space-separated list of build tags to include")
	ignorePkg := flags.String("ignorepkg", "", "comma-separated list of package paths to ignore")
	ignore := ignoreFlag(map[string]*regexp.Regexp{
		"fmt": dotStar,
	})
	flags.Var(ignore, "ignore", "[deprecated] comma-separated list of pairs of the form pkg:regex\n"+
		"            the regex is used to ignore names within pkg.")

	var excludeFile string
	flags.StringVar(&excludeFile, "exclude", "", "Path to a file containing a list of functions to exclude from checking")

	if err := flags.Parse(args[1:]); err != nil {
		return nil, exitFatalError
	}

	if excludeFile != "" {
		exclude := make(map[string]bool)
		fh, err := os.Open(excludeFile)
		if err != nil {
			fmt.Fprintf(os.Stderr, "Could not read exclude file: %s\n", err)
			return nil, exitFatalError
		}
		scanner := bufio.NewScanner(fh)
		for scanner.Scan() {
			exclude[scanner.Text()] = true
		}
		if err := scanner.Err(); err != nil {
			fmt.Fprintf(os.Stderr, "Could not read exclude file: %s\n", err)
			return nil, exitFatalError
		}
		checker.SetExclude(exclude)
	}

	checker.Tags = tags
	for _, pkg := range strings.Split(*ignorePkg, ",") {
		if pkg != "" {
			ignore[pkg] = dotStar
		}
	}
	checker.Ignore = ignore

	// ImportPaths normalizes paths and expands '...'
	return gotool.ImportPaths(flags.Args()), exitCodeOk
}
开发者ID:kisielk,项目名称:errcheck,代码行数:54,代码来源:main.go

示例11: RemoveRepo

// RemoveRepo removes go-gettable repo with no local changes (by moving it into trash).
// importPathPattern must match exactly with the repo root.
// For example, "github.com/user/repo/...".
func RemoveRepo(importPathPattern string) error {
	// TODO: Use an official Go package for `go list` functionality whenever possible.
	importPaths := gotool.ImportPaths([]string{importPathPattern})
	if len(importPaths) == 0 {
		return errors.New("no packages to remove")
	}

	var firstGoPackage *gist7480523.GoPackage
	for i, importPath := range importPaths {
		goPackage := gist7480523.GoPackageFromImportPath(importPath)
		if goPackage == nil {
			return errors.New("Import Path not found: " + importPath)
		}

		if goPackage.Bpkg.Goroot {
			return errors.New("can't remove packages from GOROOT")
		}

		goPackage.UpdateVcs()

		if goPackage.Dir.Repo == nil {
			return errors.New("can't get repo status")
		}

		if i == 0 {
			firstGoPackage = goPackage
		} else if firstGoPackage.Dir.Repo != goPackage.Dir.Repo {
			return errors.New("matched Go Packages span more than 1 repo: " + firstGoPackage.Dir.Repo.Vcs.RootPath() + " != " + goPackage.Dir.Repo.Vcs.RootPath())
		} else if !strings.HasPrefix(goPackage.Bpkg.Dir, firstGoPackage.Dir.Repo.Vcs.RootPath()) { // TODO: This is probably not neccessary...
			return errors.New("Go Package not inside repo: " + goPackage.Bpkg.Dir + " doesn't have prefix " + firstGoPackage.Dir.Repo.Vcs.RootPath())
		}
	}

	if repoImportPathPattern := gist7480523.GetRepoImportPathPattern(firstGoPackage.Dir.Repo.Vcs.RootPath(), firstGoPackage.Bpkg.SrcRoot); repoImportPathPattern != importPathPattern {
		return errors.New("importPathPattern not exact repo root match: " + importPathPattern + " != " + repoImportPathPattern)
	}

	firstGoPackage.UpdateVcsFields()

	cleanStatus := func(goPackage *gist7480523.GoPackage) bool {
		packageStatus := presenter(goPackage)[:4]
		return packageStatus == "    " || packageStatus == "  + " // Updates are okay to ignore.
	}

	if !cleanStatus(firstGoPackage) {
		return errors.New("non-clean status: " + presenter(firstGoPackage))
	}

	err := trash.MoveTo(firstGoPackage.Dir.Repo.Vcs.RootPath())
	return err

	// TODO: Clean up /pkg folder contents, if any, etc.
}
开发者ID:wutaizeng,项目名称:kapacitor,代码行数:56,代码来源:gopathutil.go

示例12: main

func main() {
	flag.Parse()

	serverURL, ok := os.LookupEnv(teamcityServerURLEnv)
	if !ok {
		log.Fatalf("teamcity server URL environment variable %s is not set", teamcityServerURLEnv)
	}
	u, err := url.Parse(serverURL)
	if err != nil {
		log.Fatal(err)
	}
	username, ok := os.LookupEnv(teamcityAPIUserEnv)
	if !ok {
		log.Fatalf("teamcity API username environment variable %s is not set", teamcityAPIUserEnv)
	}
	password, ok := os.LookupEnv(teamcityAPIPasswordEnv)
	if !ok {
		log.Fatalf("teamcity API password environment variable %s is not set", teamcityAPIPasswordEnv)
	}
	importPaths := gotool.ImportPaths([]string{"github.com/cockroachdb/cockroach/pkg/..."})

	client := teamcity.New(u.Host, username, password)
	// Queue a build per configuration per package.
	for _, params := range []map[string]string{
		{}, // uninstrumented
		{"env.GOFLAGS": "-race"},
		{tagsKey: "deadlock"},
	} {
		if tags, ok := params[tagsKey]; ok {
			params[tagsKey] = strings.Join([]string{tags, stressTag}, " ")
		} else {
			params[tagsKey] = stressTag
		}

		for _, propEvalKV := range []bool{true, false} {
			params["env.COCKROACH_PROPOSER_EVALUATED_KV"] = strconv.FormatBool(propEvalKV)

			for _, importPath := range importPaths {
				params["env.PKG"] = importPath

				build, err := client.QueueBuild(*buildTypeID, *branchName, params)
				if err != nil {
					log.Fatalf("failed to create teamcity build (*buildTypeID=%s *branchName=%s, params=%+v): %s", *buildTypeID, *branchName, params, err)
				}
				log.Printf("created teamcity build (*buildTypeID=%s *branchName=%s, params=%+v): %s", *buildTypeID, *branchName, params, build)
			}
		}
	}
}
开发者ID:veteranlu,项目名称:cockroach,代码行数:49,代码来源:main.go

示例13: main

func main() {
	flag.Parse()
	exitStatus = 0
	importPaths := gotool.ImportPaths(flag.Args())
	if len(importPaths) == 0 {
		importPaths = []string{"."}
	}
	for _, pkgPath := range importPaths {
		visitor := &visitor{pkgPath: pkgPath}
		fset, astFiles := check.ASTFilesForPackage(pkgPath, false)
		visitor.fset = fset
		for _, f := range astFiles {
			ast.Walk(visitor, f)
		}
	}
	os.Exit(exitStatus)
}
开发者ID:aganno2,项目名称:check,代码行数:17,代码来源:defercheck.go

示例14: expandPackages

func expandPackages(spec []string) ([]string, error) {
	// expand "..."
	paths := gotool.ImportPaths(spec)

	var r []string
	for _, path := range paths {
		pkg, err := build.Import(path, ".", 0)
		if _, ok := err.(*build.NoGoError); ok {
			// directory with no Go source files in it
			continue
		}
		if err != nil {
			return nil, err
		}
		if pkg.ImportPath == "" {
			return nil, fmt.Errorf("no import path found: %v", path)
		}
		r = append(r, pkg.ImportPath)
	}
	return r, nil
}
开发者ID:read-later,项目名称:bazil,代码行数:21,代码来源:gen-imports.go

示例15: main

func main() {
	dotStar := regexp.MustCompile(".*")

	ignore := ignoreFlag(make(map[string]*regexp.Regexp))
	flag.Var(ignore, "ignore", "comma-separated list of pairs of the form pkg:regex\n"+
		"            the regex is used to ignore names within pkg")
	ignorePkg := flag.String("ignorepkg", "", "comma-separated list of package paths to ignore")
	blank := flag.Bool("blank", false, "if true, check for errors assigned to blank identifier")
	flag.Parse()

	for _, pkg := range strings.Split(*ignorePkg, ",") {
		if pkg != "" {
			ignore[pkg] = dotStar
		}
	}

	if _, ok := ignore["fmt"]; !ok {
		ignore["fmt"] = dotStar
	}

	var exitStatus int
	for _, pkgPath := range gotool.ImportPaths(flag.Args()) {
		if err := errcheck.CheckPackage(pkgPath, ignore, *blank); err != nil {
			if e, ok := err.(errcheck.UncheckedErrors); ok {
				for _, uncheckedError := range e.Errors {
					fmt.Println(uncheckedError)
				}
				exitStatus = 1
				continue
			} else if err == errcheck.ErrNoGoFiles {
				fmt.Fprintln(os.Stderr, err)
				continue
			}
			Fatalf("failed to check package %s: %s", pkgPath, err)
		}
	}
	os.Exit(exitStatus)
}
开发者ID:j6n,项目名称:errcheck,代码行数:38,代码来源:main.go


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