// GoPackagePath returns the path to the provided Go package's
// source directory.
// pkg may be a path prefix without any *.go files.
// The error is os.ErrNotExist if GOPATH is unset.
7184
func GoPackagePath(pkg string) (path string, err error) {
	gp := os.Getenv("GOPATH")
	if gp == "" {
		cmd := exec.Command("go", "env", "GOPATH")
		out, err := cmd.Output()
		if err != nil {
			return "", fmt.Errorf("could not run 'go env GOPATH': %v, %s", err, out)
		}
		gp = strings.TrimSpace(string(out))
		if gp == "" {
			return "", os.ErrNotExist
		}
	}
	for _, p := range filepath.SplitList(gp) {
		dir := filepath.Join(p, "src", filepath.FromSlash(pkg))
		fi, err := os.Stat(dir)
		if os.IsNotExist(err) {
			continue
		}
		if err != nil {
			return "", err
		}
		if !fi.IsDir() {
			continue
		}
		return dir, nil
	}
	return path, os.ErrNotExist
}
9745
func isPackage(pkg *types.Package, path string) bool {
	if pkg == nil {
		return false
	}

	return pkg.Path() == path ||
		strings.HasSuffix(pkg.Path(), "/vendor/"+path)
}
717171
func PrimaryPackage(gocmd, path string, files []string) (*PkgInfo, error) {
	info, err := Package(path, files)
	if err != nil {
		return nil, err
	}

	if err := setImports(gocmd, info); err != nil {
		return nil, err
	}

	setDefault(info)
	setAliases(info)
	return info, nil
}
1119726
func (b *Builder) typeCheckPackage(pkgPath importPathString) (*tc.Package, error) {
	klog.V(5).Infof("typeCheckPackage %s", pkgPath)
	if pkg, ok := b.typeCheckedPackages[pkgPath]; ok {
		if pkg != nil {
			klog.V(6).Infof("typeCheckPackage %s already done", pkgPath)
			return pkg, nil
		}
		// We store a nil right before starting work on a package. So
		// if we get here and it's present and nil, that means there's
		// another invocation of this function on the call stack
		// already processing this package.
		return nil, fmt.Errorf("circular dependency for %q", pkgPath)
	}
	parsedFiles, ok := b.parsed[pkgPath]
	if !ok {
		return nil, fmt.Errorf("No files for pkg %q", pkgPath)
	}
	files := make([]*ast.File, len(parsedFiles))
	for i := range parsedFiles {
		files[i] = parsedFiles[i].file
	}
	b.typeCheckedPackages[pkgPath] = nil
	c := tc.Config{
		IgnoreFuncBodies: true,
		// Note that importAdapter can call b.importPackage which calls this
		// method. So there can't be cycles in the import graph.
		Importer: importAdapter{b},
		Error: func(err error) {
			klog.V(2).Infof("type checker: %v\n", err)
		},
	}
	pkg, err := c.Check(string(pkgPath), b.fset, files, nil)
	b.typeCheckedPackages[pkgPath] = pkg // record the result whether or not there was an error
	return pkg, err
}
730733
func processPackage(fset *token.FileSet, pkgImportPath, pkgPath string, pkg *ast.Package) *model.SourceInfo {
	var (
		structSpecs     []*model.TypeInfo
		initImportPaths []string

		methodSpecs     = make(methodMap)
		validationKeys  = make(map[string]map[int]string)
		scanControllers = strings.HasSuffix(pkgImportPath, "/controllers") ||
			strings.Contains(pkgImportPath, "/controllers/")
		scanTests = strings.HasSuffix(pkgImportPath, "/tests") ||
			strings.Contains(pkgImportPath, "/tests/")
	)

	// For each source file in the package...
	utils.Logger.Info("Exaimining files in path", "package", pkgPath)
	for fname, file := range pkg.Files {
		// Imports maps the package key to the full import path.
		// e.g. import "sample/app/models" => "models": "sample/app/models"
		imports := map[string]string{}

		// For each declaration in the source file...
		for _, decl := range file.Decls {
			addImports(imports, decl, pkgPath)

			if scanControllers {
				// Match and add both structs and methods
				structSpecs = appendStruct(fname, structSpecs, pkgImportPath, pkg, decl, imports, fset)
				appendAction(fset, methodSpecs, decl, pkgImportPath, pkg.Name, imports)
			} else if scanTests {
				structSpecs = appendStruct(fname, structSpecs, pkgImportPath, pkg, decl, imports, fset)
			}

			// If this is a func... (ignore nil for external (non-Go) function)
			if funcDecl, ok := decl.(*ast.FuncDecl); ok && funcDecl.Body != nil {
				// Scan it for validation calls
				lineKeys := GetValidationKeys(fname, fset, funcDecl, imports)
				if len(lineKeys) > 0 {
					validationKeys[pkgImportPath+"."+getFuncName(funcDecl)] = lineKeys
				}

				// Check if it's an init function.
				if funcDecl.Name.Name == "init" {
					initImportPaths = []string{pkgImportPath}
				}
			}
		}
	}

	// Add the method specs to the struct specs.
	for _, spec := range structSpecs {
		spec.MethodSpecs = methodSpecs[spec.StructName]
	}

	return &model.SourceInfo{
		StructSpecs:     structSpecs,
		ValidationKeys:  validationKeys,
		InitImportPaths: initImportPaths,
	}
}
866807
func ImportPaths(srcdir, cwd string, args []string) []string {
	args = importPathsNoDotExpansion(srcdir, cwd, args)
	var out []string
	for _, a := range args {
		if strings.Contains(a, "...") {
			pkgs, err := matchPackages(srcdir, a)
			if err != nil {
				fmt.Printf("could not load all packages: %v\n", err)
			}
			out = append(out, pkgs...)
			continue
		}
		out = append(out, a)
	}
	return out
}
664341
func LocatePackage(path string) (string, error) {
	p, err := build.Default.Import(path, "", build.FindOnly)
	if err != nil {
		return "", errors.Wrap(err, "LocatePackage: failed to find import")
	}

	cwd, err := os.Getwd()
	if err != nil {
		return "", errors.Wrap(err, "LocatePackage: could not get working directory")
	}

	p.Dir, err = filepath.Rel(cwd, p.Dir)
	if err != nil {
		return "", errors.Wrap(err, "LocatePackage: could not construct relative path")
	}

	return p.Dir, nil
}
925881
func (t *ImportTracker) TrackPackages(pkgs ...*types.Package) {
	for _, pkg := range pkgs {
		t.Imported[pkg.Path()] = pkg.Name()
	}
}
607999
func (client *Client) CreatePackage(pkg Package) (Package, Warnings, error) {
	bodyBytes, err := json.Marshal(pkg)
	if err != nil {
		return Package{}, nil, err
	}

	request, err := client.newHTTPRequest(requestOptions{
		RequestName: internal.PostPackageRequest,
		Body:        bytes.NewReader(bodyBytes),
	})
	if err != nil {
		return Package{}, nil, err
	}

	var responsePackage Package
	response := cloudcontroller.Response{
		DecodeJSONResponseInto: &responsePackage,
	}
	err = client.connection.Make(request, &response)

	return responsePackage, response.Warnings, err
}
489955
func (b *Builder) FindPackages() []string {
	// Iterate packages in a predictable order.
	pkgPaths := []string{}
	for k := range b.typeCheckedPackages {
		pkgPaths = append(pkgPaths, string(k))
	}
	sort.Strings(pkgPaths)

	result := []string{}
	for _, pkgPath := range pkgPaths {
		if b.userRequested[importPathString(pkgPath)] {
			// Since walkType is recursive, all types that are in packages that
			// were directly mentioned will be included.  We don't need to
			// include all types in all transitive packages, though.
			result = append(result, pkgPath)
		}
	}
	return result
}
516218
func LoadPackage(ccname string, ccversion string, path string) (CCPackage, error) {
	return (&CCInfoFSImpl{}).GetChaincodeFromPath(ccname, ccversion, path)
}
152880
func pkgForPath(path string) *build.Package {
	// get pwd for relative imports
	pwd, err := os.Getwd()
	if err != nil {
		fmt.Printf("error getting pwd (required for relative imports): %s\n", err)
		os.Exit(1)
	}

	// read full package information
	pkg, err := build.Import(path, pwd, 0)
	if err != nil {
		fmt.Printf("error reading package: %s\n", err)
		os.Exit(1)
	}

	return pkg
}
980732
func (ctx *Context) loadPackage() error {
	ctx.loaded = true
	ctx.dirty = false
	ctx.statusCache = nil
	ctx.Package = make(map[string]*Package, len(ctx.Package))
	// We following the root symlink only in case the root of the repo is symlinked into the GOPATH
	// This could happen during on some CI that didn't checkout into the GOPATH
	rootdir, err := filepath.EvalSymlinks(ctx.RootDir)
	if err != nil {
		return err
	}
	err = filepath.Walk(rootdir, func(path string, info os.FileInfo, err error) error {
		if info == nil {
			return err
		}
		if !info.IsDir() {
			// We replace the directory path (followed by the symlink), to the real go repo package name/path
			// ex : replace "<somewhere>/govendor.source.repo" to "github.com/kardianos/govendor"
			path = strings.Replace(path, rootdir, ctx.RootDir, 1)
			_, err = ctx.addFileImports(path, ctx.RootGopath)
			return err
		}
		name := info.Name()
		// Still go into "_workspace" to aid godep migration.
		if name == "_workspace" {
			return nil
		}
		switch name[0] {
		case '.', '_':
			return filepath.SkipDir
		}
		switch name {
		case "testdata", "node_modules":
			return filepath.SkipDir
		}
		return nil
	})
	if err != nil {
		return err
	}
	// Finally, set any unset status.
	return ctx.determinePackageStatus()
}
481154
func GuessPackageFromDir(dir string) (pkg *build.Package, err error) {
	absdir, err := filepath.Abs(dir)
	if err != nil {
		return
	}

	dirsplit := strings.Split(absdir, string(os.PathSeparator))
	for i, n := 1, len(dirsplit); i < n; i++ {
		trypath := strings.Join(dirsplit[i:], string(os.PathSeparator))
		if pkg, err = build.Import(trypath, absdir, 0); err == nil {
			return
		}
	}

	return nil, ErrorImpossibleImportDir1.New(nil, absdir)
}
1258484
func (g *Generator) defaultGoPackage() string {
	p := g.PackageImportPath
	if i := strings.LastIndex(p, "/"); i >= 0 {
		p = p[i+1:]
	}
	if p == "" {
		return ""
	}

	p = strings.Map(badToUnderscore, p)
	// Identifier must not be keyword: insert _.
	if isGoKeyword[p] {
		p = "_" + p
	}
	// Identifier must not begin with digit: insert _.
	if r, _ := utf8.DecodeRuneInString(p); unicode.IsDigit(r) {
		p = "_" + p
	}
	return p
}
784216
func (a *API) ImportPath() string {
	return path.Join(a.BaseImportPath, a.PackageName())
}
695611
func (g *Generator) loadPackage(path string) (*loader.PackageInfo, error) {
	pkg := g.Program.Package(path)
	if pkg != nil {
		return pkg, nil
	}

	return nil, fmt.Errorf("failed to load package %q", path)
}