Is there a stable url to always get the default branch in github?

Viewed 937

In past you could in most cases just add blob/master/ to a github url get the raw file, i.e. https://github.com/jacoco/jbang-catalog/blob/master/jbang-catalog.json`

Now with old repos using master but new using main that trick don't work on new repos.

Is there a way to avoid having to do a call to the rest api to find default branch main ?

like a magic marker like blob/@default/ or similar ?

2 Answers

The solution is to use HEAD. That symbolic name will give you tip of the default branch no matter what its name is.

It's always been required to do an actual lookup of the default branch name because people have always been able to choose a default branch that differs from the default Git or GitHub offered. It just used to be less common to use a name other than master, but many projects have long used a different name.

If you don't want to use the REST API, then you can look this up using Git:

$ git ls-remote --symref origin | head -n1
ref: refs/heads/dev     HEAD

In this case, the default branch is dev.

If you just want to get the object on the default branch in the GitHub user interface, then you can use HEAD: https://github.com/git/git/blob/HEAD/README.md. Note that this doesn't work in a local repository, since HEAD refers to your locally checked out branch there.

Otherwise, if you actually want to know the name of the branch, then you'll need to query the API. This is exposed in the REST API under default_branch and should also be available via the GraphQL API.

Related