// makeBuild partially populates a buildbucketpb.Build. Currently it attempts to
// make available .Builder.Project, .Builder.Bucket, and .Builder.Builder.
506068
func makeBuild(params httprouter.Params, build *ui.MiloBuildLegacy) *buildbucketpb.Build {
	return &buildbucketpb.Build{
		Builder: &buildbucketpb.BuilderID{
			Project: build.Trigger.Project,           // equivalent params.ByName("project")
			Bucket:  params.ByName("bucket"),         // way to get from ui.MiloBuildLegacy so don't need params here?
			Builder: build.Summary.ParentLabel.Label, // params.ByName("builder")
		},
	}
}
1053166
func ForBuild(build *buildv1.Build, policies []RunPolicy) RunPolicy {
	buildPolicy := buildRunPolicy(build)
	for _, s := range policies {
		if s.Handles(buildPolicy) {
			klog.V(5).Infof("Using %T run policy for build %s/%s", s, build.Namespace, build.Name)
			return s
		}
	}
	return nil
}
1265056
func autobuild(p *build.Package) error {
	if p.Dir == "" {
		return fmt.Errorf("no files to build")
	}
	ps, err := os.Stat(p.PkgObj)
	if err != nil {
		// Assume package file does not exist and build for the first time.
		return build_package(p)
	}
	pt := ps.ModTime()
	fs, err := readdir_lstat(p.Dir)
	if err != nil {
		return err
	}
	for _, f := range fs {
		if f.IsDir() {
			continue
		}
		if f.ModTime().After(pt) {
			// Source file is newer than package file; rebuild.
			return build_package(p)
		}
	}
	return nil
}
822328
func handleLUCIBuild(c *router.Context) error {
	bucket := c.Params.ByName("bucket")
	buildername := c.Params.ByName("builder")
	numberOrId := c.Params.ByName("numberOrId")
	forceBlamelist := c.Request.FormValue("blamelist") != ""

	if _, v2Bucket := deprecated.BucketNameToV2(bucket); v2Bucket != "" {
		// Params bucket is a v1 bucket, so call the legacy endpoint.
		return handleLUCIBuildLegacy(c, bucket, buildername, numberOrId)
	}

	// TODO(hinoka): Once v2 is default, redirect v1 bucketnames to v2 bucketname URLs.
	br := buildbucketpb.GetBuildRequest{}
	if strings.HasPrefix(numberOrId, "b") {
		id, err := strconv.ParseInt(numberOrId[1:], 10, 64)
		if err != nil {
			return errors.Annotate(err, "bad build id").Tag(grpcutil.InvalidArgumentTag).Err()
		}
		br.Id = int64(id)
	} else {
		number, err := strconv.Atoi(numberOrId)
		if err != nil {
			return errors.Annotate(err, "bad build number").Tag(grpcutil.InvalidArgumentTag).Err()
		}
		br.BuildNumber = int32(number)
		br.Builder = &buildbucketpb.BuilderID{
			Project: c.Params.ByName("project"),
			Bucket:  bucket,
			Builder: buildername,
		}
	}

	bp, err := buildbucket.GetBuildPage(c, br, forceBlamelist)
	return renderBuild(c, bp, err)
}
806102
func (o *Organization) CreateBuild(ctx context.Context, projectUUID, ref, commitSha string) (bool, Response, error) {
	path := fmt.Sprintf("/organizations/%s/projects/%s/builds", o.UUID, projectUUID)

	_, resp, err := o.client.request(ctx, "POST", path, buildRequest{
		Ref:       ref,
		CommitSha: commitSha,
	})
	if err != nil {
		return false, resp, errors.Wrap(err, "unable to create build")
	}

	return true, resp, nil
}
84650
func (c *Client) WriteBuild(build *pb.Build) error {
	c.assertInitialized()
	buf, err := proto.Marshal(build)
	if err != nil {
		return err
	}
	return c.buildStream.WriteDatagram(buf)
}
1235991
func (s *Service) BuildCreate(ctx context.Context, appIdentity string, o BuildCreateOpts) (*Build, error) {
	var build Build
	return &build, s.Post(ctx, &build, fmt.Sprintf("/apps/%v/builds", appIdentity), o)
}
821313
func AddBuild(projectName string, branch string, commit string, commitTime time.Time, committer string) error {
	o := orm.NewOrm()

	build := Build{ProjectName: projectName, Branch: branch, Commit: commit, CommitTime: commitTime, Committer: committer}
	_, err := o.Insert(&build)
	return err
}
504547
func (b *DiskBuilder) Build() (*DiskBuildResult, error) {

	// start
	b.callEventHandlerIfExists(DiskBuildOnStart)

	// create parameters
	b.currentDiskBuildValue = &DiskBuildValue{}
	b.currentDiskBuildResult = &DiskBuildResult{}

	if err := b.buildDiskParams(); err != nil {
		return nil, err
	}

	// create disk
	b.callEventHandlerIfExists(DiskBuildOnCreateDiskBefore)
	if err := b.createDisk(b.currentDiskBuildValue.Disk, b.currentDiskBuildValue.Edit); err != nil {
		return b.currentDiskBuildResult, err
	}
	b.callEventHandlerIfExists(DiskBuildOnCreateDiskAfter)

	// cleanup
	if b.isSSHKeysEphemeral && (len(b.currentDiskBuildResult.SSHKeys) > 0 || b.currentDiskBuildResult.GeneratedSSHKey != nil) {
		b.callEventHandlerIfExists(DiskBuildOnCleanupSSHKeyBefore)

		// created keys
		for _, key := range b.currentDiskBuildResult.SSHKeys {
			_, err := b.client.SSHKeyDelete(key.ID)
			if err != nil {
				return b.currentDiskBuildResult, err
			}
		}

		// generated key
		if b.currentDiskBuildResult.GeneratedSSHKey != nil {
			_, err := b.client.SSHKeyDelete(b.currentDiskBuildResult.GeneratedSSHKey.ID)
			if err != nil {
				return b.currentDiskBuildResult, err
			}
		}

		b.callEventHandlerIfExists(DiskBuildOnCleanupSSHKeyAfter)
	}
	if b.isNotesEphemeral && len(b.currentDiskBuildResult.Notes) > 0 {
		b.callEventHandlerIfExists(DiskBuildOnCleanupNoteBefore)

		for _, note := range b.currentDiskBuildResult.Notes {
			_, err := b.client.NoteDelete(note.ID)
			if err != nil {
				return b.currentDiskBuildResult, err
			}
		}

		b.callEventHandlerIfExists(DiskBuildOnCleanupNoteAfter)
	}

	b.callEventHandlerIfExists(DiskBuildOnComplete)

	return b.currentDiskBuildResult, nil
}
87704
func GetBuilds(c context.Context, q Query) (*QueryResult, error) {
	switch {
	case q.Master == "":
		return nil, errors.New("master is required")
	case q.Builder == "":
		return nil, errors.New("builder is required")
	}

	if !EmulationEnabled(c) {
		return getDatastoreBuilds(c, q, true)
	}

	var emulatedBuilds, buildbotBuilds []*buildbot.Build
	err := parallel.FanOutIn(func(work chan<- func() error) {
		work <- func() (err error) {
			res, err := getDatastoreBuilds(c, q, false)
			if res != nil {
				buildbotBuilds = res.Builds
			}
			return
		}
		work <- func() (err error) {
			emulatedBuilds, err = getEmulatedBuilds(c, q)
			return
		}
	})
	if err != nil {
		return nil, errors.Annotate(err, "could not load builds").Err()
	}

	mergedBuilds := mergeBuilds(emulatedBuilds, buildbotBuilds)
	if q.Limit > 0 && len(mergedBuilds) > q.Limit {
		mergedBuilds = mergedBuilds[:q.Limit]
	}
	return &QueryResult{Builds: mergedBuilds}, nil
}
1172847
func (bm *BuildManager) Build(ctx context.Context, config backend.BuildConfig) (*builder.Result, error) {
	buildsTriggered.Inc()
	if config.Options.Dockerfile == "" {
		config.Options.Dockerfile = builder.DefaultDockerfileName
	}

	source, dockerfile, err := remotecontext.Detect(config)
	if err != nil {
		return nil, err
	}
	defer func() {
		if source != nil {
			if err := source.Close(); err != nil {
				logrus.Debugf("[BUILDER] failed to remove temporary context: %v", err)
			}
		}
	}()

	ctx, cancel := context.WithCancel(ctx)
	defer cancel()

	if src, err := bm.initializeClientSession(ctx, cancel, config.Options); err != nil {
		return nil, err
	} else if src != nil {
		source = src
	}

	builderOptions := builderOptions{
		Options:        config.Options,
		ProgressWriter: config.ProgressWriter,
		Backend:        bm.backend,
		PathCache:      bm.pathCache,
		IDMapping:      bm.idMapping,
	}
	b, err := newBuilder(ctx, builderOptions)
	if err != nil {
		return nil, err
	}
	return b.build(source, dockerfile)
}
273401
func addBuildLabel(to map[string]string, key, value, namespace string) {
	if len(value) == 0 {
		return
	}
	to[namespace+"build."+key] = value
}
920309
func (builder *FetchBucketTypePropsCommandBuilder) Build() (Command, error) {
	if builder.protobuf == nil {
		panic("builder.protobuf must not be nil")
	}
	if err := validateLocatable(builder.protobuf); err != nil {
		return nil, err
	}
	return &FetchBucketTypePropsCommand{protobuf: builder.protobuf}, nil
}
435277
func extractBuild(c context.Context, r *http.Request) (*Build, error) {
	// sent by pubsub.
	// This struct is just convenient for unwrapping the json message
	var msg struct {
		Message struct {
			Data []byte
		}
		Attributes map[string]interface{}
	}
	if err := json.NewDecoder(r.Body).Decode(&msg); err != nil {
		return nil, errors.Annotate(err, "could not decode message").Err()
	}

	if v, ok := msg.Attributes["version"].(string); ok && v != "v1" {
		// Ignore v2 pubsub messages. TODO(nodir): use v2.
		return nil, nil
	}
	var message struct {
		Build    bbv1.ApiCommonBuildMessage
		Hostname string
	}
	switch err := json.Unmarshal(msg.Message.Data, &message); {
	case err != nil:
		return nil, errors.Annotate(err, "could not parse pubsub message data").Err()
	case !strings.HasPrefix(message.Build.Bucket, "luci."):
		logging.Infof(c, "Received build that isn't part of LUCI, ignoring...")
		return nil, nil
	case message.Build.Status != bbv1.StatusCompleted:
		logging.Infof(c, "Received build that hasn't completed yet, ignoring...")
		return nil, nil
	}

	buildsClient, err := newBuildsClient(c, message.Hostname, message.Build.Project)
	if err != nil {
		return nil, err
	}

	logging.Infof(c, "fetching build %d", message.Build.Id)
	res, err := buildsClient.GetBuild(c, &buildbucketpb.GetBuildRequest{
		Id:     message.Build.Id,
		Fields: buildFieldMask,
	})
	switch {
	case status.Code(err) == codes.NotFound:
		logging.Warningf(c, "no access to build %d", message.Build.Id)
		return nil, nil
	case err != nil:
		err = grpcutil.WrapIfTransient(err)
		err = errors.Annotate(err, "could not fetch buildbucket build %d", message.Build.Id).Err()
		return nil, err
	}

	emails, err := extractEmailNotifyValues(res, message.Build.ParametersJson)
	if err != nil {
		return nil, errors.Annotate(err, "could not decode email_notify").Err()
	}

	return &Build{
		Build:       *res,
		EmailNotify: emails,
	}, nil
}
454396
func ConfigNameForBuild(build *buildv1.Build) string {
	if build == nil {
		return ""
	}
	if build.Annotations != nil {
		if _, exists := build.Annotations[BuildConfigAnnotation]; exists {
			return build.Annotations[BuildConfigAnnotation]
		}
	}
	if _, exists := build.Labels[BuildConfigLabel]; exists {
		return build.Labels[BuildConfigLabel]
	}
	return build.Labels[BuildConfigLabelDeprecated]
}
243852
func Convert_v1_BinaryBuildSource_To_build_BinaryBuildSource(in *v1.BinaryBuildSource, out *build.BinaryBuildSource, s conversion.Scope) error {
	return autoConvert_v1_BinaryBuildSource_To_build_BinaryBuildSource(in, out, s)
}
504430
func (c Client) CreateBuild(ctx context.Context, build *buildv1.Build) error {
	_, err := c.Builds.Builds(apirequest.NamespaceValue(ctx)).Create(build)
	return err
}