66 "fmt"
77 "io"
88 "net/http"
9+ "sort"
910 "strings"
1011 "time"
1112
@@ -621,7 +622,7 @@ func PullRequestByNumber(client *Client, repo ghrepo.Interface, number int) (*Pu
621622 return & resp .Repository .PullRequest , nil
622623}
623624
624- func PullRequestForBranch (client * Client , repo ghrepo.Interface , baseBranch , headBranch string ) (* PullRequest , error ) {
625+ func PullRequestForBranch (client * Client , repo ghrepo.Interface , baseBranch , headBranch string , stateFilters [] string ) (* PullRequest , error ) {
625626 type response struct {
626627 Repository struct {
627628 PullRequests struct {
@@ -637,9 +638,9 @@ func PullRequestForBranch(client *Client, repo ghrepo.Interface, baseBranch, hea
637638 }
638639
639640 query := `
640- query PullRequestForBranch($owner: String!, $repo: String!, $headRefName: String!) {
641+ query PullRequestForBranch($owner: String!, $repo: String!, $headRefName: String!, $states: [PullRequestState!] ) {
641642 repository(owner: $owner, name: $repo) {
642- pullRequests(headRefName: $headRefName, states: OPEN , first: 30) {
643+ pullRequests(headRefName: $headRefName, states: $states , first: 30) {
643644 nodes {
644645 id
645646 number
@@ -726,6 +727,7 @@ func PullRequestForBranch(client *Client, repo ghrepo.Interface, baseBranch, hea
726727 "owner" : repo .RepoOwner (),
727728 "repo" : repo .RepoName (),
728729 "headRefName" : branchWithoutOwner ,
730+ "states" : stateFilters ,
729731 }
730732
731733 var resp response
@@ -734,7 +736,8 @@ func PullRequestForBranch(client *Client, repo ghrepo.Interface, baseBranch, hea
734736 return nil , err
735737 }
736738
737- for _ , pr := range resp .Repository .PullRequests .Nodes {
739+ prs := sortPullRequestsByState (resp .Repository .PullRequests .Nodes )
740+ for _ , pr := range prs {
738741 if pr .HeadLabel () == headBranch {
739742 if baseBranch != "" {
740743 if pr .BaseRefName != baseBranch {
@@ -1149,6 +1152,14 @@ func BranchDeleteRemote(client *Client, repo ghrepo.Interface, branch string) er
11491152 return client .REST (repo .RepoHost (), "DELETE" , path , nil , nil )
11501153}
11511154
1155+ // sortPullRequestsByState ensures that OPEN PRs precede non-open states (MERGED, CLOSED)
1156+ func sortPullRequestsByState (prs []PullRequest ) []PullRequest {
1157+ sort .SliceStable (prs , func (a , b int ) bool {
1158+ return prs [a ].State == "OPEN"
1159+ })
1160+ return prs
1161+ }
1162+
11521163func min (a , b int ) int {
11531164 if a < b {
11541165 return a
0 commit comments