Skip to content

Instantly share code, notes, and snippets.

@j2kun
Last active June 9, 2020 03:36
Show Gist options
  • Save j2kun/5d83fbe037ce9967e23535a6622af2ea to your computer and use it in GitHub Desktop.
Save j2kun/5d83fbe037ce9967e23535a6622af2ea to your computer and use it in GitHub Desktop.
Changing default branch on all your git repos

Rename all default branches of a github user

Basically, it does this for all the repos you own

Requirements

brew install hub
brew install jq

Usage

Copy the bash script below, change your user name and the desired old/new default branch names. Run.

Should be idempotent if it fails halfway through. Try passing in a file with a single repo to test it out first.

I'm not the best at bash scripting, so feel free to suggest improvements!

Caveats

  • Does not update private repos
  • Does not delete the original default branch
  • Does not update pull requests to point to main
  • Use at your own risk

Script

#!/bin/bash

MYTMPDIR=$(mktemp -d) || exit 1
trap 'rm -rf "$MYTMPDIR"' EXIT
cd $MYTMPDIR
USER=j2kun

hub api -X GET -F per_page=100 -F page=1 users/j2kun/repos | jq -r '.[] | .name' > repos.txt
hub api -X GET -F per_page=100 -F page=2 users/j2kun/repos | jq -r '.[] | .name' >> repos.txt

# usage: update_default_branch_to <repo_name> [main] [master]
# Clone the repo, rename its default branch
function update_default_branch_to {
  REPO=$1
  NEW_DEFAULT=${2:-main}
  OLD_DEFAULT=${3:-master}
  CURRENT_DEFAULT=$(hub api -X GET repos/$USER/$REPO | jq -r '.default_branch')
  if [ $CURRENT_DEFAULT = $OLD_DEFAULT ]
  then
    echo "------------------------------------------------------"
    echo "Updating repos/$USER/$REPO"
    echo "------------------------------------------------------"
    rm -rf "$REPO"
    hub clone "$USER/$REPO"
    cd "$REPO"
    git branch -m "$OLD_DEFAULT" "$NEW_DEFAULT"
    git push -u origin "$NEW_DEFAULT"
    echo "{\"default_branch\": \"$NEW_DEFAULT\"}" | hub api -X PATCH "repos/$USER/$REPO" --input=- > /dev/null
    cd -
  else
    echo "Skipping repos/$USER/$REPO. Remote default is not '$OLD_DEFAULT', but is '$CURRENT_DEFAULT'"
  fi
}

while read repo; do
  update_default_branch_to $repo main master
done < repos.txt
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment