Skip to content

Instantly share code, notes, and snippets.

@knoxilla
Created January 25, 2022 14:46
Show Gist options
  • Save knoxilla/01947dc2ebe0a9642c80df6b8dea2530 to your computer and use it in GitHub Desktop.
Save knoxilla/01947dc2ebe0a9642c80df6b8dea2530 to your computer and use it in GitHub Desktop.

Change 'master' to 'main' in place from local Github clone

The scenario:

  • You have a local clone of a Github-hosted repo with master as the default branch
  • Optionally, you have the hub command-line tool installed
  • Optionally, you have a Github Personal Access Token that can write to the relevant repos
  • You don't have any code, scripts, or workflows that depend on master existing and being the default branch
  • You are all up-to-date between local and remote repositories

Way below are detailed instructions, but it really boils down to:

You:

git branch -m master main
git push -u origin main
# change default branch on Github
# check/fix branch protection rules on Github
git push --delete origin master

Then your collaborators with existing clones:

git pull origin
git checkout main
git pull --prune origin
git branch -d master

And now you should all be good to go!

Detailed instructions:

# git clone remote repo
# cd into local clone
# look for references to 'master' branch name in scripts etc.
# and resolve those first. Search via ack, grep like:
ack -il master
# or
grep -irl master
# if all clear, continue!
# make sure we are up-to-date
git checkout master
git push
git pull
# move it
git branch -m master main
# send it on upstairs
git push -u origin main
# now address github default branch:
# via this script:
./set_default_branch_to_main.sh 
# or go to Github and fix manually:
hub browse -- settings/branches
# while in github settings, fix any branch protection rules 
# that formerly referred to 'master' by name or pattern
# delete the old github master branch
git push --delete origin master
# delete any leftover remote tracking branch for master
git pull --prune origin
# see what you have wrought!
git branch -a
#!/usr/bin/env bash
GH_USERNAME=<github_username>
GH_PA_TOKEN=<personal_access_token>
REPO_OWNER=<gh org or username>
# parse that repo name in case it does not match the local directory name
DETECTED_REPO_NAME=$(git config --get remote.origin.url | cut -d'/' -f2 | cut -d'.' -f1)
# if a repo name is passed in, use that instead, otherwise take you shot
REPO_NAME=${1-${DETECTED_REPO_NAME}}
curl -sS -u $GH_PA_USERNAME:$GH_PA_TOKEN \
-X PATCH \
-H "Accept: application/vnd.github.v3+json" \
https://api.github.com/repos/${REPO_OWNER}/${REPO_NAME} \
-d '{"default_branch":"main"}'
# output is the full JSON describing your newly updated repo
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment