How do I find the default branch for a repository using the Github v3 API
Asked Answered
P

3

33

My goal is to get the tree for the latest SHA in the default branch

GET /repos/:owner/:repo/git/trees/:sha

How do I find the lastest SHA from the default branch?

I know that I can call

GET /repos/:owner/:repo/branches/:branch

But I can't just use "master" for the branch as not all repos use master as the default branch.

How do I find out what the default branch for a repo is?

Profusive answered 11/5, 2013 at 18:34 Comment(0)
A
68

Make a call to /repos/:owner/:repo and read the default_branch property value - this is the name of the default branch. See example response here: http://developer.github.com/v3/repos/#get

Abramson answered 11/5, 2013 at 21:31 Comment(6)
100% this. Also if you're using any good wrapper library, they should all give you easy access to this.Caplan
There is actually "default_branch" key.Boarish
@android Hey, you're right -- there are two keys: the master_branch key and the default_branch key. Do you know what the difference is? I'm guessing they'll both have the same value always, and that one key was deprecated at some point in time.Abramson
@android at times default_branch is empty (nil) while master_branch isn't and at other times neither is empty. I haven't been able to discover a reason for it yet and frankly don't feel it's important enough to bug the API team about it.Caplan
master_branch only exists for backwards compatibility. default_branch will replace master_branch in the next version of the API.Zirconia
"at times default_branch is empty (nil) while master_branch isn't and at other times neither is empty." => They should always have the same value. If you see a place where they have different values, please let us know.Zirconia
C
4

This is also now avaialable with the github cli as well

gh repo list <Your_Name> --json nameWithOwner,defaultBranchRef

If you want to slightly cleanup the output, you can remap with jq

gh repo list <Your_Name> --json nameWithOwner,defaultBranchRef \
  --jq ".[] | { nameWithOwner , defaultBranch: .defaultBranchRef.name}"

The advantage to this approach being auth is integrated and much easier to manage

Carburet answered 30/1, 2022 at 18:5 Comment(0)
B
2

This is a cleaner and faster way using gh:

gh api repos/{owner}/{repo} --jq '.default_branch'

(in Git Bash leading slashes cause it to be interpreted as a local absolute path)

Buckshot answered 22/7, 2022 at 17:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.