22

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?

Daniel X Moore
  • 14,029
  • 16
  • 78
  • 89

2 Answers2

43

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

Eric Dobbs
  • 3,094
  • 2
  • 18
  • 15
Ivan Zuzak
  • 16,774
  • 3
  • 65
  • 58
  • 1
    100% this. Also if you're using any good wrapper library, they should all give you easy access to this. – Ian Stapleton Cordasco May 11 '13 at 21:45
  • There is actually "default_branch" key. – Alexei Sholik May 11 '13 at 21:46
  • @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. – Ivan Zuzak May 11 '13 at 21:53
  • @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. – Ian Stapleton Cordasco May 12 '13 at 00:29
  • 3
    `master_branch` only exists for backwards compatibility. `default_branch` will replace `master_branch` in the [next version of the API](http://developer.github.com/#expected-changes). – jasonrudolph May 14 '13 at 17:07
  • "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](https://github.com/contact). – jasonrudolph May 14 '13 at 17:08
1

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

KyleMit
  • 35,223
  • 60
  • 418
  • 600