Skip to content

Instantly share code, notes, and snippets.

@louisguitton
Last active June 3, 2021 10:05
Show Gist options
  • Save louisguitton/bf0c69b3aeeda2bb421e536d6ceb09f8 to your computer and use it in GitHub Desktop.
Save louisguitton/bf0c69b3aeeda2bb421e536d6ceb09f8 to your computer and use it in GitHub Desktop.
Clean a local git repo that uses the rebase flow. Use with care!
# pip install tqdm GitPython
from git import Repo
from git.exc import GitCommandError
from tqdm import tqdm
DEFAULT_BRANCH = "master"
IGNORED_BRANCHES = [] # develop, ...
repo = Repo(".")
branches = repo.branches
start_n = len(branches)
print(f"starting with {start_n} branches")
main = [b for b in branches if b.name == DEFAULT_BRANCH][0]
other_branches = [b for b in branches if b.name != DEFAULT_BRANCH and b.name not in IGNORED_BRANCHES]
rebase_errors = []
delete_errors = []
for branch in tqdm(other_branches):
branch.checkout()
n = branch.name
try:
repo.git.rebase(DEFAULT_BRANCH)
except GitCommandError:
rebase_errors.append(n)
repo.git.rebase(abort=True)
continue
try:
main.checkout()
repo.delete_head(branch)
print("deleted branch", n)
except GitCommandError:
delete_errors.append(n)
continue
print(f"{len(rebase_errors)} rebase errors; those branches were not touched")
print(f"{len(delete_errors)} delete errors; those branches were not touched")
print(f"cleaned up {start_n - len(repo.branches)} branches")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment