Created
May 3, 2020 23:35
-
-
Save chrisjbillington/44fa5a63028a4c4601da68cb41ebc337 to your computer and use it in GitHub Desktop.
Script to delete all remote branches that have been merged into master.
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
from subprocess import check_output, check_call | |
import sys | |
USAGE = """Error: invalid arguments. | |
usage: python delete_branches.py local_repository [remote] | |
remote defaults to 'origin' if not given.""" | |
try: | |
REPO = sys.argv[1] | |
except IndexError: | |
print(USAGE) | |
sys.exit(1) | |
try: | |
REMOTE = sys.argv[2] | |
except IndexError: | |
REMOTE = 'origin' | |
if len(sys.argv) > 3: | |
print(USAGE) | |
sys.exit(1) | |
# Ensure we know about all remote branches: | |
check_call(['git', 'fetch', '--prune', REMOTE], cwd=REPO) | |
# Get a list of all remote branches that are merged into <REMOTE>/master | |
output = check_output( | |
[ | |
'git', | |
'branch', | |
'-r', | |
'--merged', | |
f'{REMOTE}/master', | |
'--format', | |
'%(refname:short)', | |
], | |
cwd=REPO, | |
) | |
branches = output.decode().splitlines() | |
# Only delete branches from the given remote, and not HEAD or master: | |
branches_to_delete = [] | |
for branch_path in branches: | |
remote, branch = branch_path.split('/', 1) | |
if remote == REMOTE and branch not in ('HEAD', 'master'): | |
branches_to_delete.append(branch) | |
# Delete 'em: | |
for i, branch in enumerate(branches_to_delete): | |
print(f"({i+1}/{len(branches_to_delete)}) deleting {REMOTE}/{branch}...") | |
check_call(['git', 'push', REMOTE, '--delete', branch], cwd=REPO) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment