Skip to content

Instantly share code, notes, and snippets.

@PurpleBooth
Last active September 17, 2021 15:07
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PurpleBooth/6983e5c4def4f8721d4a697a3f4606a7 to your computer and use it in GitHub Desktop.
Save PurpleBooth/6983e5c4def4f8721d4a697a3f4606a7 to your computer and use it in GitHub Desktop.
Change your default branch on github without checkout anything out

change-github-default-branch.sh

Usage

change-github-default-branch.sh "$GITHUB_TOKEN" PurpleBooth/homebrew-repo

Does not delete the old default branch, or change where pull requests are based from, incase something breaks.

Thanks mfcrocker for ubuntu fixes.

#!/usr/bin/env bash
set -euo pipefail
if [ $# -ne 3 ] && [ $# -ne 2 ]; then
echo "USAGE: $0 pat_token user/repo [new_default]" 1>&2
echo
printf "pat_token\tA GitHub personal access with at least repo:public_repo, or repo on private repositores https://github.com/settings/tokens/new\n"
printf "user/repo\tA github repository, for example purplebooth/readable-name-generator\n"
printf "new_default\tName of the new default branch, default: main\n"
exit 1
fi
GITHUB_TOKEN="$1"
REPO="$2"
DEFAULT_BRANCH_NAME="${3:-main}"
LATEST_SHA="$(
curl \
--silent \
-X GET \
--header "Authorization: token $GITHUB_TOKEN" \
--location \
--output - \
"https://api.github.com/repos/$REPO/git/refs/heads" |
python -c 'import sys, json; print(json.load(sys.stdin)[0]["object"]["sha"])'
)"
curl \
--silent \
-X POST \
--header "Authorization: token $GITHUB_TOKEN" \
--header "Content-Type: application/json" \
-d "{ \"ref\": \"refs/heads/$DEFAULT_BRANCH_NAME\", \"sha\": \"$LATEST_SHA\" }" \
"https://api.github.com/repos/$REPO/git/refs"
curl \
--silent \
-X PATCH \
--header "Authorization: token $GITHUB_TOKEN" \
--header "Content-Type: application/json" \
--data "{\"default_branch\": \"$DEFAULT_BRANCH_NAME\" }" \
"https://api.github.com/repos/$REPO"
@PurpleBooth
Copy link
Author

PurpleBooth commented Jun 13, 2020

It's on my GH if you spot any problems! PurpleBooth/change-github-default-branch.sh, I'll probably stick updates there

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment