Skip to content

Instantly share code, notes, and snippets.

@tomleo
Created March 23, 2015 23:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tomleo/0f005e69aaefa0f4ca1b to your computer and use it in GitHub Desktop.
Save tomleo/0f005e69aaefa0f4ca1b to your computer and use it in GitHub Desktop.
Deletes Stale Branches from your Github repo

Delete Stale Branches

This script makes the following assumptions

  • develop and master are special branches that are never deleted
  • upstream is your canonical repository
  • origin is your fork of upstream
  • The remote origin is a gitHub repo
  • The origin repo is SSH not HTTPS i.e. your ssh key is used instead of manually entering user name and password
#!/usr/bin/env python
from subprocess import Popen, PIPE
MASTER = 'master'
DEVELOP = 'develop'
SPECIAL_BRANCHES = [MASTER, DEVELOP]
def get_merged_branches_list():
p1 = Popen('git branch -a --merged', stdout=PIPE, stderr=PIPE, shell=True)
_merged_branches, _ = p1.communicate()
merged_branches = _merged_branches.split()
merged_branches.pop(merged_branches.index('*')) # For some reason * is included
return merged_branches
def get_local_branches():
p2 = Popen('git branch', stdout=PIPE, stderr=PIPE, shell=True)
_local_branches, _ = p2.communicate()
local_branches = _local_branches.split()
local_branches.pop(local_branches.index('*'))
return local_branches
def remove_local_branch(branch_name):
remove_cmd = 'git branch -d %s' % branch_name
p = Popen(remove_cmd, stdout=PIPE, stderr=PIPE, shell=True)
stdout, stderr = p.communicate()
if stdout:
print stdout
if stderr:
print stderr
else:
print "Done"
def remove_remote_branch(branch_name):
remove_cmd = 'git push origin :%s' % branch_name
p = Popen(remove_cmd, stdout=PIPE, stderr=PIPE, shell=True)
stdout, stderr = p.communicate()
if stdout:
print stdout
if stderr:
print stderr
else:
print "Done"
def main():
"""
This function will see if any local branches have been merged. If they have
it will delete them locally and on origin.
"""
merged_branches = get_merged_branches_list()
local_branches = get_local_branches()
for branch in local_branches:
if branch in SPECIAL_BRANCHES:
continue
for mbranch in merged_branches: # Yeah O^n!
if branch in mbranch:
print "Removing Local branch..."
remove_local_branch(branch)
print "Removing Branch from Origin..."
remove_remote_branch(branch)
print "\n"
break
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment