Programmatically convert Github master branch to main

February 15, 2021 0 By addshore

Back in 2020 Github said that the default settings for new repositories would change.

On Oct. 1, 2020, any new repositories you create will use main as the default branch, instead of master

Some blog post on Medium

Github provided some advice for renaming branches focused around how this can be done in the UI. But with the Github CLI tool that was also release at the end of 2020 you can programatically make this change too.

The Github CLI tool is called gh. The README for the tool has installation instructions for a variety of platforms. One of the commands that it enables is called api, which can be used to “Make an authenticated GitHub API request”.

The Github API obviously allows you to perform most actions that can be performed by the UI, this we can use the gh cli tool to rename the branches of repositories.

For example, for the addwiki/addwiki repository, we can rename the master to main branch using the following command:

gh api --method POST repos/addwiki/addwiki/branches/master/rename --field new_name='main'Code language: JavaScript (javascript)

And you can use such a command in whatever loops etc you want to, to quickly rename a whole bunch of branches in a whole bunch of repositories.

You can read more on the API docs here and the api cli command here.