Script below is what I've used to industrialise moving from a 'master' branch to 'main' both locally and remotely.
Have a local Github authentication token set in environment variable GIT_TOKEN
Assumes you have a repo with more than 1 commit, and a local master
branch tracking a remote master
branch.
For the script to run it checks you are on a local master
branch, and it is up to date with the latest HEAD
commit on the remote master
branch.
#!/bin/bash
# Step 1: Get the remote repository URL
REMOTE_URL=$(git remote get-url origin)
# Extract username and repository name from the remote URL
USERNAME=$(echo "$REMOTE_URL" | cut -d/ -f4)
REPOSITORY=$(echo "$REMOTE_URL" | cut -d/ -f5 | cut -d. -f1)
# Step 2: Check if on local master branch
CURRENT_BRANCH=$(git symbolic-ref --short HEAD)
if [ "$CURRENT_BRANCH" != "master" ]; then
echo "ERROR: Not on the local 'master' branch. Please switch to the 'master' branch and try again."
exit 1
fi
# Step 3: Check if local branch is up to date with remote head commit
if ! git fetch origin; then
echo "ERROR: Failed to fetch the latest changes from the remote repository."
exit 1
fi
if ! git diff --quiet master origin/master; then
echo "ERROR: Local 'master' branch is not up to date with the latest remote head commit. Please pull the latest changes and try again."
exit 1
fi
# Step 4: Create a new branch named 'main' and switch to it
git branch main
git checkout main
# Step 5: Push the 'main' branch to the remote repository
git push -u origin main
# Step 6: Set the new 'main' branch as the default branch on GitHub
REPO_URL="https://api.github.com/repos/$USERNAME/$REPOSITORY"
curl -X PATCH \
-H "Authorization: Bearer $GIT_TOKEN" \
-H "Accept: application/vnd.github.v3+json" \
-d '{"default_branch": "main"}' \
"$REPO_URL"
# Step 7: Update local branches that track the remote 'master' branch
git branch -m master main
git fetch origin
git branch --unset-upstream main
git branch -u origin/main main
# Step 8: Push the renamed branches to the remote repository
git push origin main
# Step 9: Delete the remote 'master' branch
git push origin --delete master
# Step 10: Delete the local 'master' branch
git branch -D master