// CalculatedBuildpacks will return back the buildpacks for the application.
498217
func (app Application) CalculatedBuildpacks() []string {
	buildpack := app.CalculatedBuildpack()
	switch {
	case app.Buildpacks != nil:
		return app.Buildpacks
	case len(buildpack) > 0:
		return []string{buildpack}
	default:
		return nil
	}
}
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
}
95837
func (bs *CustomBuildStrategy) CreateBuildPod(build *buildv1.Build, additionalCAs map[string]string, internalRegistryHost string) (*corev1.Pod, error) {
	strategy := build.Spec.Strategy.CustomStrategy
	if strategy == nil {
		return nil, errors.New("CustomBuildStrategy cannot be executed without CustomStrategy parameters")
	}

	codec := customBuildEncodingCodecFactory.LegacyCodec(buildv1.GroupVersion)
	if len(strategy.BuildAPIVersion) != 0 {
		gv, err := schema.ParseGroupVersion(strategy.BuildAPIVersion)
		if err != nil {
			return nil, &FatalError{fmt.Sprintf("failed to parse buildAPIVersion specified in custom build strategy (%q): %v", strategy.BuildAPIVersion, err)}
		}
		codec = customBuildEncodingCodecFactory.LegacyCodec(gv)
	}

	data, err := runtime.Encode(codec, build)
	if err != nil {
		return nil, fmt.Errorf("failed to encode the build: %v", err)
	}

	containerEnv := []corev1.EnvVar{
		{Name: "BUILD", Value: string(data)},
		{Name: "LANG", Value: "en_US.utf8"},
	}

	if build.Spec.Source.Git != nil {
		addSourceEnvVars(build.Spec.Source, &containerEnv)
	}

	if build.Spec.Output.To != nil {
		addOutputEnvVars(build.Spec.Output.To, &containerEnv)
		if err != nil {
			return nil, fmt.Errorf("failed to parse the output docker tag %q: %v", build.Spec.Output.To.Name, err)
		}
	}

	if len(strategy.From.Name) == 0 {
		return nil, errors.New("CustomBuildStrategy cannot be executed without image")
	}

	if len(strategy.Env) > 0 {
		containerEnv = append(containerEnv, strategy.Env...)
	}

	if strategy.ExposeDockerSocket {
		klog.V(2).Infof("ExposeDockerSocket is enabled for %s build", build.Name)
		containerEnv = append(containerEnv, corev1.EnvVar{Name: "DOCKER_SOCKET", Value: dockerSocketPath})
	}

	serviceAccount := build.Spec.ServiceAccount
	if len(serviceAccount) == 0 {
		serviceAccount = buildutil.BuilderServiceAccountName
	}

	privileged := true
	pod := &corev1.Pod{
		ObjectMeta: metav1.ObjectMeta{
			Name:      buildapihelpers.GetBuildPodName(build),
			Namespace: build.Namespace,
			Labels:    getPodLabels(build),
		},
		Spec: corev1.PodSpec{
			ServiceAccountName: serviceAccount,
			Containers: []corev1.Container{
				{
					Name:  CustomBuild,
					Image: strategy.From.Name,
					Env:   containerEnv,
					// TODO: run unprivileged https://github.com/openshift/origin/issues/662
					SecurityContext: &corev1.SecurityContext{
						Privileged: &privileged,
					},
					TerminationMessagePolicy: corev1.TerminationMessageFallbackToLogsOnError,
				},
			},
			RestartPolicy: corev1.RestartPolicyNever,
			NodeSelector:  build.Spec.NodeSelector,
		},
	}
	if build.Spec.CompletionDeadlineSeconds != nil {
		pod.Spec.ActiveDeadlineSeconds = build.Spec.CompletionDeadlineSeconds
	}

	if !strategy.ForcePull {
		pod.Spec.Containers[0].ImagePullPolicy = corev1.PullIfNotPresent
	} else {
		klog.V(2).Infof("ForcePull is enabled for %s build", build.Name)
		pod.Spec.Containers[0].ImagePullPolicy = corev1.PullAlways
	}
	pod.Spec.Containers[0].Resources = build.Spec.Resources
	if build.Spec.Source.Binary != nil {
		pod.Spec.Containers[0].Stdin = true
		pod.Spec.Containers[0].StdinOnce = true
	}

	if strategy.ExposeDockerSocket {
		setupDockerSocket(pod)
	}
	setupDockerSecrets(pod, &pod.Spec.Containers[0], build.Spec.Output.PushSecret, strategy.PullSecret, build.Spec.Source.Images)
	setOwnerReference(pod, build)
	setupSourceSecrets(pod, &pod.Spec.Containers[0], build.Spec.Source.SourceSecret)
	setupInputSecrets(pod, &pod.Spec.Containers[0], build.Spec.Source.Secrets)
	setupAdditionalSecrets(pod, &pod.Spec.Containers[0], build.Spec.Strategy.CustomStrategy.Secrets)
	setupContainersConfigs(build, pod)
	setupBuildCAs(build, pod, additionalCAs, internalRegistryHost)
	setupContainersStorage(pod, &pod.Spec.Containers[0]) // for unprivileged builds
	return pod, nil
}
738738
func (Actor) setBuildpack(config ApplicationConfig) types.FilteredString {
	buildpacks := config.DesiredApplication.Buildpacks

	if len(buildpacks) == 1 {
		var filtered types.FilteredString
		filtered.ParseValue(buildpacks[0])
		return filtered
	}

	if buildpacks != nil && len(buildpacks) == 0 {
		return types.FilteredString{IsSet: true}
	}

	return config.DesiredApplication.Buildpack
}
782816
func (client *Client) UploadBuildpack(buildpackGUID string, buildpackPath string, buildpack io.Reader, buildpackLength int64) (Warnings, error) {

	contentLength, err := buildpacks.CalculateRequestSize(buildpackLength, buildpackPath, "buildpack")
	if err != nil {
		return nil, err
	}

	contentType, body, writeErrors := buildpacks.CreateMultipartBodyAndHeader(buildpack, buildpackPath, "buildpack")

	request, err := client.newHTTPRequest(requestOptions{
		RequestName: internal.PutBuildpackBitsRequest,
		URIParams:   Params{"buildpack_guid": buildpackGUID},
		Body:        body,
	})

	if err != nil {
		return nil, err
	}

	request.Header.Set("Content-Type", contentType)
	request.ContentLength = contentLength

	_, warnings, err := client.uploadBuildpackAsynchronously(request, writeErrors)
	if err != nil {
		return warnings, err
	}
	return warnings, nil
}
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
}
781187
func (s *Stellar) finalizeBuildPayment(mctx libkb.MetaContext, bid stellar1.BuildPaymentID) (res *buildPaymentData, err error) {
	mctx.Debug("Stellar.finalizeBuildPayment(%v)", bid)
	s.bidLock.Lock()
	defer s.bidLock.Unlock()
	for _, entry := range s.bids {
		entry := entry
		if !entry.Bid.Eq(bid) {
			continue
		}
		if entry.Stopped {
			return nil, fmt.Errorf("This payment might have already been sent. Check your recent payments before trying again.")
		}
		entry.Slot.Shutdown()
		entry.Stopped = true
		err = libkb.AcquireWithContextAndTimeout(mctx.Ctx(), &entry.DataLock, 5*time.Second)
		if err != nil {
			// This likely means something in the Slot is not yielding to its context or forgot to release the lock.
			mctx.Debug("error while attempting to acquire data lock: %v", err)
			return nil, err
		}
		res = &entry.Data
		entry.DataLock.Unlock()
		return res, nil
	}
	return nil, fmt.Errorf("payment build not found")
}
335035
func InferBuildTypes(components app.ComponentReferences, g *GenerationInputs) (app.ComponentReferences, error) {
	errs := []error{}
	for _, ref := range components {
		input := ref.Input()

		// identify whether the input is a builder and whether generation is requested
		input.ResolvedMatch.Builder = app.IsBuilderMatch(input.ResolvedMatch)
		generatorInput, err := app.GeneratorInputFromMatch(input.ResolvedMatch)
		if err != nil && !g.AllowGenerationErrors {
			errs = append(errs, err)
			continue
		}
		input.ResolvedMatch.GeneratorInput = generatorInput

		// if the strategy is set explicitly, apply it to all repos.
		// for example, this affects repos specified in the form image~source.
		if g.Strategy != newapp.StrategyUnspecified && input.Uses != nil {
			input.Uses.SetStrategy(g.Strategy)
		}

		// if we are expecting build inputs, or get a build input when strategy is not docker, expect to build
		if g.ExpectToBuild || (input.ResolvedMatch.Builder && g.Strategy != newapp.StrategyDocker) {
			input.ExpectToBuild = true
		}

		switch {
		case input.ExpectToBuild && input.ResolvedMatch.IsTemplate():
			// TODO: harder - break the template pieces and check if source code can be attached (look for a build config, build image, etc)
			errs = append(errs, errors.New("template with source code explicitly attached is not supported - you must either specify the template and source code separately or attach an image to the source code using the '[image]~[code]' form"))
			continue
		}
	}
	if len(components) == 0 && g.BinaryBuild && g.Strategy == newapp.StrategySource {
		return nil, errors.New("you must provide a builder image when using the source strategy with a binary build")
	}
	if len(components) == 0 && g.BinaryBuild {
		if len(g.Name) == 0 {
			return nil, errors.New("you must provide a --name when you don't specify a source repository or base image")
		}
		ref := &app.ComponentInput{
			From:          "--binary",
			Argument:      "--binary",
			Value:         g.Name,
			ScratchImage:  true,
			ExpectToBuild: true,
		}
		components = append(components, ref)
	}

	return components, kutilerrors.NewAggregate(errs)
}
589667
func (s ReleaseContainersSpec) CalculateRelease(rc ReleaseContext, logger log.Logger) ([]*WorkloadUpdate, Result, error) {
	results := Result{}
	prefilter, postfilter := s.filters()
	all, err := rc.SelectWorkloads(results, prefilter, postfilter)
	if err != nil {
		return nil, results, err
	}
	updates := s.workloadUpdates(results, all)
	return updates, results, s.resultsError(results)
}
536170
func CurrentPackage() string {
	for _, root := range gobuild.Default.SrcDirs() {
		if pkg, ok := hasSubdir(root, "."); ok {
			return pkg
		}
	}
	return ""
}
514073
func calculatePcts(lastTimes cpu.TimesStat, curTimes cpu.TimesStat) cpu.TimesStat {
	totalDelta := curTimes.Total() - lastTimes.Total()
	return cpu.TimesStat{
		User:      formatPct(curTimes.User-lastTimes.User, totalDelta),
		System:    formatPct(curTimes.System-lastTimes.System, totalDelta),
		Idle:      formatPct(curTimes.Idle-lastTimes.Idle, totalDelta),
		Nice:      formatPct(curTimes.Nice-lastTimes.Nice, totalDelta),
		Iowait:    formatPct(curTimes.Iowait-lastTimes.Iowait, totalDelta),
		Irq:       formatPct(curTimes.Irq-lastTimes.Irq, totalDelta),
		Softirq:   formatPct(curTimes.Softirq-lastTimes.Softirq, totalDelta),
		Steal:     formatPct(curTimes.Steal-lastTimes.Steal, totalDelta),
		Guest:     formatPct(curTimes.Guest-lastTimes.Guest, totalDelta),
		GuestNice: formatPct(curTimes.GuestNice-lastTimes.GuestNice, totalDelta),
		Stolen:    formatPct(curTimes.Stolen-lastTimes.Stolen, totalDelta),
	}
}
784215
func (h *receivedPacketHistory) GetAckRanges() []wire.AckRange {
	if h.ranges.Len() == 0 {
		return nil
	}

	ackRanges := make([]wire.AckRange, h.ranges.Len())
	i := 0
	for el := h.ranges.Back(); el != nil; el = el.Prev() {
		ackRanges[i] = wire.AckRange{Smallest: el.Value.Start, Largest: el.Value.End}
		i++
	}
	return ackRanges
}
414562
func (s *ListBuildsOutput) SetBuilds(v []*Build) *ListBuildsOutput {
	s.Builds = v
	return s
}
397345
func readBuildSecrets(ctx context.Context) (*pb.BuildSecrets, error) {
	swarming := lucictx.GetSwarming(ctx)
	if swarming == nil {
		return nil, nil
	}

	secrets := &pb.BuildSecrets{}
	if err := proto.Unmarshal(swarming.SecretBytes, secrets); err != nil {
		return nil, err
	}
	return secrets, nil
}
303064
func (j *Job) AttachPackages(packages []*boshpkg.Package) error {
	var coms []boshpkg.Compilable

	for _, pkg := range packages {
		coms = append(coms, pkg)
	}

	return j.AttachCompilablePackages(coms)
}
954776
func ParsedPackage(pkg *ast.Package) func(r *Rego) {
	return func(r *Rego) {
		r.parsedPackage = pkg
	}
}
1372026
func calculateBuildConfigTriggers(bc *buildv1.BuildConfig) []triggerapi.ObjectFieldTrigger {
	var triggers []triggerapi.ObjectFieldTrigger
	for _, t := range bc.Spec.Triggers {
		if t.ImageChange == nil {
			continue
		}
		var (
			fieldPath string
			from      *corev1.ObjectReference
		)
		if t.ImageChange.From != nil {
			from = t.ImageChange.From
			fieldPath = "spec.triggers"
		} else {
			from = buildapihelpers.GetInputReference(bc.Spec.Strategy)
			fieldPath = "spec.strategy.*.from"
		}
		if from == nil || from.Kind != "ImageStreamTag" || len(from.Name) == 0 {
			continue
		}

		// add a trigger
		triggers = append(triggers, triggerapi.ObjectFieldTrigger{
			From: triggerapi.ObjectReference{
				Name:       from.Name,
				Namespace:  from.Namespace,
				Kind:       from.Kind,
				APIVersion: from.APIVersion,
			},
			FieldPath: fieldPath,
		})
	}
	return triggers
}