GraphQL: getting the n most recent branches ("refs/heads/") in a repository

Hey there,

I’m trying to write a query against the GraphQL API that returns the ~100 most recent branches (i.e., /refs/heads/) for a repository. 

Please excuse the Hacklang string interpolation; so far I have: 

{
    repository(owner: "{$repo['owner']}", name: "{$repo['name']}") {
        refs(first: 100, refPrefix:"refs/heads/") {
            nodes {
                name
                target {
                    ...on Commit {
                        author {
                            user {
                                login
                            }
                        }
                        pushedDate
                        oid
                    }
                }
            }
        }
    }
}

…however, I can’t find a way to return the refs in descending order of the target commit’s pushedDate since the RefOrder parameter accepted by refs only allows ordering by TAG_COMMIT_DATE for refs/tags/ (tags) and not refs/heads/ (branches). As a result, the query above only returns the first 100 PRs in alphabetical order. 

Worst case, I can use pagination to query for all refs/tags/ and filter them that way. That will be quite expensive for repos with a lot of branches, though, so if there’s a way to do it in a single query, I would love to know.

Thank you!

1 Like

You mention that “the query above only returns the first 100 PRs in alphabetical order” (emphasis mine). A branch isn’t necessarily a PR, though a PR is always a branch on some repository. So if you’re looking for the 100 most recent PRs and not branches, you should be able to use the following query:

{
  repository(owner: "atom", name: "atom") {
    pullRequests(first: 100, orderBy: { field: UPDATED_AT, direction: DESC }) {
      nodes {
        author {
          login
        }
        updatedAt
        headRepository {
          nameWithOwner
        }
        headRefName
      }
    }
  }
}

This will, of course, include branches originated on forks, which may not be what you want. But perhaps it will get you closer to your goal?

Let us know if you have more questions.