Last active
June 21, 2020 06:08
-
-
Save ATGardner/40072104ab18e689b9a789e4834bdd15 to your computer and use it in GitHub Desktop.
A script to convert all personal GitHub repos' default branch from 'master' to 'main'
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /bin/bash | |
# The script requires jq (https://stedolan.github.io/jq/) and gh-cli (https://cli.github.com/) > 0.10 | |
# It assumes the current user is already logged into their GitHub account, and that they have SSH access set up | |
# with `gh config set git_protocol ssh` | |
# | |
# The script goes over all (up to 100) personal, non-archived, non-forked repositories, that currently has 'master' as | |
# their default branch and replaces it with NEW_DEFAULT (defined as 'main', but can be easily changed) | |
# | |
# It clones a new local repo from each one, creates a NEW_DEFAULT branch in it, pushes it, and also sets it as the | |
# default branch in GitHub. | |
# The script *does not* change or update any existing local repos. This will have to be done manually, or with a | |
# different script. | |
# | |
# used samples and tips from https://github.com/cli/cli/issues/1215 (thanks, metcalfc) | |
NEW_DEFAULT=main | |
LOGIN=$(gh api graphql -f query='query b{ | |
viewer { | |
login | |
} | |
}' | jq '.data.viewer.login' --raw-output -) | |
REPOSITORIES=($(gh api graphql -F q='user:${LOGIN} fork:false archived:false' -f query='query($q:String!) { | |
repos: search(query: $q, type: REPOSITORY, first: 100) { | |
codeCount | |
edges { | |
node { | |
... on Repository { | |
name | |
defaultBranchRef { | |
name | |
} | |
} | |
} | |
} | |
} | |
}' | jq '.data.repos.edges[] | select (.node.defaultBranchRef.name=="master") | .node.name' --raw-output -)) | |
echo "Updating ${#REPOSITORIES[@]} repositories" | |
for i in "${REPOSITORIES[@]}"; do | |
echo "updating ${i}" | |
TEMP_FOLDER="temp_${i}" | |
gh repo clone $i "${TEMP_FOLDER}" || exit 1 | |
cd ${TEMP_FOLDER} | |
OLD_DEFAULT=$(gh api "repos/:owner/:repo" | jq '.default_branch' --raw-output) || exit 1 | |
git checkout -b "$NEW_DEFAULT" "origin/${OLD_DEFAULT}" --no-track || exit 1 | |
git push -u origin "$NEW_DEFAULT" || exit 1 | |
git REMOTE set-head origin "$NEW_DEFAULT" || exit 1 | |
gh api -XPATCH "repos/:owner/:repo" -f default_branch="$NEW_DEFAULT" >/dev/null || exit 1 | |
cd .. | |
rm -rf ${TEMP_FOLDER} | |
echo "done ${i}" | |
done | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment