// Package compiles information about a mage package.
518198
func Package(path string, files []string) (*PkgInfo, error) {
	start := time.Now()
	defer func() {
		debug.Println("time parse Magefiles:", time.Since(start))
	}()
	fset := token.NewFileSet()
	pkg, err := getPackage(path, files, fset)
	if err != nil {
		return nil, err
	}
	p := doc.New(pkg, "./", 0)
	pi := &PkgInfo{
		AstPkg:      pkg,
		DocPkg:      p,
		Description: toOneLine(p.Doc),
	}

	setNamespaces(pi)
	setFuncs(pi)

	hasDupes, names := checkDupeTargets(pi)
	if hasDupes {
		msg := "Build targets must be case insensitive, thus the following targets conflict:\n"
		for _, v := range names {
			if len(v) > 1 {
				msg += "  " + strings.Join(v, ", ") + "\n"
			}
		}
		return nil, errors.New(msg)
	}

	return pi, nil
}
474229
func Packages(context *generator.Context, arguments *args.GeneratorArgs) generator.Packages {
	boilerplate, err := arguments.LoadGoBoilerplate()
	if err != nil {
		klog.Fatalf("Failed loading boilerplate: %v", err)
	}

	customArgs, ok := arguments.CustomArgs.(*clientgenargs.CustomArgs)
	if !ok {
		klog.Fatalf("cannot convert arguments.CustomArgs to clientgenargs.CustomArgs")
	}
	includedTypesOverrides := customArgs.IncludedTypesOverrides

	applyGroupOverrides(context.Universe, customArgs)

	gvToTypes := map[clientgentypes.GroupVersion][]*types.Type{}
	groupGoNames := make(map[clientgentypes.GroupVersion]string)
	for gv, inputDir := range customArgs.GroupVersionPackages() {
		p := context.Universe.Package(path.Vendorless(inputDir))

		// If there's a comment of the form "// +groupGoName=SomeUniqueShortName", use that as
		// the Go group identifier in CamelCase. It defaults
		groupGoNames[gv] = namer.IC(strings.Split(gv.Group.NonEmpty(), ".")[0])
		if override := types.ExtractCommentTags("+", p.Comments)["groupGoName"]; override != nil {
			groupGoNames[gv] = namer.IC(override[0])
		}

		// Package are indexed with the vendor prefix stripped
		for n, t := range p.Types {
			// filter out types which are not included in user specified overrides.
			typesOverride, ok := includedTypesOverrides[gv]
			if ok {
				found := false
				for _, typeStr := range typesOverride {
					if typeStr == n {
						found = true
						break
					}
				}
				if !found {
					continue
				}
			} else {
				// User has not specified any override for this group version.
				// filter out types which dont have genclient.
				if tags := util.MustParseClientGenTags(append(t.SecondClosestCommentLines, t.CommentLines...)); !tags.GenerateClient {
					continue
				}
			}
			if _, found := gvToTypes[gv]; !found {
				gvToTypes[gv] = []*types.Type{}
			}
			gvToTypes[gv] = append(gvToTypes[gv], t)
		}
	}

	var packageList []generator.Package
	clientsetPackage := filepath.Join(arguments.OutputPackagePath, customArgs.ClientsetName)

	packageList = append(packageList, packageForClientset(customArgs, clientsetPackage, groupGoNames, boilerplate))
	packageList = append(packageList, packageForScheme(customArgs, clientsetPackage, arguments.OutputBase, groupGoNames, boilerplate))
	if customArgs.FakeClient {
		packageList = append(packageList, fake.PackageForClientset(customArgs, clientsetPackage, groupGoNames, boilerplate))
	}

	// If --clientset-only=true, we don't regenerate the individual typed clients.
	if customArgs.ClientsetOnly {
		return generator.Packages(packageList)
	}

	orderer := namer.Orderer{Namer: namer.NewPrivateNamer(0)}
	gvPackages := customArgs.GroupVersionPackages()
	for _, group := range customArgs.Groups {
		for _, version := range group.Versions {
			gv := clientgentypes.GroupVersion{Group: group.Group, Version: version.Version}
			types := gvToTypes[gv]
			inputPath := gvPackages[gv]
			packageList = append(packageList, packageForGroup(gv, orderer.OrderTypes(types), clientsetPackage, group.PackageName, groupGoNames[gv], customArgs.ClientsetAPIPath, arguments.OutputBase, inputPath, boilerplate))
			if customArgs.FakeClient {
				packageList = append(packageList, fake.PackageForGroup(gv, orderer.OrderTypes(types), clientsetPackage, group.PackageName, groupGoNames[gv], inputPath, boilerplate))
			}
		}
	}

	return generator.Packages(packageList)
}
853962
func allPackages(pattern string) []string {
	pkgs := matchPackages(pattern)
	if len(pkgs) == 0 {
		fmt.Fprintf(os.Stderr, "warning: %q matched no packages\n", pattern)
	}
	return pkgs
}
1030475
func (pkg *Package) Copy() *Package {
	cpy := *pkg
	cpy.Path = pkg.Path.Copy()
	return &cpy
}
28077
func NewPackage(id int64, j Job) *Package {
	p := &Package{
		ID:         id,
		status:     Queued,
		job:        j,
		statusLock: new(sync.RWMutex),
	}

	return p
}
916208
func parsePackage(ctx *context, jsonRoot *jsongo.JSONNode) (*Package, error) {
	logf(" %s (version: %s) contains: %d services, %d messages, %d types, %d enums, %d unions, %d aliases",
		ctx.packageName,
		jsonRoot.Map(vlAPIVersion).Get(),
		jsonRoot.Map(objServices).Len(),
		jsonRoot.Map(objMessages).Len(),
		jsonRoot.Map(objTypes).Len(),
		jsonRoot.Map(objEnums).Len(),
		jsonRoot.Map(objUnions).Len(),
		jsonRoot.Map(objAliases).Len(),
	)

	pkg := Package{
		APIVersion: jsonRoot.Map(vlAPIVersion).Get().(string),
		RefMap:     make(map[string]string),
	}

	// parse enums
	enums := jsonRoot.Map(objEnums)
	pkg.Enums = make([]Enum, enums.Len())
	for i := 0; i < enums.Len(); i++ {
		enumNode := enums.At(i)

		enum, err := parseEnum(ctx, enumNode)
		if err != nil {
			return nil, err
		}
		pkg.Enums[i] = *enum
		pkg.RefMap[toApiType(enum.Name)] = enum.Name
	}
	// sort enums
	sort.SliceStable(pkg.Enums, func(i, j int) bool {
		return pkg.Enums[i].Name < pkg.Enums[j].Name
	})

	// parse aliases
	aliases := jsonRoot.Map(objAliases)
	if aliases.GetType() == jsongo.TypeMap {
		pkg.Aliases = make([]Alias, aliases.Len())
		for i, key := range aliases.GetKeys() {
			aliasNode := aliases.At(key)

			alias, err := parseAlias(ctx, key.(string), aliasNode)
			if err != nil {
				return nil, err
			}
			pkg.Aliases[i] = *alias
			pkg.RefMap[toApiType(alias.Name)] = alias.Name
		}
	}
	// sort aliases to ensure consistent order
	sort.Slice(pkg.Aliases, func(i, j int) bool {
		return pkg.Aliases[i].Name < pkg.Aliases[j].Name
	})

	// parse types
	types := jsonRoot.Map(objTypes)
	pkg.Types = make([]Type, types.Len())
	for i := 0; i < types.Len(); i++ {
		typNode := types.At(i)

		typ, err := parseType(ctx, typNode)
		if err != nil {
			return nil, err
		}
		pkg.Types[i] = *typ
		pkg.RefMap[toApiType(typ.Name)] = typ.Name
	}
	// sort types
	sort.SliceStable(pkg.Types, func(i, j int) bool {
		return pkg.Types[i].Name < pkg.Types[j].Name
	})

	// parse unions
	unions := jsonRoot.Map(objUnions)
	pkg.Unions = make([]Union, unions.Len())
	for i := 0; i < unions.Len(); i++ {
		unionNode := unions.At(i)

		union, err := parseUnion(ctx, unionNode)
		if err != nil {
			return nil, err
		}
		pkg.Unions[i] = *union
		pkg.RefMap[toApiType(union.Name)] = union.Name
	}
	// sort unions
	sort.SliceStable(pkg.Unions, func(i, j int) bool {
		return pkg.Unions[i].Name < pkg.Unions[j].Name
	})

	// parse messages
	messages := jsonRoot.Map(objMessages)
	pkg.Messages = make([]Message, messages.Len())
	for i := 0; i < messages.Len(); i++ {
		msgNode := messages.At(i)

		msg, err := parseMessage(ctx, msgNode)
		if err != nil {
			return nil, err
		}
		pkg.Messages[i] = *msg
	}
	// sort messages
	sort.SliceStable(pkg.Messages, func(i, j int) bool {
		return pkg.Messages[i].Name < pkg.Messages[j].Name
	})

	// parse services
	services := jsonRoot.Map(objServices)
	if services.GetType() == jsongo.TypeMap {
		pkg.Services = make([]Service, services.Len())
		for i, key := range services.GetKeys() {
			svcNode := services.At(key)

			svc, err := parseService(ctx, key.(string), svcNode)
			if err != nil {
				return nil, err
			}
			pkg.Services[i] = *svc
		}
	}
	// sort services
	sort.Slice(pkg.Services, func(i, j int) bool {
		// dumps first
		if pkg.Services[i].Stream != pkg.Services[j].Stream {
			return pkg.Services[i].Stream
		}
		return pkg.Services[i].RequestType < pkg.Services[j].RequestType
	})

	printPackage(&pkg)

	return &pkg, nil
}
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
}
349730
func (cfg *ubuntuCloudConfig) PackageProxy() string {
	proxy, _ := cfg.attrs["apt_proxy"].(string)
	return proxy
}
372105
func Packages(c *generator.Context, arguments *args.GeneratorArgs) generator.Packages {
	pkgs := generator.Packages{}
	c.FileTypes = map[string]generator.FileType{
		importBossFileType: importRuleFile{},
	}

	for _, p := range c.Universe {
		if !arguments.InputIncludes(p) {
			// Don't run on e.g. third party dependencies.
			continue
		}
		savedPackage := p
		pkgs = append(pkgs, &generator.DefaultPackage{
			PackageName: p.Name,
			PackagePath: p.Path,
			// GeneratorFunc returns a list of generators. Each generator makes a
			// single file.
			GeneratorFunc: func(c *generator.Context) (generators []generator.Generator) {
				return []generator.Generator{&importRules{
					myPackage: savedPackage,
				}}
			},
			FilterFunc: func(c *generator.Context, t *types.Type) bool {
				return false
			},
		})
	}

	return pkgs
}
1223541
func MustParsePackage(input string) *Package {
	parsed, err := ParsePackage(input)
	if err != nil {
		panic(err)
	}
	return parsed
}
613670
func (ctx *Context) newPackage(p *build.Package) (*Package, error) {
	pkg := &Package{
		Context: ctx,
		Package: p,
	}
	for _, i := range p.Imports {
		dep, ok := ctx.pkgs[i]
		if !ok {
			return nil, errors.Errorf("newPackage(%q): could not locate dependant package %q ", p.Name, i)
		}
		pkg.Imports = append(pkg.Imports, dep)
	}
	return pkg, nil
}
869314
func (m *CommandAck) Pack() []byte {
	data := new(bytes.Buffer)
	binary.Write(data, binary.LittleEndian, m.COMMAND)
	binary.Write(data, binary.LittleEndian, m.RESULT)
	return data.Bytes()
}
526257
func Package(buffer Buffer, event *cue.Event) {
	if len(event.Frames) == 0 {
		buffer.AppendString(cue.UnknownPackage)
		return
	}
	buffer.AppendString(event.Frames[0].Package)
}
1183546
func (c *Context) PACK(code int, data interface{}) (err error) {
	c.response.Header().Set("Content-Type", "application/msgpack; charset=utf-8")
	c.response.WriteHeader(code)
	if data != nil {
		codec.NewEncoder(c.response, &mh).Encode(data)
	}
	return
}
1114609
func (r *report) addPackage(p *gocov.Package) {
	i := sort.Search(len(r.packages), func(i int) bool {
		return r.packages[i].Name >= p.Name
	})
	if i < len(r.packages) && r.packages[i].Name == p.Name {
		r.packages[i].Accumulate(p)
	} else {
		head := r.packages[:i]
		tail := append([]*gocov.Package{p}, r.packages[i:]...)
		r.packages = append(head, tail...)
	}
}
666907
func doPackage(names []string, basePkg *Package) *Package {
	var files []*File
	var astFiles []*ast.File
	fs := token.NewFileSet()
	for _, name := range names {
		data, err := ioutil.ReadFile(name)
		if err != nil {
			// Warn but continue to next package.
			warnf("%s: %s", name, err)
			return nil
		}
		checkBuildTag(name, data)
		var parsedFile *ast.File
		if strings.HasSuffix(name, ".go") {
			parsedFile, err = parser.ParseFile(fs, name, data, 0)
			if err != nil {
				warnf("%s: %s", name, err)
				return nil
			}
			astFiles = append(astFiles, parsedFile)
		}
		files = append(files, &File{
			fset:    fs,
			content: data,
			name:    name,
			file:    parsedFile,
			dead:    make(map[ast.Node]bool),
		})
	}
	if len(astFiles) == 0 {
		return nil
	}
	pkg := new(Package)
	pkg.path = astFiles[0].Name.Name
	pkg.files = files
	// Type check the package.
	errs := pkg.check(fs, astFiles)
	if errs != nil {
		if vcfg.SucceedOnTypecheckFailure {
			os.Exit(0)
		}
		if *verbose || mustTypecheck {
			for _, err := range errs {
				fmt.Fprintf(os.Stderr, "%v\n", err)
			}
			if mustTypecheck {
				// This message could be silenced, and we could just exit,
				// but it might be helpful at least at first to make clear that the
				// above errors are coming from vet and not the compiler
				// (they often look like compiler errors, such as "declared but not used").
				errorf("typecheck failures")
			}
		}
	}

	// Check.
	chk := make(map[ast.Node][]func(*File, ast.Node))
	for typ, set := range checkers {
		for name, fn := range set {
			if vet(name) {
				chk[typ] = append(chk[typ], fn)
			}
		}
	}
	for _, file := range files {
		file.pkg = pkg
		file.basePkg = basePkg
		file.checkers = chk
		if file.file != nil {
			file.walkFile(file.name, file.file)
		}
	}
	return pkg
}
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,
	}
}