// fetchBuilds fetches builds given a criteria.
// The returned builds are sorted by build creation descending.
// count defines maximum number of builds to fetch; if <0, defaults to 100.
761783
func fetchBuilds(c context.Context, client *bbv1.Service, bid BuilderID,
	status string, limit int, cursor string) ([]*bbv1.ApiCommonBuildMessage, string, error) {

	c, _ = context.WithTimeout(c, bbRPCTimeout)
	search := client.Search()
	search.Context(c)
	search.Bucket(bid.V1Bucket())
	search.Status(status)
	search.Tag(strpair.Format(bbv1.TagBuilder, bid.Builder))
	search.IncludeExperimental(true)
	search.StartCursor(cursor)

	if limit < 0 {
		limit = 100
	}

	start := clock.Now(c)
	msgs, cursor, err := search.Fetch(limit, nil)
	if err != nil {
		return nil, "", err
	}
	logging.Infof(c, "Fetched %d %s builds in %s", len(msgs), status, clock.Since(c, start))
	return msgs, cursor, 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
}
900111
func (bs *BuildsService) List(opt *BuildListOptions) ([]Build, []Job, []Commit, *http.Response, error) {
	u, err := urlWithOptions("/builds", opt)
	if err != nil {
		return nil, nil, nil, nil, err
	}

	req, err := bs.client.NewRequest("GET", u, nil, nil)
	if err != nil {
		return nil, nil, nil, nil, err
	}

	var buildsResp listBuildsResponse
	resp, err := bs.client.Do(req, &buildsResp)
	if err != nil {
		return nil, nil, nil, resp, err
	}

	return buildsResp.Builds, buildsResp.Jobs, buildsResp.Commits, resp, err
}
376966
func searchBuilds(ctx context.Context, buildC chan<- *pb.Build, client pb.BuildsClient, req *pb.SearchBuildsRequest) error {
	// Prepare a channel of responses, s.t. we make an RPC as soon as we started
	// consuming the response, as opposed to after the response is completely
	// consumed.
	resC := make(chan *pb.SearchBuildsResponse)
	errC := make(chan error)
	go func() {
		err := searchResponses(ctx, resC, client, req)
		close(resC)
		errC <- err
	}()

	// Forward builds.
	for res := range resC {
		for _, b := range res.Builds {
			select {
			case buildC <- b:

			// Note: selecting on errC here would be a race because goroutine
			// above might have been already done, but we still did not send
			// all builds to the caller.
			case <-ctx.Done():
				return <-errC
			}
		}
	}
	return <-errC
}
938205
func (cs *CommitsService) GetFromBuild(buildId uint) (*Commit, *http.Response, error) {
	u, err := urlWithOptions(fmt.Sprintf("/builds/%d", buildId), nil)
	if err != nil {
		return nil, nil, err
	}

	req, err := cs.client.NewRequest("GET", u, nil, nil)
	if err != nil {
		return nil, nil, err
	}

	var buildResp getBuildResponse
	resp, err := cs.client.Do(req, &buildResp)
	if err != nil {
		return nil, resp, err
	}

	return &buildResp.Commit, resp, nil
}
1342815
func (b *unboundBuilder) Build(t Type, v interface{}) (*Literal, error) {
	switch v.(type) {
	case bool:
		if t != Bool {
			return nil, fmt.Errorf("literal.Build: type %v does not match type of value %v", t, v)
		}
	case int64:
		if t != Int64 {
			return nil, fmt.Errorf("literal.Build: type %v does not match type of value %v", t, v)
		}
	case float64:
		if t != Float64 {
			return nil, fmt.Errorf("literal.Build: type %v does not match type of value %v", t, v)
		}
	case string:
		if t != Text {
			return nil, fmt.Errorf("literal.Build: type %v does not match type of value %v", t, v)
		}
	case []byte:
		if t != Blob {
			return nil, fmt.Errorf("literal.Build: type %v does not match type of value %v", t, v)
		}
	default:
		return nil, fmt.Errorf("literal.Build: type %T is not supported when building literals", v)
	}
	return &Literal{
		t: t,
		v: v,
	}, nil
}
528361
func getRelatedBuilds(c context.Context, client buildbucketpb.BuildsClient, b *buildbucketpb.Build) ([]*ui.Build, error) {
	var bs []string
	for _, buildset := range protoutil.BuildSets(b) {
		// HACK(hinoka): Remove the commit/git/ buildsets because we know they're redundant
		// with the commit/gitiles/ buildsets, and we don't need to ask Buildbucket twice.
		if strings.HasPrefix(buildset, "commit/git/") {
			continue
		}
		bs = append(bs, buildset)
	}
	if len(bs) == 0 {
		// No buildset? No builds.
		return nil, nil
	}

	// Do the search request.
	// Use multiple requests instead of a single batch request.
	// A single large request is CPU bound to a single GAE instance on the buildbucket side.
	// Multiple requests allows the use of multiple GAE instances, therefore more parallelism.
	resps := make([]*buildbucketpb.SearchBuildsResponse, len(bs))
	if err := parallel.FanOutIn(func(ch chan<- func() error) {
		for i, buildset := range bs {
			i := i
			buildset := buildset
			ch <- func() (err error) {
				logging.Debugf(c, "Searching for %s (%d)", buildset, i)
				resps[i], err = client.SearchBuilds(c, searchBuildset(buildset, summaryBuildsMask))
				return
			}
		}
	}); err != nil {
		return nil, err
	}

	// Dedupe builds.
	// It's possible since we've made multiple requests that we got back the same builds
	// multiple times.
	seen := map[int64]bool{} // set of build IDs.
	result := []*ui.Build{}
	for _, resp := range resps {
		for _, rb := range resp.GetBuilds() {
			if seen[rb.Id] {
				continue
			}
			seen[rb.Id] = true
			result = append(result, &ui.Build{rb})
		}
	}

	// Sort builds by ID.
	sort.Slice(result, func(i, j int) bool { return result[i].Id < result[j].Id })

	return result, nil
}
661049
func getBuildDefaults(pluginConfig map[string]*legacyconfigv1.AdmissionPluginConfig) (*openshiftcontrolplanev1.BuildDefaultsConfig, error) {
	const buildDefaultsPlugin = "BuildDefaults"
	uncastConfig, err := getPluginConfigObj(pluginConfig, buildDefaultsPlugin, &openshiftcontrolplanev1.BuildDefaultsConfig{})
	if err != nil {
		return nil, err
	}
	if uncastConfig == nil {
		return nil, nil
	}
	config, ok := uncastConfig.(*openshiftcontrolplanev1.BuildDefaultsConfig)
	if !ok {
		return nil, fmt.Errorf("expected BuildDefaultsConfig, not %T", uncastConfig)
	}

	return config, nil
}
457048
func (m *MockBuildsServer) SearchBuilds(arg0 context.Context, arg1 *SearchBuildsRequest) (*SearchBuildsResponse, error) {
	m.ctrl.T.Helper()
	ret := m.ctrl.Call(m, "SearchBuilds", arg0, arg1)
	ret0, _ := ret[0].(*SearchBuildsResponse)
	ret1, _ := ret[1].(error)
	return ret0, ret1
}
1292514
func (q *MssqlQueryBuilder) BuildOrderByAndLimit(sql string, cols []string, limit int64, offset int64) string {
	orderBy := q.BuildOrderBy(cols)
	if limit < 0 && offset < 0 {
		if orderBy == "" {
			return sql
		}
		return sql + "\n" + orderBy
	}

	// only SQL SERVER 2012 or newer are supported by this method

	if orderBy == "" {
		// ORDER BY clause is required when FETCH and OFFSET are in the SQL
		orderBy = "ORDER BY (SELECT NULL)"
	}
	sql += "\n" + orderBy

	// http://technet.microsoft.com/en-us/library/gg699618.aspx
	if offset < 0 {
		offset = 0
	}
	sql += "\n" + fmt.Sprintf("OFFSET %v ROWS", offset)
	if limit >= 0 {
		sql += "\n" + fmt.Sprintf("FETCH NEXT %v ROWS ONLY", limit)
	}
	return sql
}
59205
func (b *Builder) Build(ctx context.Context, opt backend.BuildConfig) (*builder.Result, error) {
	var rc = opt.Source

	if buildID := opt.Options.BuildID; buildID != "" {
		b.mu.Lock()

		upload := false
		if strings.HasPrefix(buildID, "upload-request:") {
			upload = true
			buildID = strings.TrimPrefix(buildID, "upload-request:")
		}

		if _, ok := b.jobs[buildID]; !ok {
			b.jobs[buildID] = newBuildJob()
		}
		j := b.jobs[buildID]
		var cancel func()
		ctx, cancel = context.WithCancel(ctx)
		j.cancel = cancel
		b.mu.Unlock()

		if upload {
			ctx2, cancel := context.WithTimeout(ctx, 5*time.Second)
			defer cancel()
			err := j.SetUpload(ctx2, rc)
			return nil, err
		}

		if remoteContext := opt.Options.RemoteContext; remoteContext == "upload-request" {
			ctx2, cancel := context.WithTimeout(ctx, 5*time.Second)
			defer cancel()
			var err error
			rc, err = j.WaitUpload(ctx2)
			if err != nil {
				return nil, err
			}
			opt.Options.RemoteContext = ""
		}

		defer func() {
			delete(b.jobs, buildID)
		}()
	}

	var out builder.Result

	id := identity.NewID()

	frontendAttrs := map[string]string{}

	if opt.Options.Target != "" {
		frontendAttrs["target"] = opt.Options.Target
	}

	if opt.Options.Dockerfile != "" && opt.Options.Dockerfile != "." {
		frontendAttrs["filename"] = opt.Options.Dockerfile
	}

	if opt.Options.RemoteContext != "" {
		if opt.Options.RemoteContext != "client-session" {
			frontendAttrs["context"] = opt.Options.RemoteContext
		}
	} else {
		url, cancel := b.reqBodyHandler.newRequest(rc)
		defer cancel()
		frontendAttrs["context"] = url
	}

	cacheFrom := append([]string{}, opt.Options.CacheFrom...)

	frontendAttrs["cache-from"] = strings.Join(cacheFrom, ",")

	for k, v := range opt.Options.BuildArgs {
		if v == nil {
			continue
		}
		frontendAttrs["build-arg:"+k] = *v
	}

	for k, v := range opt.Options.Labels {
		frontendAttrs["label:"+k] = v
	}

	if opt.Options.NoCache {
		frontendAttrs["no-cache"] = ""
	}

	if opt.Options.PullParent {
		frontendAttrs["image-resolve-mode"] = "pull"
	} else {
		frontendAttrs["image-resolve-mode"] = "default"
	}

	if opt.Options.Platform != "" {
		// same as in newBuilder in builder/dockerfile.builder.go
		// TODO: remove once opt.Options.Platform is of type specs.Platform
		sp, err := platforms.Parse(opt.Options.Platform)
		if err != nil {
			return nil, err
		}
		if err := system.ValidatePlatform(sp); err != nil {
			return nil, err
		}
		frontendAttrs["platform"] = opt.Options.Platform
	}

	switch opt.Options.NetworkMode {
	case "host", "none":
		frontendAttrs["force-network-mode"] = opt.Options.NetworkMode
	case "", "default":
	default:
		return nil, errors.Errorf("network mode %q not supported by buildkit", opt.Options.NetworkMode)
	}

	extraHosts, err := toBuildkitExtraHosts(opt.Options.ExtraHosts)
	if err != nil {
		return nil, err
	}
	frontendAttrs["add-hosts"] = extraHosts

	exporterName := ""
	exporterAttrs := map[string]string{}

	if len(opt.Options.Outputs) > 1 {
		return nil, errors.Errorf("multiple outputs not supported")
	} else if len(opt.Options.Outputs) == 0 {
		exporterName = "moby"
	} else {
		// cacheonly is a special type for triggering skipping all exporters
		if opt.Options.Outputs[0].Type != "cacheonly" {
			exporterName = opt.Options.Outputs[0].Type
			exporterAttrs = opt.Options.Outputs[0].Attrs
		}
	}

	if exporterName == "moby" {
		if len(opt.Options.Tags) > 0 {
			exporterAttrs["name"] = strings.Join(opt.Options.Tags, ",")
		}
	}

	cache := controlapi.CacheOptions{}

	if inlineCache := opt.Options.BuildArgs["BUILDKIT_INLINE_CACHE"]; inlineCache != nil {
		if b, err := strconv.ParseBool(*inlineCache); err == nil && b {
			cache.Exports = append(cache.Exports, &controlapi.CacheOptionsEntry{
				Type: "inline",
			})
		}
	}

	req := &controlapi.SolveRequest{
		Ref:           id,
		Exporter:      exporterName,
		ExporterAttrs: exporterAttrs,
		Frontend:      "dockerfile.v0",
		FrontendAttrs: frontendAttrs,
		Session:       opt.Options.SessionID,
		Cache:         cache,
	}

	if opt.Options.NetworkMode == "host" {
		req.Entitlements = append(req.Entitlements, entitlements.EntitlementNetworkHost)
	}

	aux := streamformatter.AuxFormatter{Writer: opt.ProgressWriter.Output}

	eg, ctx := errgroup.WithContext(ctx)

	eg.Go(func() error {
		resp, err := b.controller.Solve(ctx, req)
		if err != nil {
			return err
		}
		if exporterName != "moby" {
			return nil
		}
		id, ok := resp.ExporterResponse["containerimage.digest"]
		if !ok {
			return errors.Errorf("missing image id")
		}
		out.ImageID = id
		return aux.Emit("moby.image.id", types.BuildResult{ID: id})
	})

	ch := make(chan *controlapi.StatusResponse)

	eg.Go(func() error {
		defer close(ch)
		// streamProxy.ctx is not set to ctx because when request is cancelled,
		// only the build request has to be cancelled, not the status request.
		stream := &statusProxy{streamProxy: streamProxy{ctx: context.TODO()}, ch: ch}
		return b.controller.Status(&controlapi.StatusRequest{Ref: id}, stream)
	})

	eg.Go(func() error {
		for sr := range ch {
			dt, err := sr.Marshal()
			if err != nil {
				return err
			}
			if err := aux.Emit("moby.buildkit.trace", dt); err != nil {
				return err
			}
		}
		return nil
	})

	if err := eg.Wait(); err != nil {
		return nil, err
	}

	return &out, nil
}
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
}
201647
func (client *Client) GetBuildpacks(filters ...Filter) ([]Buildpack, Warnings, error) {
	request, err := client.newHTTPRequest(requestOptions{
		RequestName: internal.GetBuildpacksRequest,
		Query:       ConvertFilterParameters(filters),
	})

	if err != nil {
		return nil, nil, err
	}

	var buildpacks []Buildpack
	warnings, err := client.paginate(request, Buildpack{}, func(item interface{}) error {
		if buildpack, ok := item.(Buildpack); ok {
			buildpacks = append(buildpacks, buildpack)
		} else {
			return ccerror.UnknownObjectInListError{
				Expected:   Buildpack{},
				Unexpected: item,
			}
		}
		return nil
	})

	return buildpacks, warnings, err
}
921926
func (q *BuildQueue) checkBuildGuarantees() error {
	q.mutex.Lock()
	defer q.mutex.Unlock()

	buildCount := map[string]int{}

	for _, status := range q.buildStatus {
		if build := status.currentBuild; build != nil {
			buildCount[build.uuid]++
		}
	}

	switch {
	case q.exclusiveBuilds.running > 1:
		return fmt.Errorf("More than one exclusive build is running")
	case q.exclusiveBuilds.running > 0 && q.regularBuilds.running > 0:
		return fmt.Errorf("Exclusive build is running in parallel with regular build")
	default:
		for uuid, count := range buildCount {
			if count > 1 {
				return fmt.Errorf("UUID %s is being built in parallel", uuid)
			}
		}
	}

	return nil
}
1050723
func GetBuildsWithProjectName(projectName string) []*Build {
	o := orm.NewOrm()

	var builds []*Build
	num, err := o.QueryTable("build").Filter("project_name", projectName).All(&builds)
	fmt.Printf("Returned Rows Num: %s, %s", num, err)
	return builds
}
57510
func (c Client) GetBuild(ctx context.Context, name string, options *metav1.GetOptions) (*buildv1.Build, error) {
	return c.Builds.Builds(apirequest.NamespaceValue(ctx)).Get(name, *options)
}
1140226
func getEmulatedBuild(c context.Context, id buildbot.BuildID, fetchAnnotations, fetchChanges bool) (*buildbot.Build, error) {
	if err := id.Validate(); err != nil {
		return nil, err
	}

	buildbucketBuild, err := EmulationOf(c, id)
	switch {
	case err != nil:
		return nil, err
	case buildbucketBuild == nil:
		return nil, nil
	}

	buildbotBuild, err := buildFromBuildbucket(c, id.Master, buildbucketBuild, fetchAnnotations)
	switch {
	case ErrNoBuildNumber.In(err):
		// This is an old buildbucket build without a build number.  Just drop it.
		// All emulated builds should have a build number.
		return nil, nil
	case err != nil:
		return nil, err
	}

	if fetchChanges {
		if err := blame(c, buildbotBuild); err != nil {
			return nil, err
		}
	}

	return buildbotBuild, nil
}