MCPcopy Create free account
hub / github.com/cli/cli / findForRefs

Function findForRefs

pkg/cmd/pr/shared/finder.go:384–440  ·  view source on GitHub ↗
(httpClient *http.Client, prRefs PRFindRefs, stateFilters, fields []string)

Source from the content-addressed store, hash-verified

382}
383
384func findForRefs(httpClient *http.Client, prRefs PRFindRefs, stateFilters, fields []string) (*api.PullRequest, error) {
385 type response struct {
386 Repository struct {
387 PullRequests struct {
388 Nodes []api.PullRequest
389 }
390 DefaultBranchRef struct {
391 Name string
392 }
393 }
394 }
395
396 fieldSet := set.NewStringSet()
397 fieldSet.AddValues(fields)
398 // these fields are required for filtering below
399 fieldSet.AddValues([]string{"state", "baseRefName", "headRefName", "isCrossRepository", "headRepositoryOwner"})
400
401 query := fmt.Sprintf(`
402 query PullRequestForBranch($owner: String!, $repo: String!, $headRefName: String!, $states: [PullRequestState!]) {
403 repository(owner: $owner, name: $repo) {
404 pullRequests(headRefName: $headRefName, states: $states, first: 30, orderBy: { field: CREATED_AT, direction: DESC }) {
405 nodes {%s}
406 }
407 defaultBranchRef { name }
408 }
409 }`, api.PullRequestGraphQL(fieldSet.ToSlice()))
410
411 variables := map[string]any{
412 "owner": prRefs.BaseRepo().RepoOwner(),
413 "repo": prRefs.BaseRepo().RepoName(),
414 "headRefName": prRefs.UnqualifiedHeadRef(),
415 "states": stateFilters,
416 }
417
418 var resp response
419 client := api.NewClientFromHTTP(httpClient)
420 err := client.GraphQL(prRefs.BaseRepo().RepoHost(), query, variables, &resp)
421 if err != nil {
422 return nil, err
423 }
424
425 prs := resp.Repository.PullRequests.Nodes
426 sort.SliceStable(prs, func(a, b int) bool {
427 return prs[a].State == "OPEN" && prs[b].State != "OPEN"
428 })
429
430 for _, pr := range prs {
431 // When the head is the default branch, it doesn't really make sense to show merged or closed PRs.
432 // https://github.com/cli/cli/issues/4263
433 isNotClosedOrMergedWhenHeadIsDefault := pr.State == "OPEN" || resp.Repository.DefaultBranchRef.Name != prRefs.QualifiedHeadRef()
434 if prRefs.Matches(pr.BaseRefName, pr.HeadLabel()) && isNotClosedOrMergedWhenHeadIsDefault {
435 return &pr, nil
436 }
437 }
438
439 return nil, &NotFoundError{fmt.Errorf("no pull requests found for branch %q", prRefs.QualifiedHeadRef())}
440}
441

Callers 1

FindMethod · 0.85

Calls 15

NewStringSetFunction · 0.92
PullRequestGraphQLFunction · 0.92
NewClientFromHTTPFunction · 0.92
AddValuesMethod · 0.80
GraphQLMethod · 0.80
MatchesMethod · 0.80
HeadLabelMethod · 0.80
ToSliceMethod · 0.65
RepoOwnerMethod · 0.65
BaseRepoMethod · 0.65
RepoNameMethod · 0.65
UnqualifiedHeadRefMethod · 0.65

Tested by

no test coverage detected