// GetBuild fetches a buildbot build from the storage.
// Returns (nil, nil) if build is not found.
// Does not check access.
542214
func GetBuild(c context.Context, id buildbot.BuildID) (*buildbot.Build, error) {
	return getBuild(c, id, true, true)
}
646817
func mergeBuilds(a, b []*buildbot.Build) []*buildbot.Build {
	ret := make([]*buildbot.Build, len(a), len(a)+len(b))
	copy(ret, a)

	// add builds from b that have unique build numbers.
	aNumbers := make(map[int]struct{}, len(a))
	for _, build := range a {
		aNumbers[build.Number] = struct{}{}
	}
	for _, build := range b {
		if _, ok := aNumbers[build.Number]; !ok {
			ret = append(ret, build)
		}
	}
	sort.Slice(ret, func(i, j int) bool {
		return ret[i].Number > ret[j].Number
	})
	return ret
}
273067
func (lh *GoLangHelper) PreBuild() error {
	wd, err := os.Getwd()
	if err != nil {
		return err
	}
	// todo: this won't work if the function is more complex since the import paths won't match up, need to fix
	pbcmd := fmt.Sprintf("docker run --rm -v %s:/go/src/github.com/x/y -w /go/src/github.com/x/y iron/go:dev go build -o func", wd)
	fmt.Println("Running prebuild command:", pbcmd)
	parts := strings.Fields(pbcmd)
	head := parts[0]
	parts = parts[1:len(parts)]
	cmd := exec.Command(head, parts...)
	// cmd.Dir = dir
	cmd.Stderr = os.Stderr
	cmd.Stdout = os.Stdout
	if err := cmd.Run(); err != nil {
		return fmt.Errorf("error running docker build: %v", err)
	}
	return nil
}
424891
func GetBuildWithId(buildId int64) Build {
	o := orm.NewOrm()

	build := Build{Id: buildId}
	err := o.Read(&build)
	fmt.Printf("ERR: %v\n", err)
	return build
}
61183
func GetBuilderID(c context.Context, id int64) (builder *buildbucketpb.BuilderID, number int32, err error) {
	host, err := getHost(c)
	if err != nil {
		return
	}
	client, err := buildbucketClient(c, host, auth.AsUser)
	if err != nil {
		return
	}
	br, err := client.GetBuild(c, &buildbucketpb.GetBuildRequest{
		Id:     id,
		Fields: builderIDMask,
	})
	switch grpcutil.Code(err) {
	case codes.OK:
		builder = br.Builder
		number = br.Number
	case codes.NotFound:
		if auth.CurrentIdentity(c) == identity.AnonymousIdentity {
			err = ErrNotLoggedIn
			return
		}
		fallthrough
	case codes.PermissionDenied:
		err = ErrNotFound
	}
	return
}
1344960
func GetBuilder(c context.Context, bid BuilderID, limit int, cursor string) (*ui.Builder, error) {
	host, err := getHost(c)
	if err != nil {
		return nil, err
	}

	if limit < 0 {
		limit = 20
	}

	result := &ui.Builder{
		Name: bid.Builder,
	}
	if host == "debug" {
		return result, getDebugBuilds(c, bid, limit, result)
	}
	client, err := newBuildbucketClient(c, host)
	if err != nil {
		return nil, err
	}

	fetch := func(statusFilter string, limit int, cursor string) (result []*ui.BuildSummary, nextCursor string, err error) {
		msgs, nextCursor, err := fetchBuilds(c, client, bid, statusFilter, limit, cursor)
		if err != nil {
			logging.WithError(err).Errorf(c, "Could not fetch %s builds", statusFilter)
			return
		}
		result = toMiloBuildsSummaries(c, msgs)
		return
	}
	return result, parallel.FanOutIn(func(work chan<- func() error) {
		work <- func() error {
			return ensureDefined(c, host, bid)
		}
		work <- func() (err error) {
			result.MachinePool, err = getPool(c, bid)
			return
		}
		work <- func() (err error) {
			result.PendingBuilds, _, err = fetch(bbv1.StatusScheduled, -1, "")
			return
		}
		work <- func() (err error) {
			result.CurrentBuilds, _, err = fetch(bbv1.StatusStarted, -1, "")
			return
		}
		work <- func() (err error) {
			result.FinishedBuilds, result.NextCursor, err = fetch(bbv1.StatusCompleted, limit, cursor)
			result.PrevCursor = backCursor(c, bid, limit, cursor, result.NextCursor) // Safe to do even with error.
			return
		}
	})
}
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
}
977069
func WaitForRunningBuild(buildClient buildtypedclient.BuildsGetter, buildNamespace, buildName string, timeout time.Duration) (*buildv1.Build,
	bool,
	error) {
	fieldSelector := fields.OneTermEqualSelector("metadata.name", buildName)
	options := metav1.ListOptions{FieldSelector: fieldSelector.String(), ResourceVersion: "0"}

	done := make(chan interface{}, 1)
	var resultBuild *buildv1.Build
	var success bool
	var resultErr error

	deadline := time.Now().Add(timeout)
	go func() {
		defer close(done)
		defer utilruntime.HandleCrash()

		for time.Now().Before(deadline) {

			// make sure the build has not been deleted before we start trying to watch on it because
			// we won't get a watch event for it if it's been deleted (because we are watching starting
			// at resource version 0).
			_, err := buildClient.Builds(buildNamespace).Get(buildName, metav1.GetOptions{})
			if err != nil {
				resultErr = err
				if errors.IsNotFound(err) {
					resultErr = ErrBuildDeleted
				}
				return
			}

			w, err := buildClient.Builds(buildNamespace).Watch(options)
			if err != nil {
				resultErr = err
				return
			}

			ctx, cancel := context.WithTimeout(context.Background(), timeout)
			defer cancel()
			_, err = watchtools.UntilWithoutRetry(ctx, w, func(event watch.Event) (bool, error) {
				if event.Type == watch.Error {
					return false, ErrWatchError{fmt.Errorf("watch event type error: %v", event)}
				}
				obj, ok := event.Object.(*buildv1.Build)
				if !ok {
					return false, fmt.Errorf("received unknown object while watching for builds: %T", event.Object)
				}

				if event.Type == watch.Deleted {
					return false, ErrBuildDeleted
				}

				switch obj.Status.Phase {
				case buildv1.BuildPhaseRunning, buildv1.BuildPhaseComplete, buildv1.BuildPhaseFailed, buildv1.BuildPhaseError, buildv1.BuildPhaseCancelled:
					resultBuild = obj
					return true, nil
				case buildv1.BuildPhaseNew, buildv1.BuildPhasePending:
				default:
					return false, ErrUnknownBuildPhase
				}

				return false, nil
			})

			if err != nil {
				if _, ok := err.(ErrWatchError); ok {
					continue
				}
				resultErr = err
				success = false
				resultBuild = nil
				return
			}
			success = true
			return
		}
	}()

	select {
	case <-time.After(timeout):
		return nil, false, wait.ErrWaitTimeout
	case <-done:
		return resultBuild, success, resultErr
	}

}
673564
func getDatastoreBuild(c context.Context, id buildbot.BuildID) (*buildbot.Build, error) {
	if err := id.Validate(); err != nil {
		return nil, err
	}

	entity := &buildEntity{
		Master:      id.Master,
		Buildername: id.Builder,
		Number:      id.Number,
	}

	err := datastore.Get(c, entity)
	if err == datastore.ErrNoSuchEntity {
		return nil, nil
	}

	entity.addViewPath()

	return (*buildbot.Build)(entity), err
}
421359
func (o *Organization) GetBuild(ctx context.Context, projectUUID, buildUUID string) (Build, Response, error) {
	path := fmt.Sprintf("/organizations/%s/projects/%s/builds/%s", o.UUID, projectUUID, buildUUID)

	body, resp, err := o.client.request(ctx, "GET", path, nil)
	if err != nil {
		return Build{}, resp, errors.Wrap(err, "unable to get build")
	}

	var build buildResponse
	if err = json.Unmarshal(body, &build); err != nil {
		return Build{}, resp, errors.Wrap(err, "unable to unmarshal response into Build")
	}

	return build.Build, resp, nil
}
1078543
func GetAllBuilds() []*Build {
	o := orm.NewOrm()

	var builds []*Build
	// o.QueryTable("build").Filter("name", "slene").All(&builds) to filter with build status
	num, err := o.QueryTable("build").All(&builds)
	fmt.Printf("Returned Rows Num: %s, %s", num, err)
	return builds
}
821506
func (jenkins *Jenkins) GetBuild(job Job, number int) (build Build, err error) {
	err = jenkins.get(fmt.Sprintf("/job/%s/%d", job.Name, number), nil, &build)
	return
}
198715
func (client Client) GetLastBuild(jobName string) (LastBuild, error) {
	retry := retry.New(3, retry.DefaultBackoffFunc)

	var data []byte
	work := func() error {
		req, err := http.NewRequest("GET", fmt.Sprintf("%s/job/%s/lastBuild/api/json?depth=1&tree=timestamp,result,url", client.baseURL.String(), jobName), nil)
		if err != nil {
			return err
		}
		req.Header.Set("Accept", "application/json")
		req.SetBasicAuth(client.userName, client.password)

		var responseCode int
		responseCode, data, err = consumeResponse(req)
		if err != nil {
			return err
		}

		if responseCode != http.StatusOK {
			return fmt.Errorf("Status code: %d, response %s", responseCode, string(data))
		}
		return nil
	}
	if err := retry.Try(work); err != nil {
		return LastBuild{}, err
	}

	var lastBuild LastBuild
	if err := json.Unmarshal(data, &lastBuild); err != nil {
		return LastBuild{}, err
	}
	return lastBuild, nil
}
793945
func buildFromBuildbucket(c context.Context, master string, b *deprecated.Build, fetchAnnotations bool) (*buildbot.Build, error) {
	num, err := buildNumber(b)
	if err != nil {
		return nil, err
	}

	res := &buildbot.Build{
		Emulated:    true,
		ViewPath:    (&model.BuildSummary{BuildID: "buildbucket/" + b.Address()}).SelfLink(),
		Master:      master,
		Buildername: b.Builder,
		Number:      num,
		Results:     statusResult(b.Status),
		TimeStamp:   buildbot.Time{b.UpdateTime},
		Times: buildbot.TimeRange{
			Start:  buildbot.Time{b.StartTime},
			Finish: buildbot.Time{b.CompletionTime},
		},
		// TODO(nodir): use buildbucket access API when it is ready,
		// or, perhaps, just delete this code.
		// Note that this function should not be called on builds
		// that the requester does not have access to, in the first place.
		Internal:    b.Bucket != "luci.chromium.try",
		Finished:    protoutil.IsEnded(b.Status),
		Sourcestamp: &buildbot.SourceStamp{},

		// non-nil slice because we want an array, not null,
		// when converted to JSON
		Steps: []buildbot.Step{},
	}

	for _, bs := range b.Tags[bbv1.TagBuildSet] {
		commit, ok := protoutil.ParseBuildSet(bs).(*buildbucketpb.GitilesCommit)
		if ok {
			res.Sourcestamp.Repository = protoutil.GitilesRepoURL(commit)
			res.Sourcestamp.Revision = commit.Id
			break
		}
	}

	if fetchAnnotations && b.Status != buildbucketpb.Status_SCHEDULED {
		addr, err := logLocation(b)
		if err != nil {
			return nil, grpcutil.NotFound
		}

		ann, err := fetchAnnotationProto(c, addr)
		switch {
		case err == errAnnotationNotFound:
		case err != nil:
			return nil, errors.Annotate(err, "could not load annotation proto").Err()
		default:
			res.Properties = extractProperties(ann)

			prefix, _ := addr.Path.Split()
			conv := annotationConverter{
				logdogServer:       addr.Host,
				logdogPrefix:       fmt.Sprintf("%s/%s", addr.Project, prefix),
				buildCompletedTime: b.CompletionTime,
			}
			convCtx := logging.SetField(c, "build_id", b.ID)
			conv.addSteps(convCtx, &res.Steps, ann.Substep, "")
			for i := range res.Steps {
				s := &res.Steps[i]
				s.StepNumber = i + 1
				res.Logs = append(res.Logs, s.Logs...)
				if !s.IsFinished {
					res.Currentstep = s.Name
				}
				if s.Results.Result != buildbot.Success {
					res.Text = append(res.Text, fmt.Sprintf("%s %s", s.Results.Result, s.Name))
				}
			}
		}
	}

	if len(res.Text) == 0 && b.Status == buildbucketpb.Status_SUCCESS {
		res.Text = []string{"Build successful"}
	}

	return res, nil
}
159811
func GetBuildSummary(c context.Context, id int64) (*model.BuildSummary, error) {
	// The host is set to prod because buildbot is hardcoded to talk to prod.
	uri := fmt.Sprintf("buildbucket://cr-buildbucket.appspot.com/build/%d", id)
	bs := make([]*model.BuildSummary, 0, 1)
	q := datastore.NewQuery("BuildSummary").Eq("ContextURI", uri).Limit(1)
	switch err := datastore.GetAll(c, q, &bs); {
	case err != nil:
		return nil, common.ReplaceNSEWith(err.(errors.MultiError), ErrNotFound)
	case len(bs) == 0:
		return nil, ErrNotFound
	default:
		return bs[0], nil
	}
}
1146793
func getBuildName(pod metav1.Object) string {
	if pod == nil {
		return ""
	}
	return pod.GetAnnotations()[buildutil.BuildAnnotation]
}
1001934
func (c *ApiController) GetActiveBuilds() {
	// TODO(tobe): this is not implemented because nobody uses it yet.
	log.Info("Get active builds")

	result := "Not implemented"
	c.Ctx.WriteString(result)
}