Fetch PRs newest-first

Some branch names are re-used across PRs, so now we sort PRs by
newest-first when fetching so we don't get stale PRs.
This commit is contained in:
Jesse Duffield 2026-02-08 09:51:27 +11:00
parent 5d452122b3
commit a9a13619fd
2 changed files with 60 additions and 2 deletions

View file

@ -85,7 +85,7 @@ func fetchPullRequestsQuery(branches []string, owner string, repo string) string
fieldName := fmt.Sprintf("a%d", i+1)
// We fetch a few PRs per branch name because multiple forks may have PRs
// with the same head ref name. The mapping logic filters by owner later.
queries = append(queries, fmt.Sprintf(`%s: pullRequests(first: 5, headRefName: "%s") {
queries = append(queries, fmt.Sprintf(`%s: pullRequests(first: 5, headRefName: "%s", orderBy: {field: CREATED_AT, direction: DESC}) {
edges {
node {
title
@ -254,7 +254,12 @@ func GenerateGithubPullRequestMap(
prByKey := map[prKey]models.GithubPullRequest{}
for _, pr := range prs {
prByKey[prKey{owner: pr.UserName(), branchName: pr.BranchName()}] = *pr
key := prKey{owner: pr.UserName(), branchName: pr.BranchName()}
// PRs are returned newest-first from the API, so the first one we
// see for each key is the most recent and therefore the most relevant.
if _, exists := prByKey[key]; !exists {
prByKey[key] = *pr
}
}
for _, branch := range branches {

View file

@ -288,6 +288,59 @@ func TestGenerateGithubPullRequestMap(t *testing.T) {
},
},
},
{
name: "uses first PR when branch name is reused (API returns newest first)",
prs: []*models.GithubPullRequest{
// API returns newest first (CREATED_AT DESC)
{
HeadRefName: "update-sponsors",
Number: 50,
Title: "Newest PR",
State: "CLOSED",
Url: "https://github.com/jesseduffield/lazygit/pull/50",
HeadRepositoryOwner: models.GithubRepositoryOwner{Login: "jesseduffield"},
},
{
HeadRefName: "update-sponsors",
Number: 30,
Title: "Middle PR",
State: "OPEN",
Url: "https://github.com/jesseduffield/lazygit/pull/30",
HeadRepositoryOwner: models.GithubRepositoryOwner{Login: "jesseduffield"},
},
{
HeadRefName: "update-sponsors",
Number: 10,
Title: "Oldest PR",
State: "CLOSED",
Url: "https://github.com/jesseduffield/lazygit/pull/10",
HeadRepositoryOwner: models.GithubRepositoryOwner{Login: "jesseduffield"},
},
},
branches: []*models.Branch{
{
Name: "update-sponsors",
UpstreamRemote: "origin",
UpstreamBranch: "update-sponsors",
},
},
remotes: []*models.Remote{
{
Name: "origin",
Urls: []string{"git@github.com:jesseduffield/lazygit.git"},
},
},
expected: map[string]*models.GithubPullRequest{
"update-sponsors": {
HeadRefName: "update-sponsors",
Number: 50,
Title: "Newest PR",
State: "CLOSED",
Url: "https://github.com/jesseduffield/lazygit/pull/50",
HeadRepositoryOwner: models.GithubRepositoryOwner{Login: "jesseduffield"},
},
},
},
{
name: "matches with HTTPS remote URL",
prs: []*models.GithubPullRequest{