// checkPackageImportsFromDepExist ensures that, if the dep is already selected,
// the newly-required set of packages being placed on it exist and are valid.
971611
func (s *solver) checkPackageImportsFromDepExist(a atomWithPackages, cdep completeDep) error {
	sel, is := s.sel.selected(cdep.workingConstraint.Ident)
	if !is {
		// dep is not already selected; nothing to do
		return nil
	}

	ptree, err := s.b.ListPackages(sel.a.id, sel.a.v)
	if err != nil {
		// TODO(sdboyer) handle this more gracefully
		return err
	}

	e := &depHasProblemPackagesFailure{
		goal: dependency{
			depender: a.a,
			dep:      cdep,
		},
		v:    sel.a.v,
		prob: make(map[string]error),
	}

	for _, pkg := range cdep.pl {
		perr, has := ptree.Packages[pkg]
		if !has || perr.Err != nil {
			if has {
				e.prob[pkg] = perr.Err
			} else {
				e.prob[pkg] = nil
			}
		}
	}

	if len(e.prob) > 0 {
		return e
	}
	return nil
}
259992
func (p PackageInfo) ImportedPackageComputedNames() []string {
	result := []string{}
	seen := map[string]bool{
		p.ComputedPackage: true,
	}
	for _, d := range p.Deps {
		pkg := d.ComputedPackage
		if seen[pkg] {
			continue
		}
		seen[pkg] = true
		result = append(result, pkg)
	}
	return result
}
1095583
func (g *GenOpts) CheckOpts() error {
	if !filepath.IsAbs(g.Target) {
		if _, err := filepath.Abs(g.Target); err != nil {
			return fmt.Errorf("could not locate target %s: %v", g.Target, err)
		}
	}
	if filepath.IsAbs(g.ServerPackage) {
		return fmt.Errorf("you shouldn't specify an absolute path in --server-package: %s", g.ServerPackage)
	}
	if !filepath.IsAbs(g.Spec) && !strings.HasPrefix(g.Spec, "http://") && !strings.HasPrefix(g.Spec, "https://") {
		if _, err := filepath.Abs(g.Spec); err != nil {
			return fmt.Errorf("could not locate spec: %s", g.Spec)
		}
	}
	return nil
}
542936
func (ctx *Context) ModifyImport(imp *pkgspec.Pkg, mod Modify, mops ...ModifyOption) error {
	var err error
	if ctx.added == nil {
		ctx.added = make(map[string]bool, 10)
	}
	// Grap the origin of the pkg spec from the vendor file as needed.
	if len(imp.Origin) == 0 {
		for _, vpkg := range ctx.VendorFile.Package {
			if vpkg.Remove {
				continue
			}
			if vpkg.Path == imp.Path {
				imp.Origin = vpkg.Origin
			}
		}
	}
	if !imp.MatchTree {
		if !ctx.added[imp.PathOrigin()] {
			err = ctx.modify(imp, mod, mops)
			if err != nil {
				return err
			}
		}
		return nil
	}
	list, err := ctx.Status()
	if err != nil {
		return err
	}
	// If add any matched from "...".
	match := imp.Path + "/"
	for _, item := range list {
		if ctx.added[item.Pkg.PathOrigin()] {
			continue
		}
		if item.Pkg.Path != imp.Path && !strings.HasPrefix(item.Pkg.Path, match) {
			continue
		}
		if imp.HasVersion {
			item.Pkg.HasVersion = true
			item.Pkg.Version = imp.Version
		}
		item.Pkg.HasOrigin = imp.HasOrigin
		item.Pkg.Origin = path.Join(imp.PathOrigin(), strings.TrimPrefix(item.Pkg.Path, imp.Path))
		err = ctx.modify(item.Pkg, mod, mops)
		if err != nil {
			return err
		}
	}
	// cache for later use
	ctx.TreeImport = append(ctx.TreeImport, imp)
	return nil
}
583046
func findTypeDef(importPath, typeName string) (*ast.TypeSpec, error) {
	cwd, err := os.Getwd()
	if err != nil {
		return nil, err
	}

	conf := loader.Config{
		ParserMode: goparser.SpuriousErrors,
		Cwd:        cwd,
	}

	conf.Import(importPath)

	lprog, err := conf.Load()
	if err != nil {
		return nil, err
	}

	// If the pkg is vendored, the actual pkg path is going to resemble
	// something like "{importPath}/vendor/{importPath}"
	for k := range lprog.AllPackages {
		realPkgPath := k.Path()

		if strings.Contains(realPkgPath, "vendor/"+importPath) {
			importPath = realPkgPath
		}
	}

	pkgInfo := lprog.Package(importPath)

	if pkgInfo == nil {
		return nil, errors.New("package was nil")
	}

	// TODO: possibly cache pkgInfo since it's an expensive operation

	for i := range pkgInfo.Files {
		for _, astDeclaration := range pkgInfo.Files[i].Decls {
			if generalDeclaration, ok := astDeclaration.(*ast.GenDecl); ok && generalDeclaration.Tok == token.TYPE {
				for _, astSpec := range generalDeclaration.Specs {
					if typeSpec, ok := astSpec.(*ast.TypeSpec); ok {
						if typeSpec.Name.String() == typeName {
							return typeSpec, nil
						}
					}
				}
			}
		}
	}
	return nil, errors.New("type spec not found")
}
1297865
func allExportedOrBuiltin(types []reflect.Type) bool {
	for _, typ := range types {
		for typ.Kind() == reflect.Ptr {
			typ = typ.Elem()
		}
		// PkgPath will be non-empty even for an exported type,
		// so we need to check the type name as well.
		if !isExported(typ.Name()) && typ.PkgPath() != "" {
			return false
		}
	}
	return true
}
1004675
func CheckPackages(c context.Context, names []string, includeHidden bool) ([]string, error) {
	if len(names) == 0 {
		return nil, nil
	}

	pkgs := make([]*Package, len(names))
	for i, n := range names {
		pkgs[i] = &Package{Name: n}
	}

	if err := datastore.Get(c, pkgs); err != nil {
		merr, ok := err.(errors.MultiError)
		if !ok {
			return nil, transient.Tag.Apply(err)
		}
		existing := pkgs[:0]
		for i, pkg := range pkgs {
			switch err := merr[i]; {
			case err == nil:
				existing = append(existing, pkg)
			case err != datastore.ErrNoSuchEntity:
				return nil, errors.Annotate(err, "failed to fetch %q", pkg.Name).Tag(transient.Tag).Err()
			}
		}
		pkgs = existing
	}

	out := make([]string, 0, len(pkgs))
	for _, p := range pkgs {
		if !p.Hidden || includeHidden {
			out = append(out, p.Name)
		}
	}
	return out, nil
}
799287
func isExportedOrBuiltin(t reflect.Type) bool {
	for t.Kind() == reflect.Ptr {
		t = t.Elem()
	}
	// PkgPath will be non-empty even for an exported type,
	// so we need to check the type name as well.
	return isExported(t.Name()) || t.PkgPath() == ""
}
1331307
func OptImportOptionsIgnoreKeyCheck(b bool) ImportOption {
	return func(o *ImportOptions) error {
		o.IgnoreKeyCheck = b
		return nil
	}
}
868985
func determinePackagePrefix(dir string) (string, error) {
	gopathList := os.Getenv("GOPATH")
	if gopathList == "" {
		return "", errors.New("$GOPATH is not set")
	}

	for _, gopath := range filepath.SplitList(gopathList) {
		packagePath, err := filepath.Rel(filepath.Join(gopath, "src"), dir)
		if err != nil {
			return "", err
		}

		// The match is valid only if it's within the directory tree.
		if !strings.HasPrefix(packagePath, "..") {
			return packagePath, nil
		}
	}

	return "", fmt.Errorf("directory %q is not inside $GOPATH/src", dir)
}
52561
func dropEmptyImportDeclarations(decl ast.Decl) bool {
	switch t := decl.(type) {
	case *ast.GenDecl:
		if t.Tok != token.IMPORT {
			return false
		}
		specs := []ast.Spec{}
		for _, s := range t.Specs {
			switch spec := s.(type) {
			case *ast.ImportSpec:
				if spec.Name != nil && spec.Name.Name == "_" {
					continue
				}
				specs = append(specs, spec)
			}
		}
		if len(specs) == 0 {
			return true
		}
		t.Specs = specs
	}
	return false
}
813150
func (c *client) checkForImportServices(acc *Account, msg []byte) {
	if acc == nil || acc.imports.services == nil {
		return
	}
	acc.mu.RLock()
	rm := acc.imports.services[string(c.pa.subject)]
	invalid := rm != nil && rm.invalid
	acc.mu.RUnlock()

	// Get the results from the other account for the mapped "to" subject.
	// If we have been marked invalid simply return here.
	if rm != nil && !invalid && rm.acc != nil && rm.acc.sl != nil {
		var nrr []byte
		if rm.ae {
			acc.removeServiceImport(rm.from)
		}
		if c.pa.reply != nil {
			// We want to remap this to provide anonymity.
			nrr = c.newServiceReply()
			rm.acc.addImplicitServiceImport(acc, string(nrr), string(c.pa.reply), true, nil)
			// If this is a client connection and we are in
			// gateway mode, we need to send RS+ to local cluster
			// and possibly to inbound GW connections for
			// which we are in interest-only mode.
			if c.kind == CLIENT && c.srv.gateway.enabled {
				c.srv.gatewayHandleServiceImport(rm.acc, nrr, c, 1)
			}
		}
		// FIXME(dlc) - Do L1 cache trick from above.
		rr := rm.acc.sl.Match(rm.to)

		// If we are a route or gateway and this message is flipped to a queue subscriber we
		// need to handle that since the processMsgResults will want a queue filter.
		if (c.kind == ROUTER || c.kind == GATEWAY) && c.pa.queues == nil && len(rr.qsubs) > 0 {
			c.makeQFilter(rr.qsubs)
		}

		// If this is not a gateway connection but gateway is enabled,
		// try to send this converted message to all gateways.
		if c.srv.gateway.enabled && (c.kind == CLIENT || c.kind == SYSTEM || c.kind == LEAF) {
			queues := c.processMsgResults(rm.acc, rr, msg, []byte(rm.to), nrr, pmrCollectQueueNames)
			c.sendMsgToGateways(rm.acc, msg, []byte(rm.to), nrr, queues)
		} else {
			c.processMsgResults(rm.acc, rr, msg, []byte(rm.to), nrr, pmrNoFlag)
		}
	}
}
1083037
func DefaultImporter(path string, srcDir string) *ast.Package {
	bpkg, err := build.Default.Import(path, srcDir, 0)
	if err != nil {
		return nil
	}
	goFiles := make(map[string]bool)
	for _, f := range bpkg.GoFiles {
		goFiles[f] = true
	}
	for _, f := range bpkg.CgoFiles {
		goFiles[f] = true
	}
	shouldInclude := func(d os.FileInfo) bool {
		return goFiles[d.Name()]
	}
	pkgs, err := parser.ParseDir(FileSet, bpkg.Dir, shouldInclude, 0, DefaultImportPathToName)
	if err != nil {
		if Debug {
			switch err := err.(type) {
			case scanner.ErrorList:
				for _, e := range err {
					debugp("\t%v: %s", e.Pos, e.Msg)
				}
			default:
				debugp("\terror parsing %s: %v", bpkg.Dir, err)
			}
		}
		return nil
	}
	if pkg := pkgs[bpkg.Name]; pkg != nil {
		return pkg
	}
	if Debug {
		debugp("package not found by ParseDir!")
	}
	return nil
}
364536
func validatePorts(to int64, from int64, expected expectedPortPair) bool {
	if to != expected.to_port || from != expected.from_port {
		return false
	}

	return true
}
437422
func (f *file) lintBlankImports() {
	// In package main and in tests, we don't complain about blank imports.
	if f.pkg.main || f.isTest() {
		return
	}

	// The first element of each contiguous group of blank imports should have
	// an explanatory comment of some kind.
	for i, imp := range f.f.Imports {
		pos := f.fset.Position(imp.Pos())

		if !isBlank(imp.Name) {
			continue // Ignore non-blank imports.
		}
		if i > 0 {
			prev := f.f.Imports[i-1]
			prevPos := f.fset.Position(prev.Pos())
			if isBlank(prev.Name) && prevPos.Line+1 == pos.Line {
				continue // A subsequent blank in a group.
			}
		}

		// This is the first blank import of a group.
		if imp.Doc == nil && imp.Comment == nil {
			ref := ""
			f.errorf(imp, 1, link(ref), category("imports"), "a blank import should be only in a main or test package, or have a comment justifying it")
		}
	}
}
841270
func (s *storeImpl) GetAllExportedEndpoints(ctx datastore.Context) ([]ExportedEndpoint, error) {
	defer ctx.Metrics().Stop(ctx.Metrics().Start("ServiceStore.GetAllExportedEndpoints"))
	searchRequest := newServiceDetailsElasticRequest(map[string]interface{}{
		"query": map[string]interface{}{
			"term": map[string]interface{}{
				"Endpoints.Purpose": "export",
			},
		},
		"fields": exportedEndpointFields,
		"size":   serviceDetailsLimit,
	})

	results, err := datastore.NewQuery(ctx).Execute(searchRequest)
	if err != nil {
		return nil, err
	}

	eps := []ExportedEndpoint{}
	for results.HasNext() {
		var result EndpointQueryResult
		err := results.Next(&result)
		if err != nil {
			return nil, err
		}
		endpoints := createExportedEndpoints(result)
		eps = append(eps, endpoints...)
	}

	return eps, nil
}
800763
func (s *selection) getRequiredPackagesIn(id ProjectIdentifier) map[string]int {
	// TODO(sdboyer) this is horribly inefficient to do on the fly; we need a method to
	// precompute it on pushing a new dep, and preferably with an immut
	// structure so that we can pop with zero cost.
	uniq := make(map[string]int)
	for _, dep := range s.deps[id.ProjectRoot] {
		for _, pkg := range dep.dep.pl {
			uniq[pkg] = uniq[pkg] + 1
		}
	}

	return uniq
}