Skip to content

Instantly share code, notes, and snippets.

@nicholsn
Created June 16, 2020 23:40
Show Gist options
  • Select an option

  • Save nicholsn/24737bd098cb8738ffce20bf93fe84b6 to your computer and use it in GitHub Desktop.

Select an option

Save nicholsn/24737bd098cb8738ffce20bf93fe84b6 to your computer and use it in GitHub Desktop.
Update your default branch in GitHub (default: main)
"""Update your default branch in GitHub (default: main).
This script will rename the master branch (default: main), push the new branch to GitHub,
optionally delete the master branch (default: True, delete master).
python update_github_default_branch.py
Installation
------------
pip install GitPython PyGitHub
# Create a Github Token: https://github.com/settings/tokens/
export GITHUB_API_KEY=<token>
cd <into a clone of the repo to update>
This assumes your remote is named "origin" and you are currently on the 'master'
branch.
"""
import os
import git
import github
from git import InvalidGitRepositoryError
def main(argv=None):
api_key = os.environ.get('GITHUB_API_KEY')
try:
repo = git.Repo('.')
except InvalidGitRepositoryError as err:
print(f'Please change to the root repo directory. Currently at: {err}')
return 0
try:
assert repo.active_branch.name == 'master'
except AssertionError:
print('Please change to the master branch of this repo.')
#return 0
repo.active_branch.rename(argv.branch)
remote = repo.remote()
remote.push('main')
remote_url = list(remote.urls)[0]
if remote_url.startswith('https'):
repo_name = '/'.join(remote_url.split('.')[1].split('/')[1:])
elif remote_url.startswith('git'):
repo_name = remote_url.split('.')[1].split(':')[1]
else:
print('Remote URL protocol unknown: {remot_url}')
return 0
try:
print(f'Setting default branch for: {repo_name}')
g = github.Github(api_key)
gh_repo = g.get_repo(repo_name)
except UnknownObjectException:
print('Please ensure that your API key has permissions to manage this repo.')
return 0
gh_repo.edit(default_branch=argv.branch)
if argv.delete_master:
gh_repo.get_git_ref('heads/master').delete()
if __name__ == '__main__':
import sys
import argparse
parser = argparse.ArgumentParser(prog='update_github_default_branch.py',
description='Update your default branch in GitHub.',
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog=__doc__)
parser.add_argument('-b --branch',
dest='branch',
type=str,
default='main',
help="Set the name of the default branch in Github.")
parser.add_argument('-d --delete-master',
dest='delete_master',
type=bool,
default=True,
help="Delete the master branch.")
args = parser.parse_args()
sys.exit(main(argv=args))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment