Rename GitHub default branch from CLI
Install GitHub’s official CLI and create the script gh-rename-master
with the contents below.
After this, it’s possible to run gh-rename-master main
to replace master
with main
within the current repository.
#!/bin/bash
# Usage: gh-rename-master <newbranch> [<remote>]
#
# Renames the "master" branch of the current repository both locally and on GitHub.
#
# dependencies: GitHub CLI v0.10
set -e
newbranch="${1?}"
remote="${2:-origin}"
git fetch "$remote" master
git checkout -b "$newbranch" "${remote}/master" --no-track
git push -u "$remote" "$newbranch"
git remote set-head "$remote" "$newbranch"
# update the default branch
gh api -XPATCH "repos/:owner/:repo" -f default_branch="$newbranch" >/dev/null
# update the base branch of all open pull requests
for num in `gh pr list -B master -L999 | cut -f1`; do
gh api -XPATCH "repos/:owner/:repo/pulls/${num}" -f base="$newbranch" >/dev/null
echo -n .
done
printf '\nDone!\n'
Source: https://gist.github.com/mislav/5ac69530acbe1b4ca909e272caabfdba
Also handy to have around:
gh alias \
set default-branch \
'api -X PATCH repos/:owner/:repo --raw-field default_branch=$1'
This will allow you to run gh default-branch main
to change the default branch for a new repository.
Source: https://dev.to/softprops/digitally-unmastered-the-github-cli-edition-1cc4