Automate Git operations with GitPython. Scan a repository for stale branches not merged into main and untouched for over 6 months. Check if each branch is fully merged using git merge-base and delete if safe.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Providing GitPython script for stale branch cleanup
I'm preparing a Python script using GitPython that scans local branches older than six months not merged into main (or master), confirms merge status via git merge-base --is-ancestor, and deletes branches safely. The script will include disclaimers about careful usage and optional remote branch deletion.
Below is a self‑contained example script using GitPython that:
Opens a local repository.
Figures out your default branch (main or master by default).
Scans local branches that have not been touched in over 6 months.
Checks whether each such branch is already fully merged into the main branch (via git merge-base --is-ancestor).
Deletes the branch if it is stale and fully merged.
⚠️ Always test on a non‑critical clone first and review the branches flagged before enabling deletion. If you also want to delete remote branches, do that explicitly (see commented lines).
python
import sys
from datetime import datetime, timedelta, timezone
from git import Repo
from git.exc import GitCommandError, InvalidGitRepositoryError
def find_default_branch(repo):
"""
Return name of default branch (prefers 'main', otherwise 'master'),
or raise if neither exists.
"""
if 'main' in repo.heads:
return 'main'
elif 'master' in repo.heads:
return 'master'
else:
raise ValueError("Could not find 'main' or 'master' in local heads")
def is_branch_merged(repo, branch_name, base_branch):
"""
Returns True if branch_name is fully merged into base_branch,
using 'git merge-base --is-ancestor'.
"""
try:
repo.git.merge_base('--is-ancestor', branch_name, base_branch)
return True
except GitCommandError:
return False
def main(path_to_repo, months=6, dry_run=True):
try:
repo = Repo(path_to_repo)
except InvalidGitRepositoryError:
print(f"Error: '{path_to_repo}' is not a Git repository")
sys.exit(1)
default_branch = find_default_branch(repo)
now = datetime.now(timezone.utc)
cutoff = now - timedelta(days=months * 30) # approximate 30-day months
print(f"Scanning repo: {path_to_repo}")
print(f"Default branch: {default_branch}")
print(f"Cutoff date: {cutoff.isoformat()}")
print(f"Dry run: {dry_run}\n")
for head in repo.heads:
# Skip default branch
if head.name == default_branch:
continue
last_commit_dt = head.commit.committed_datetime
# Only consider stale branches
if last_commit_dt > cutoff:
continue
merged = is_branch_merged(repo, head.name, default_branch)
status = []
if last_commit_dt <= cutoff:
status.append("STALE")
if merged:
status.append("MERGED")
print(f"Branch: {head.name}")
print(f" Last commit: {last_commit_dt.isoformat()}")
print(f" Status: {', '.join(status) if status else 'active'}")
if merged:
if dry_run:
print(f" (dry-run) Would delete {head.name}\n")
else:
try:
repo.delete_head(head, force=True)
print(f" Deleted local branch: {head.name}")
# If you also want to delete the remote branch, uncomment:
# repo.git.push('origin', '--delete', head.name)
# print(f" Deleted remote branch: {head.name}")
except GitCommandError as e:
print(f" Failed to delete {head.name}: {e}\n")
print()
if __name__ == "__main__":
"""
Usage:
python cleanup_branches.py /path/to/repo [months] [--force]
Default: 6 months, dry-run. Add '--force' to actually delete.
"""
if len(sys.argv) < 2:
print("Usage: python cleanup_branches.py /path/to/repo [months] [--force]")
sys.exit(1)
repo_path = sys.argv[1]
months_arg = int(sys.argv[2]) if len(sys.argv) > 2 and sys.argv[2].isdigit() else 6
force_delete = '--force' in sys.argv
main(repo_path, months=months_arg, dry_run=not force_delete)
How it works
Staleness: We approximate 6 months as 6 * 30 days. Adjust as needed or use a more precise calculation (e.g., dateutil.relativedelta).
Merged check: git merge-base --is-ancestor branch main returns success if the branch tip is an ancestor of main (meaning fully merged).
Deletion: By default, the script runs in dry_run mode. Pass --force on the command line to actually delete branches. Local deletion is performed with repo.delete_head(..., force=True). Optionally delete remote branches by pushing a delete ref (--delete).
Notes
Update the default branch discovery if your main branch has a different name.
Consider logging or backing up branch names before deletion.
Test in a safe environment before automating on production repositories.