Skip to content

Instantly share code, notes, and snippets.

@clarkritchie
Created February 15, 2024 19:31
Show Gist options
  • Save clarkritchie/6be7d3d8fec96901002b01df2eaafb6e to your computer and use it in GitHub Desktop.
Save clarkritchie/6be7d3d8fec96901002b01df2eaafb6e to your computer and use it in GitHub Desktop.
Quick script to delete old branches
#!/usr/bin/env python3
import sys
import subprocess
from datetime import datetime, timezone
try:
date = sys.argv[1]
yyyy,mm,dd = date.split("-")
except Exception:
print(f"Missing data argument, usage {__file__} YYYY-MM-DD")
sys.exit()
if any(var is None for var in (yyyy, dd, mm)):
print(f"Missing data argument, usage {__file__} YYYY-MM-DD")
sys.exit()
print(f"Searching for branches older than {mm}/{dd}/{yyyy}")
def get_remote_branches_by_date(remote):
# Get the list of remote branches
output = subprocess.check_output(['git', 'ls-remote', '--heads', remote]).decode('utf-8').split('\n')
branches_by_date = []
# Iterate over the remote branches
for line in output:
if not line.strip():
continue
# print("line: " + line)
commit_hash, branch_ref = line.split('\t')
branch_name = branch_ref.split('refs/heads/')[-1]
# print(f" commit_hash: {commit_hash}")
# Get the date of the last commit in the branch
last_commit_date_output = subprocess.check_output(['git', 'show', '-s', '--format=%ci', commit_hash]).decode('utf-8')
# print(f" last_commit_date_output: {last_commit_date_output}")
last_commit_date = datetime.strptime(last_commit_date_output.strip(), '%Y-%m-%d %H:%M:%S %z')
# print(f" last_commit_date: {last_commit_date}")
branches_by_date.append((branch_name, last_commit_date))
return branches_by_date
# Replace 'origin' with your remote name
remote_branches = get_remote_branches_by_date('origin')
# Make the cutoff_date timezone-aware using UTC timezone
cutoff_date = datetime(int(yyyy), int(mm), int(dd), tzinfo=timezone.utc)
recent_branches = [(name, date) for name, date in remote_branches if cutoff_date > date ]
for branch_name, last_commit_date in recent_branches:
print(f"{last_commit_date} -- {branch_name}")
print(f" git push origin :{branch_name}\n")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment