// GuessPackageFromDir return importable package from dir if possible
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)
}
526257
func Package(buffer Buffer, event *cue.Event) {
	if len(event.Frames) == 0 {
		buffer.AppendString(cue.UnknownPackage)
		return
	}
	buffer.AppendString(event.Frames[0].Package)
}
362389
func (ctx *Context) CopyPackage(destPath, srcPath, lookRoot, pkgPath string, ignoreFiles []string, tree bool, h hash.Hash, beforeCopy func(deps []string) error) error {
	if pathos.FileStringEquals(destPath, srcPath) {
		return fmt.Errorf("Attempting to copy package to same location %q.", destPath)
	}
	err := os.MkdirAll(destPath, 0777)
	if err != nil {
		return err
	}

	// Ensure the dest is empty of files.
	destDir, err := os.Open(destPath)
	if err != nil {
		return err
	}
	ignoreTest := false
	for _, ignore := range ctx.ignoreTag {
		if ignore == "test" {
			ignoreTest = true
			break
		}
	}

	fl, err := destDir.Readdir(-1)
	destDir.Close()
	if err != nil {
		return err
	}
	for _, fi := range fl {
		if fi.IsDir() {
			if tree {
				err = errors.Wrap(os.RemoveAll(filepath.Join(destPath, fi.Name())), "remove all existing tree entries")
				if err != nil {
					return err
				}
			}
			continue
		}
		err = errors.Wrap(os.Remove(filepath.Join(destPath, fi.Name())), "remove existing file")
		if err != nil {
			return err
		}
	}

	// Copy files into dest.
	srcDir, err := os.Open(srcPath)
	if err != nil {
		return errors.Wrap(err, "open srcPath directory")
	}

	fl, err = srcDir.Readdir(-1)
	srcDir.Close()
	if err != nil {
		return errors.Wrap(err, "src readdir")
	}
	if h != nil {
		// Write relative path to GOPATH.
		h.Write([]byte(strings.Trim(pkgPath, "/")))
		// Sort file list to present a stable hash.
		sort.Sort(fileInfoSort(fl))
	}
fileLoop:
	for _, fi := range fl {
		name := fi.Name()
		if name[0] == '.' {
			continue
		}
		if fi.IsDir() {
			isTestdata := name == "testdata"
			if !tree && !isTestdata {
				continue
			}
			if name[0] == '_' {
				continue
			}
			if ignoreTest {
				if strings.HasSuffix(name, "_test") || isTestdata {
					continue
				}
			}
			nextDestPath := filepath.Join(destPath, name)
			nextSrcPath := filepath.Join(srcPath, name)
			var nextIgnoreFiles, deps []string
			if !isTestdata && !strings.Contains(pkgPath, "/testdata/") {
				nextIgnoreFiles, deps, err = ctx.getIgnoreFiles(nextSrcPath)
				if err != nil {
					return err
				}
			}
			if beforeCopy != nil {
				err = beforeCopy(deps)
				if err != nil {
					return errors.Wrap(err, "beforeCopy")
				}
			}
			err = ctx.CopyPackage(nextDestPath, nextSrcPath, lookRoot, path.Join(pkgPath, name), nextIgnoreFiles, true, h, beforeCopy)
			if err != nil {
				return errors.Wrapf(err,
					"CopyPackage dest=%q src=%q lookRoot=%q pkgPath=%q ignoreFiles=%q tree=%t has beforeCopy=%t",
					nextDestPath, nextSrcPath, lookRoot, path.Join(pkgPath, name), nextIgnoreFiles, true, beforeCopy != nil,
				)
			}
			continue
		}
		for _, ignore := range ignoreFiles {
			if pathos.FileStringEquals(name, ignore) {
				continue fileLoop
			}
		}
		if h != nil {
			h.Write([]byte(name))
		}
		err = copyFile(
			filepath.Join(destPath, name),
			filepath.Join(srcPath, name),
			h,
		)
		if err != nil {
			return errors.Wrapf(err, "copyFile dest=%q src=%q", filepath.Join(destPath, name), filepath.Join(srcPath, name))
		}
	}

	return errors.Wrapf(licenseCopy(lookRoot, srcPath, filepath.Join(ctx.RootDir, ctx.VendorFolder), pkgPath), "licenseCopy srcPath=%q", srcPath)
}
432638
func (l *Loader) IsConfigDir(path string) bool {
	return l.parser.IsConfigDir(path)
}
487476
func TypeByPackageName(pkgPath string, name string) Type {
	initOnce.Do(discoverTypes)
	pkgTypes := packages[pkgPath]
	if pkgTypes == nil {
		return nil
	}
	return Type2(pkgTypes[name])
}
367762
func FindAllSubPackages(importPath string, srcDir string) (pkglist *PackageList, err error) {
	pkglist = &PackageList{}
	if srcDir, err = filepath.Abs(srcDir); err != nil {
		return
	}
	if importPath == "" {
		var pkg *build.Package
		if pkg, err = GuessPackageFromDir(srcDir); err != nil {
			if !ErrorImpossibleImportDir1.Match(err) {
				return
			}
			if IsGoModDir(srcDir) {
				var mods []Module
				mods, err = ParseGoMod(srcDir)
				if err != nil {
					return
				}
				err = collectModule(pkglist, mods)
			}
			return nil, ErrorImpossibleImportDir1.New(nil, srcDir)
		}
		importPath = pkg.ImportPath
	}
	if err = collectPackage(pkglist, importPath, srcDir); err != nil {
		return
	}
	return
}
1223541
func MustParsePackage(input string) *Package {
	parsed, err := ParsePackage(input)
	if err != nil {
		panic(err)
	}
	return parsed
}
582731
func listPackages(dir string) (directories []string) {
	// add subdirectories
	files, err := ioutil.ReadDir(dir)
	if err != nil {
		complete.Log("failed reading directory %s: %s", dir, err)
		return
	}

	// build paths array
	paths := make([]string, 0, len(files)+1)
	for _, f := range files {
		if f.IsDir() {
			paths = append(paths, filepath.Join(dir, f.Name()))
		}
	}
	paths = append(paths, dir)

	// import packages according to given paths
	for _, p := range paths {
		pkg, err := build.ImportDir(p, 0)
		if err != nil {
			complete.Log("failed importing directory %s: %s", p, err)
			continue
		}
		directories = append(directories, pkg.Dir)
	}
	return
}
953646
func expandPkgDir(ctx context.Context, c cipd.Client, packagePrefix string) ([]string, error) {
	if !strings.HasSuffix(packagePrefix, "/") {
		return []string{packagePrefix}, nil
	}
	pkgs, err := c.ListPackages(ctx, packagePrefix, false, false)
	if err != nil {
		return nil, err
	}
	// Skip directories.
	var out []string
	for _, p := range pkgs {
		if !strings.HasSuffix(p, "/") {
			out = append(out, p)
		}
	}
	if len(out) == 0 {
		return nil, fmt.Errorf("no packages under %s", packagePrefix)
	}
	return out, nil
}
1320758
func predictPackages(a complete.Args) (prediction []string) {
	prediction = []string{a.Last}
	lastPrediction := ""
	for len(prediction) == 1 && (lastPrediction == "" || lastPrediction != prediction[0]) {
		// if only one prediction, predict files within this prediction,
		// for example, if the user entered 'pk' and we have a package named 'pkg',
		// which is the only package prefixed with 'pk', we will automatically go one
		// level deeper and give the user the 'pkg' and all the nested packages within
		// that package.
		lastPrediction = prediction[0]
		a.Last = prediction[0]
		prediction = predictLocalAndSystem(a)
	}
	return
}
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
}
161879
func allPackagesInFS(pattern string) []string {
	pkgs := matchPackagesInFS(pattern)
	if len(pkgs) == 0 {
		fmt.Fprintf(os.Stderr, "warning: %q matched no packages\n", pattern)
	}
	return pkgs
}
608706
func (u Universe) Package(packagePath string) *Package {
	if p, ok := u[packagePath]; ok {
		return p
	}
	p := &Package{
		Path:      packagePath,
		Types:     map[string]*Type{},
		Functions: map[string]*Type{},
		Variables: map[string]*Type{},
		Imports:   map[string]*Package{},
	}
	u[packagePath] = p
	return p
}
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
}
689875
func (ctx *Context) findPackageChild(ck *Package) []*Package {
	out := make([]*Package, 0, 3)
	for _, pkg := range ctx.Package {
		if pkg == ck {
			continue
		}
		if !pkg.inVendor {
			continue
		}
		if pkg.Status.Presence == PresenceTree {
			continue
		}
		if strings.HasPrefix(pkg.Path, ck.Path+"/") {
			out = append(out, pkg)
		}
	}
	return out
}
56842
func LocatePackagedPEMDir() (dir string, err error) {
	if packagedCertDir != "" {
		dir = packagedCertDir
		return
	} else if _certPath != "" {
		packagedCertDir = _certPath
		dir = packagedCertDir
		return
	}

	var binDir string
	binDir, err = executable.Dir()
	if err != nil {
		return
	}

	cwd, _ := os.Getwd()

	searchList := []string{
		binDir + "../certs", // deb: certs is one up from bin
		cwd + "/testcerts",  // tests: certs is 4 up from _test files
	}

	// src-containing git checkout: $GOPATH/certs
	if goPath := os.Getenv("GOPATH"); goPath != "" {
		for _, gp := range filepath.SplitList(goPath) {
			searchList = append(searchList, gp+"/certs")
		}
	}

	// non-src git checkout: search for a certs/ starting deepest-first at
	// $GOPATH/src/foo/bar/, where foo/bar is the package calling into this
	// one. This works if foo/bar has subpackages which call this function,
	// even indirectly by way of the other functions in this package.
	if callerDir, ok := callerPkgDir(); ok {
		if certsDir, ok := searchUpwards(callerDir, "certs"); ok {
			searchList = append(searchList, certsDir)
		}
	}

	for _, l := range searchList {
		d := filepath.Clean(l)
		var info os.FileInfo
		if info, err = os.Stat(d); err == nil && info.IsDir() {
			packagedCertDir = d
			dir = packagedCertDir
			return
		}
	}
	err = fmt.Errorf("couldn't locate packaged PEMs in any of %v", searchList)
	return
}
284539
func FindPackage(ctxt *build.Context, path, dir string, mode build.ImportMode) (*build.Package, error) {
	if !useVendor {
		return ctxt.Import(path, dir, mode)
	}

	// First, walk up the filesystem from dir looking for vendor directories
	var vendorDir string
	for tmp := dir; vendorDir == "" && tmp != "/"; tmp = filepath.Dir(tmp) {
		dname := filepath.Join(tmp, "vendor", filepath.FromSlash(path))
		fd, err := os.Open(dname)
		if err != nil {
			continue
		}
		// Directories are only valid if they contain at least one file
		// with suffix ".go" (this also ensures that the file descriptor
		// we have is in fact a directory)
		names, err := fd.Readdirnames(-1)
		if err != nil {
			continue
		}
		for _, name := range names {
			if strings.HasSuffix(name, ".go") {
				vendorDir = filepath.ToSlash(dname)
				break
			}
		}
	}

	if vendorDir != "" {
		pkg, err := ctxt.ImportDir(vendorDir, mode)
		if err != nil {
			return nil, err
		}
		// Go tries to derive a valid import path for the package, but
		// it's wrong (it includes "/vendor/"). Overwrite it here.
		pkg.ImportPath = path
		return pkg, nil
	}

	return ctxt.Import(path, dir, mode)
}