Skip to content

Commit 123dcfc

Browse files
Add git remote branch cleaner script.
1 parent a532141 commit 123dcfc

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

dev/git-branch-cleaner-remote

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
#!/usr/bin/env python
2+
# -*- coding: utf-8 -*-
3+
4+
# This scripts helps removing remote Git branches.
5+
# Run it from a git repo dir. It will open the Git branches list
6+
# in your favorite editor. Delete some branches from the list.
7+
# Save and close the file. The script applies the changes to the repo.
8+
9+
from subprocess import call, Popen, PIPE
10+
from os import getenv
11+
import re
12+
13+
# configure commands used in this script
14+
editor_command = getenv('EDITOR')
15+
branch_command = 'git branch -r'
16+
mktemp_command = 'mktemp'
17+
18+
# takes 'git branch' output and returns a set of branches
19+
def branches_to_list(text):
20+
branches = set()
21+
for branch in re.split('\n', text):
22+
branch = re.sub(' .+', '', branch.lstrip());
23+
if branch is not '':
24+
branches.add(branch)
25+
return branches
26+
27+
# create a temp file
28+
tmp_file = Popen(mktemp_command, stdout=PIPE).communicate()[0].decode().rstrip()
29+
30+
# write git branches to the temp file
31+
call('%s > %s' % (branch_command, tmp_file), shell=True)
32+
33+
# get original branches
34+
original_branches = branches_to_list(open(tmp_file, 'r').read())
35+
36+
# edit the temp file with the editor command
37+
call('%s %s' % (editor_command, tmp_file), shell=True)
38+
39+
# get new branches
40+
new_branches = branches_to_list(open(tmp_file, 'r').read())
41+
42+
# adding and renaming branches is not supported
43+
if(new_branches.difference(original_branches)):
44+
exit('Aborting! Do not add or rename branches, just remove them.')
45+
46+
# remove branches with Git
47+
for branch in original_branches.difference(new_branches):
48+
pushable = re.sub('/', ' :', branch)
49+
call('git branch -rd %s' % branch, shell=True)
50+
call('git push %s' % pushable, shell=True)
51+

0 commit comments

Comments
 (0)