Skip to content

Instantly share code, notes, and snippets.

@fm-sys
Last active August 2, 2021 21:49
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 fm-sys/469156b2eb60b885ccff33da33eb0392 to your computer and use it in GitHub Desktop.
Save fm-sys/469156b2eb60b885ccff33da33eb0392 to your computer and use it in GitHub Desktop.
A python script which helps you with cleaning up local and remote branches of merged PR's.
from git import Repo
import subprocess, os
class PR:
def __init__(self, line):
self.id, self.name, self.branch, self.state = line.split("\t")
self.branch = self.branch.split(":")[1] # this removes 'your_user_name:'
def __repr__(self):
return "PR ID: '" + self.id + "' \tBRANCH: '" + self.branch + "' \t NAME: '" + self.name + "'"
repo = Repo('path/to/repo') # Replace with the path to your repository (don't use backslashs!). E.g. "C://github/myrepo"
assert not repo.bare
def branch_exists(branchName):
for ref in repo.references:
if branchName == ref.name:
return ref
# Replace "your_user_name" with your correct user name
returnVal = subprocess.run(['gh', 'pr', 'list', '-A', 'your_user_name', '-s', 'merged'], stdout=subprocess.PIPE).stdout.decode('utf-8')
# for all my recently merged PR's:
for prLine in returnVal.splitlines():
pr = PR(prLine)
localBranch = branch_exists(pr.branch)
originBranch = branch_exists("origin/" + pr.branch)
if localBranch != None and originBranch != None and localBranch.commit == originBranch.commit:
print("delete branch '" + pr.branch + "' local and on remote 'origin'")
repo.delete_head(localBranch)
repo.remotes.origin.push(":" + originBranch.remote_head)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment