29

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,637
  • 17
  • 80
  • 92

3 Answers3

60

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,844
  • 3
  • 19
  • 16
Ivan Zuzak
  • 18,068
  • 3
  • 69
  • 61
  • 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
  • 1
    @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
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

KyleMit
  • 30,350
  • 66
  • 462
  • 664
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)

NGT
  • 13
  • 4
pborenstein
  • 446
  • 4
  • 5