// This method assumes following fields have been assigned with valid values:
// Required - Issue, BaseRepo
// Optional - HeadRepo, Merger
433034
func (pr *PullRequest) APIFormat() *api.PullRequest {
	// In case of head repo has been deleted.
	var apiHeadRepo *api.Repository
	if pr.HeadRepo == nil {
		apiHeadRepo = &api.Repository{
			Name: "deleted",
		}
	} else {
		apiHeadRepo = pr.HeadRepo.APIFormat(nil)
	}

	apiIssue := pr.Issue.APIFormat()
	apiPullRequest := &api.PullRequest{
		ID:         pr.ID,
		Index:      pr.Index,
		Poster:     apiIssue.Poster,
		Title:      apiIssue.Title,
		Body:       apiIssue.Body,
		Labels:     apiIssue.Labels,
		Milestone:  apiIssue.Milestone,
		Assignee:   apiIssue.Assignee,
		State:      apiIssue.State,
		Comments:   apiIssue.Comments,
		HeadBranch: pr.HeadBranch,
		HeadRepo:   apiHeadRepo,
		BaseBranch: pr.BaseBranch,
		BaseRepo:   pr.BaseRepo.APIFormat(nil),
		HTMLURL:    pr.Issue.HTMLURL(),
		HasMerged:  pr.HasMerged,
	}

	if pr.Status != PULL_REQUEST_STATUS_CHECKING {
		mergeable := pr.Status != PULL_REQUEST_STATUS_CONFLICT
		apiPullRequest.Mergeable = &mergeable
	}
	if pr.HasMerged {
		apiPullRequest.Merged = &pr.Merged
		apiPullRequest.MergedCommitID = &pr.MergedCommitID
		apiPullRequest.MergedBy = pr.Merger.APIFormat()
	}

	return apiPullRequest
}
774119
func (lsa *LeadershipSettingsAccessor) Merge(bulkArgs params.MergeLeadershipSettingsBulkParams) (params.ErrorResults, error) {

	requireAppName, err := lsa.callerApplication()
	if err != nil {
		return params.ErrorResults{}, err
	}
	// Start out assuming the caller is a unit (for older clients).
	callerUnitId := lsa.authorizer.GetAuthTag().Id()

	results := make([]params.ErrorResult, len(bulkArgs.Params))

	for i, arg := range bulkArgs.Params {
		result := &results[i]

		// TODO(fwereade): we shoudn't assume a ApplicationTag: we should
		// use an actual auth func to determine permissions.
		applicationTag, err := names.ParseApplicationTag(arg.ApplicationTag)
		if err != nil {
			result.Error = common.ServerError(err)
			continue
		}

		// If a unit is passed in as an arg, use that instead of the caller id.
		if arg.UnitTag != "" {
			unitTag, err := names.ParseUnitTag(arg.UnitTag)
			if err != nil {
				result.Error = common.ServerError(err)
				continue
			}
			callerUnitId = unitTag.Id()
			unitAppName, err := names.UnitApplication(callerUnitId)
			if err != nil || unitAppName != requireAppName {
				result.Error = common.ServerError(common.ErrPerm)
				continue
			}
		}

		appName := applicationTag.Id()
		if appName != requireAppName {
			result.Error = common.ServerError(common.ErrPerm)
			continue
		}

		token := lsa.leaderCheckFn(appName, callerUnitId)
		err = lsa.mergeSettingsChunkFn(token, appName, arg.Settings)
		if err != nil {
			result.Error = common.ServerError(err)
		}
	}

	return params.ErrorResults{Results: results}, nil
}
597173
func (cr *ConflictResolver) BeginNewBranch() {
	cr.inputLock.Lock()
	defer cr.inputLock.Unlock()
	// Reset the curr input so we don't ignore a future CR
	// request that uses the same revision number (i.e.,
	// because the previous CR failed to flush due to a
	// conflict).
	cr.currInput = conflictInput{}
}
370099
func NewErrParamRequired(field string) *ErrParamRequired {
	return &ErrParamRequired{
		errInvalidParam{
			code:  ParamRequiredErrCode,
			field: field,
			msg:   fmt.Sprintf("missing required field"),
		},
	}
}
43551
func (v mergeStrategy) MergeType(e apply.TypeElement) (apply.Result, error) {
	// No merge logic if adding or deleting a field
	if result, done := v.doAddOrDelete(e); done {
		return result, nil
	}
	// Detect conflict in TypeElement
	if err := v.doConflictDetect(e); err != nil {
		return apply.Result{}, err
	}
	return v.doMergeMap(e.GetValues())
}
791761
func merge(appliabels ...[]appliable) []appliable {
	all := []appliable{}

	for _, appl := range appliabels {
		all = append(all, appl...)
	}

	return all
}
865408
func (info *HostCertificateInfo) IssuerName() *pkix.Name {
	if info.issuerName != nil {
		return info.issuerName
	}

	return info.toName(info.Issuer)
}
1226235
func ValidateRegexp(ch *Changeset, field string, exp *regexp.Regexp, opts ...Option) {
	val, exist := ch.changes[field]
	if !exist {
		return
	}

	options := Options{
		message: ValidateRegexpErrorMessage,
	}
	options.apply(opts)

	if str, ok := val.(string); ok {
		match := exp.MatchString(str)
		if !match {
			msg := strings.Replace(options.message, "{field}", field, 1)
			AddError(ch, field, msg)
		}
		return
	}
}
115079
func ValidateInclusion(ch *Changeset, field string, values []interface{}, opts ...Option) {
	val, exist := ch.changes[field]
	if !exist {
		return
	}

	options := Options{
		message: ValidateInclusionErrorMessage,
	}
	options.apply(opts)

	invalid := true
	for _, inval := range values {
		if val == inval {
			invalid = false
			break
		}
	}

	if invalid {
		r := strings.NewReplacer("{field}", field, "{values}", fmt.Sprintf("%v", values))
		AddError(ch, field, r.Replace(options.message))
	}
}
438979
func (inode *Inode) fillXattrFromHead(resp *s3.HeadObjectOutput) {
	inode.userMetadata = make(map[string][]byte)

	if resp.ETag != nil {
		inode.s3Metadata["etag"] = []byte(*resp.ETag)
	}
	if resp.StorageClass != nil {
		inode.s3Metadata["storage-class"] = []byte(*resp.StorageClass)
	} else {
		inode.s3Metadata["storage-class"] = []byte("STANDARD")
	}

	for k, v := range resp.Metadata {
		k = strings.ToLower(k)
		value, err := url.PathUnescape(*v)
		if err != nil {
			value = *v
		}
		inode.userMetadata[k] = []byte(value)
	}
}
1343566
func (verr *ValidationErrors) Merge(err *ValidationErrors) {
	if err == nil {
		return
	}
	verr.Errors = append(verr.Errors, err.Errors...)
	verr.Definitions = append(verr.Definitions, err.Definitions...)
}
10615
func (pair comparablePrincipalSetPair) MergeWithPlurality() ComparablePrincipalSet {
	var principalsToAdd []*ComparablePrincipal
	used := make(map[int]struct{})
	// Iterate over the contained set and for each principal
	for _, principal := range pair.contained {
		var covered bool
		// Search a principal in the containing set to cover the principal in the contained set
		for i, coveringPrincipal := range pair.containing {
			// The principal found shouldn't be used twice
			if _, isUsed := used[i]; isUsed {
				continue
			}
			// All identities that satisfy the found principal, should satisfy the covered principal as well.
			if coveringPrincipal.IsA(principal) {
				used[i] = struct{}{}
				covered = true
				break
			}
		}
		// If we haven't found a cover to the principal, it's because we already used up all the potential candidates
		// among the containing set, so just add it to the principals set to be added later.
		if !covered {
			principalsToAdd = append(principalsToAdd, principal)
		}
	}

	res := pair.containing.Clone()
	res = append(res, principalsToAdd...)
	return res
}
1274446
func (u *UpdateCheckRunOptions) GetHeadBranch() string {
	if u == nil || u.HeadBranch == nil {
		return ""
	}
	return *u.HeadBranch
}
134861
func (m *Memberlist) mergeRemoteState(join bool, remoteNodes []pushNodeState, userBuf []byte) error {
	if err := m.verifyProtocol(remoteNodes); err != nil {
		return err
	}

	// Invoke the merge delegate if any
	if join && m.config.Merge != nil {
		nodes := make([]*Node, len(remoteNodes))
		for idx, n := range remoteNodes {
			nodes[idx] = &Node{
				Name: n.Name,
				Addr: n.Addr,
				Port: n.Port,
				Meta: n.Meta,
				PMin: n.Vsn[0],
				PMax: n.Vsn[1],
				PCur: n.Vsn[2],
				DMin: n.Vsn[3],
				DMax: n.Vsn[4],
				DCur: n.Vsn[5],
			}
		}
		if err := m.config.Merge.NotifyMerge(nodes); err != nil {
			return err
		}
	}

	// Merge the membership state
	m.mergeState(remoteNodes)

	// Invoke the delegate for user state
	if userBuf != nil && m.config.Delegate != nil {
		m.config.Delegate.MergeRemoteState(userBuf, join)
	}
	return nil
}
1173497
func (mk MergeKeys) GetMergeKeyValue(i interface{}) (MergeKeyValue, error) {
	result := MergeKeyValue{}
	if len(mk) <= 0 {
		return result, fmt.Errorf("merge key must have at least 1 value to merge")
	}
	m, ok := i.(map[string]interface{})
	if !ok {
		return result, fmt.Errorf("cannot use mergekey %v for primitive item in list %v", mk, i)
	}
	for _, field := range mk {
		if value, found := m[field]; !found {
			result[field] = ""
		} else {
			result[field] = fmt.Sprintf("%v", value)
		}
	}
	return result, nil
}
1041882
func MergeHeader(base, more http.Header, overwrite bool) http.Header {
	if base == nil {
		base = http.Header{}
	}
	if more == nil {
		return base
	}
	for k, vals := range more {
		if overwrite {
			base.Del(k)
		}

		for _, v := range vals {
			v = strings.TrimSpace(v)
			if len(v) > 0 {
				base.Add(k, v)
			}
		}
	}
	return base
}
478973
func compatibleFields(existing FieldDefinition, new FieldDefinition) bool {
	if existing.Required != new.Required {
		return false
	}
	return existing.Type.Equal(new.Type)
}