Skip to content

Instantly share code, notes, and snippets.

@scotje
Created June 17, 2020 19:53
Show Gist options
  • Save scotje/ad7cfae5b9762acff0003a6528c59470 to your computer and use it in GitHub Desktop.
Save scotje/ad7cfae5b9762acff0003a6528c59470 to your computer and use it in GitHub Desktop.
#!/bin/bash
# Usage: gh-rename-master <newbranch> [<remote>]
#
# Renames the "master" branch of the current repository both locally and on GitHub.
# Also attempts to update current user's fork if specified remote is not 'origin'
#
# Based on https://gist.github.com/mislav/5ac69530acbe1b4ca909e272caabfdba
#
# dependencies: GitHub CLI v0.10
set -e
newbranch="${1?}"
remote="${2:-origin}"
git fetch "$remote" master
git checkout -b "$newbranch" "${remote}/master" --no-track || echo "Branch ${newbranch} already exists locally..."
git push -u "$remote" "$newbranch"
git remote set-head "$remote" "$newbranch"
# update the default branch
echo "Updating default branch for remote..."
gh api -XPATCH "repos/:owner/:repo" -f default_branch="$newbranch" >/dev/null
echo "Updating base branch of outstanding PRs..."
# update the base branch of all open pull requests
for num in $(gh pr list -B master -L999 | cut -f1); do
gh api -XPATCH "repos/:owner/:repo/pulls/${num}" -f base="$newbranch" >/dev/null
echo -n .
done
# If specified remote is not "origin", check to see if "origin" is current
# user's fork and if so, update
if [ "$remote" != "origin" ]; then
echo "Given remote is not 'origin', checking if 'origin' is personal fork..."
gh_user=$(gh api user | grep -o '"login":"[^"]*' | cut -d'"' -f4)
origin_url="$(git config --get remote.origin.url)"
fork_url_pattern="github\.com[/:]${gh_user}/.*"
if [[ $origin_url =~ $fork_url_pattern ]]; then
echo "Remote 'origin' appears to be personal fork, updating default branch to '${newbranch}'..."
# `origin` is this users fork, update that too but don't track it
git push origin "$newbranch"
git remote set-head origin "$newbranch"
# update the default branch of our fork
gh api -XPATCH "repos/${gh_user}/:repo" -f default_branch="$newbranch" >/dev/null
fi
fi
printf '\nDone!\n'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment