I'm currently writing a small project using the GitHub API v3.
I'm constantly doing a calculation based on the number of branches a repo contains. I can't seem to find a way to do so without also requesting to list all the branches of that repo. The need to request that repo's branches adds unnecessary running time, especially when dealing with hundreds of repos, containing dozens of branches each.
The apparent lack of ability to do so caught me by a small surprise, since a quite similar operation, getting the number of repos of an organization, is easily available by doing so:
GET https://api.github.com/orgs/cloudify-cosmo
, using proper GitHub authentication credentials.public_repos
and total_private_repos
So, am I missing something? Is there a similarly-convenient way (or any way at all) of getting the number of branches of a repo without having to list its branches?
There's no such attribute currently.
However, there's a neat trick you can use to avoid fetching all pages. If you set per_page
to 1
, then each page will contain 1 item and the number of pages (revealed by the last page) will also tell you the total number of items:
https://developer.github.com/v3/#pagination
So, with just one request -- you can get the total number of branches. For example, if you fetch this URL and inspect the Link header:
https://api.github.com/repos/github/linguist/branches?per_page=1
then you'll notice that the Link
header is:
Link: <https://api.github.com/repositories/1725199/branches?per_page=1&page=2>; rel="next", <https://api.github.com/repositories/1725199/branches?per_page=1&page=28>; rel="last"
This tells you that there are 28 pages of results, and because there is one item per page -- the total number of branches is 28.
Hope this helps.
You can also use GraphQL API v4 to get branch count easily :
{
repository(owner: "google", name: "gson") {
refs(first: 0, refPrefix: "refs/heads/") {
totalCount
}
}
}
Try it in the explorer
which gives :
{
"data": {
"repository": {
"refs": {
"totalCount": 13
}
}
}
}
As you are doing this on multiple repo, it's also more straightforward with GraphQL as you can build the query with different aliases per repo & use only one request to get branch count for all of these :
{
fetch: repository(owner: "github", name: "fetch") {
...RepoFragment
}
hub: repository(owner: "github", name: "hub") {
...RepoFragment
}
scientist: repository(owner: "github", name: "scientist") {
...RepoFragment
}
}
fragment RepoFragment on Repository {
refs(first: 0, refPrefix: "refs/heads/") {
totalCount
}
}
Try it in the explorer
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With