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.
This is a comprehensive request for a Git automation tool using GitPython. Let me create a robust solution that:
Scans a repository for branches
Identifies stale branches (not touched for 6+ months)
Checks if branches are fully merged into main using git merge-base
Safely deletes branches that meet the criteria
Includes proper error handling, logging, and safety checks
Let me build this solution step by step:
Key components:
Connect to a Git repository
Get all branches
Check the last commit date for each branch
Determine if 6+ months have passed
Use git merge-base to check if fully merged
Provide dry-run mode and confirmation prompts
Generate a report
Handle both local and remote branches
Proper cleanup and safety mechanisms
Here's my implementation:
python
import os
import sys
from datetime import datetime, timedelta
from typing import List, Tuple, Dict, Optional
import logging
from pathlib import Path
import argparse
from git import Repo, GitCommandError, RemoteProgress
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)
class StaleBranchScanner:
"""Scan and manage stale branches in a Git repository."""
def __init__(self, repo_path: str, main_branch: str = 'main',
stale_days: int = 180):
"""
Initialize the scanner.
Args:
repo_path: Path to the Git repository
main_branch: Name of the main branch (default: 'main')
stale_days: Number of days to consider a branch stale (default: 180)
"""
self.repo_path = Path(repo_path)
self.main_branch = main_branch
self.stale_days = stale_days
self.stale_date = datetime.now() - timedelta(days=stale_days)
# Validate repository exists and is a valid Git repo
if not self.repo_path.is_dir():
raise ValueError(f"Repository path does not exist: {repo_path}")
try:
self.repo = Repo(self.repo_path)
except Exception as e:
raise ValueError(f"Invalid Git repository: {repo_path}") from e
logger.info(f"Initialized scanner for {repo_path}")
I'm setting up the scanner with configurable parameters for the main branch name and staleness threshold, then validating that the provided path is a valid Git repository before proceeding. if merge_base[0] == branch_commit:
logger.debug(f"Branch {branch_name} is fully merged")
return True
code
logger.debug(f"Branch {branch_name} is NOT fully merged")
return False
except GitCommandError as e:
logger.error(f"Error checking merge status for {branch_name}: {e}")
return False
def scan_local_branches(self) -> List[Dict]:
"""
Scan local branches for stale, unmerged branches.
Returns:
List of dictionaries containing branch information
"""
stale_branches = []
try:
branches = list(self.repo.heads)
logger.info(f"Found {len(branches)} local branches to analyze")
The merge-base comparison determines if a branch is fully merged by checking whether its commit matches the merge base with main. If they're equal, the branch is an ancestor of main and therefore merged. The scan then iterates through all local branches to identify which ones are stale or unmerged.
For each branch, I skip the main branch itself, retrieve its last commit date, and compare it against the stale threshold. When a branch qualifies as stale, I check its merge status and collect details like how many days it's been inactive and whether it's already been merged into main. This information gets logged and added to the results list.
For remote branches, I first verify the remote exists, then iterate through its references. I extract the branch name by removing the remote prefix, skip the main branch, and retrieve the commit timestamp to determine staleness. The same merge and age calculations apply to build the branch information dictionary. _local_branch(self, branch_name: str, force: bool = False) -> bool:
"""
Delete a local branch.
code
Args:
branch_name: Name of the branch to delete
force: Force delete even if not fully merged
Returns:
True if successful, False otherwise
"""
try:
self.repo.delete_head(branch_name, force=force)
logger.info(f"Deleted local branch: {branch_name}")
return True
except GitCommandError as e:
logger.error(f"Failed to delete local branch {branch_name}: {e}")
return False
def delete_remote_branch(self, remote_name: str, branch_name: str) -> bool:
"""
Delete a remote branch.
Args:
remote_
name: Name of the remote
branch_name: Name of the branch to delete
code
def main():
"""Main CLI interface."""
parser = argparse.ArgumentParser(
description='Scan and cleanup stale Git branches'
)
parser.add_argument(
'repo_path',
help='Path to the Git repository'
)
parser.add_argument(
'--main-branch',
default='main',
help='Name of the main branch (default: main)'
)
parser.add_argument(
'--stale-days',
type=int,
default=180,
help='Number of days to consider a branch stale (default: 180)'
)
parser.add_argument(
'--scan-remote',
action='store_true',
help='Also scan remote branches'
)
parser.add_argument(
'--remote-name',
default='origin',
help='Name of the remote to scan (default: origin)'
)
parser.add_argument(
'--delete',
action='store_true',
help='Delete stale merged branches (requires confirmation)'
)
parser.add_argument(
'--delete-unmerged',
action='store_true',
help='Also delete unmerged stale branches (use with caution!)'
)
parser.add_argument(
'--no-confirm',
action='store_true',
help='Skip confirmation prompt'
)
parser.add_argument(
'--report-only',
action='store_true',
help='Only generate report, do not delete'
)
parser.add_argument(
'-v', '--verbose',
action='store_true',
help='Enable verbose logging'
)
code
args = parser.parse_args()
if args.verbose:
logging.getLogger().setLevel(logging.DEBUG)
try:
scanner = StaleBranchScanner(
args.repo_path,
main_branch=args.main_branch,
stale_days=args.stale_days
)
stale_branches = scanner.scan_local_branches()
if args.scan_remote:
remote_branches = scanner.scan_remote_branches(args.remote_name)
stale_branches.extend(remote_branches)
report = scanner.generate_report(stale_branches)
print(report)
if args.delete and not args.report_only:
scanner.cleanup_branches(
stale_branches,
delete_unmerged=args.delete_unmerged,
interactive=not args.no_confirm
)
return 0
except Exception as e:
logger.error(f"Fatal error: {e}")
return 1
if name == 'main':
sys.exit(main())
code
Setting up the dependencies and test suite:
code
# requirements.txt
GitPython==3.1.37
python
# test_stale_branch_cleaner.py
"""
Unit tests for the stale branch cleaner.
"""
import unittest
import tempfile
import os
from datetime import datetime, timedelta
from pathlib import Path
from git import Repo
from stale_branch_cleaner import StaleBranchScanner
from advanced_branch_cleaner import AdvancedStaleBranchCleaner, BranchStatus
class TestStaleBranchScanner(unittest.TestCase):
"""Test cases for StaleBranchScanner."""
@classmethod
def setUpClass(cls):
"""Set up test repository."""
cls.temp_dir = tempfile.mkdtemp()
cls.repo = Repo.init(cls.temp_dir)
# Configure git user settings
cls.repo.config_writer().set_value("user", "name", "Test User").release()
cls.repo.config_writer().set_value("user", "email", "test@example.com").release()
# Create initial commit on main branch
test_file = Path(cls.temp_dir) / "test.txt"
test_file.write_text("test")
cls.repo.index.add([str(test_file)])
cls.repo.index.commit("Initial commit")
def test_initialization(self):
"""Test scanner initialization."""
scanner = StaleBranchScanner(self.temp_dir)
self.assertEqual(scanner.main_branch, 'main')
self.assertEqual(scanner.stale_days, 180)
def test_invalid_repo_path(self):
"""Test with invalid repository path."""
with self.assertRaises(ValueError):
StaleBranchScanner("/nonexistent/path")
def test_custom_stale_threshold(self):
"""Test custom stale days threshold."""
scanner = StaleBranchScanner(
self.temp_dir,
stale_days=365
)
self.assertEqual(scanner.stale_days, 365)
class TestAdvancedCleaner(unittest.TestCase):
"""Test cases for AdvancedStaleBranchCleaner."""
@classmethod
def setUpClass(cls):
"""Set up test repository."""
cls.temp_dir = tempfile.mkdtemp()
cls.repo = Repo.init(cls.temp_dir)
# Configure git user settings
cls.repo.config_writer().set_value("user", "name", "Test User").release()
cls.repo.config_writer().set_value("user", "email", "test@example.com").release()
# Create initial commit on main branch
test_file = Path(cls.temp_dir) / "test.txt"
test_file.write_text("test")
cls.repo.index.add([str(test_file)])
cls.repo.index.commit("Initial commit")
def test_branch_status_enum(self):
"""Test BranchStatus enum."""
self.assertEqual(BranchStatus.SAFE_DELETE.value, "safe_delete")
self.assertEqual(BranchStatus.NEEDS_REVIEW.value, "needs_review")
if __name__ == '__main__':
unittest.main()
Now creating the comprehensive README documentation:
markdown
# Git Stale Branch Cleaner
Automate Git operations to identify, report, and safely delete stale branches that haven't been touched for a specified period using GitPython.
## Features
- **Automated Scanning**: Find branches untouched for 6+ months (configurable)
- **Merge Detection**: Use git merge-base to safely identify merged vs unmerged branches
- **Risk Assessment**: Distinguish between branches safe to delete and those needing review
- **Detailed Reports**: Generate comprehensive reports with branch metadata
- **Dry Run Mode**: Test cleanup operations without making changes
- **Remote Branch Support**: Scan and manage both local and remote branches
- **Interactive Deletion**: Confirm before deleting branches
- **Export Capabilities**: Save reports in JSON format
- **Extensive Logging**: Track all operations with detailed logging
## Installation
```bash
pip install -r requirements.txt
from advanced_branch_cleaner import AdvancedStaleBranchCleaner
# Initialize
cleaner = AdvancedStaleBranchCleaner(
repo_path='/path/to/repo',
stale_days=180
)
# Scan branches
branches = cleaner.scan_branches(
include_remote=True,
remote_name='origin'
)
# Generate detailed report
print(cleaner.generate_detailed_report(branches))
# Get branch activity info
for branch in branches:
activity = cleaner.get_branch_activity(branch)
print(f"{branch.name}: {activity}")
# Export report
cleaner.export_report(branches, 'report.json')
Then perform the cleanup with options for dry-run mode, selective deletion of unmerged branches, and interactive confirmation prompts.
Examples
Example 1: Find All Stale Branches
python
from stale_branch_cleaner import StaleBranchScanner
scanner = StaleBranchScanner('/path/to/repo')
stale = scanner.scan_local_branches()
for branch in stale:
print(f"{branch['name']}: {branch['days_stale']} days old, "
f"merged: {branch['is_merged']}")
Example 2: Identify Very Old Branches
python
from advanced_branch_cleaner import AdvancedStaleBranchCleaner
cleaner = AdvancedStaleBranchCleaner(
'/path/to/repo',
stale_days=365 # 1 year
)
branches = cleaner.scan_branches()
# Find 2+ year old branches
very_old = [b for b in branches if b.days_stale > 730]
for branch in very_old:
print(f" {branch.name}: {branch.days_stale} days old")
print(f" Author: {branch.last_commit_author}")
print(f" Last: {branch.last_commit_date}")
Example 3: Get Branches by Author
python
branches = cleaner.scan_branches()
# Branches by specific author
author_branches = [
b for b in branches
if 'john.doe' in b.last_commit_author.lower()
]
for branch in author_branches:
print(f" {branch.name}: {branch.days_stale} days")
Example 4: Export and Analyze
python
branches = cleaner.scan_branches(include_remote=True)
# Export for analysis
cleaner.export_report(branches, 'stale_branches.json')
# Analyze
safe = [b for b in branches if b.is_merged]
risky = [b for b in branches if not b.is_merged]
print(f"Safe to delete: {len(safe)}")
print(f"Need review: {len(risky)}")
Safety Features
Merge Detection: Uses git merge-base to verify if branch is fully merged
Dry Run Mode: Always available to preview changes
Interactive Confirmation: Asks for confirmation before deletion
Detailed Logging: Track all operations
Error Handling: Gracefully handle errors without data loss
Backup Report: Export reports before cleanup
Safe Defaults: Default to dry-run, requires explicit flag to delete
Best Practices
Always Run Dry Run First
bash
# Preview what will be deleted
python stale_branch_cleaner.py /repo --delete --dry-run --verbose
# batch_cleanup.py
"""
Batch cleanup utility for multiple repositories.
"""
import yaml
import logging
from pathlib import Path
from datetime import datetime
from typing import List, Dict
from stale_branch_cleaner import StaleBranchScanner
logger = logging.getLogger(__name__)
class BatchBranchCleaner:
"""Manage stale branches across multiple repositories."""
def __init__(self, config_file: str):
"""Initialize with config file."""
self.config_file = Path(config_file)
self.config = self._load_config()
self.results = []
def _load_config(self) -> Dict:
"""Load configuration from YAML file."""
with open(self.config_file) as f:
return yaml.safe_load(f)
For each repository in the config, I scan local and remote branches based on the settings, collecting stale branch data. The scanner creates a result dictionary with counts of safe-to-delete versus risky branches, then exports to JSON if configured. After processing all repositories, I generate a summary showing total stale branches found, how many are safe to delete versus need review, and per-repository breakdowns.
Git Stale Branch Cleaner - Complete Automation Solution
I'll create a comprehensive Git automation tool using GitPython to identify and safely delete stale branches not merged into main.
✅ Safe branch detection using git merge-base
✅ Detailed reporting with commit metrics
✅ Dry-run mode for preview
✅ Interactive confirmation for safety
✅ Batch processing across multiple repos
✅ JSON export for analysis
✅ Extensive logging for audit trails
✅ Unit tests for reliability
✅ Error handling and validation
Returns:
True if successful, False otherwise
"""
try:
remote = self.repo.remote(remote_name)
remote.push(refspec=(f":{branch_name}",))
logger.info(f"Deleted remote branch: {remote_name}/{branch_name}")
return True
except GitCommandError as e:
logger.error(
f"Failed to delete remote branch {remote_name}/{branch_name}: {e}"
)
return False
def generate_report(self, branches: List[Dict]) -> str:
"""
Generate a formatted report of stale branches.
Args:
branches: List of branch information dictionaries
Returns:
Formatted report string
"""
if not branches:
return "No stale branches found."
report = f"\n{'='*80}\n"
report += f"STALE BRANCHES REPORT (not touched for {self.stale_days} days)\n"
report += f"{'='*80}\n\n"
# Separate branches by merge status
merged = [b for b in branches if b['is_merged']]
unmerged = [b for b in branches if not b['is_merged']]
# Display merged branches as safe candidates for deletion
if merged:
report += f"SAFE TO DELETE ({len(merged)} branches - already merged):\n"
report += f"{'-'*80}\n"
for branch in sorted(merged, key=lambda x: x['last_commit_date']):
report += (
f" Name: {branch['name']}\n"
f" Type: {branch['branch_type']}\n"
f" Last commit: {branch['last_commit_date'].date()}\n"
f" Days stale: {branch['days_stale']}\n"
f" Merged: Yes\n\n"
)
# Display unmerged branches as risky to delete
if unmerged:
report += f"\nREQ UIRE REVIEW ({len(unmerged)} branches - NOT merged):\n"
report += f"{'-'*80}\n"
for branch in sorted(unmerged, key=lambda x: x['last_commit_date']):
report += (
f" Name: {branch['name']}\n"
f" Type: {branch['branch_type']}\n"
f" Last commit: {branch['last_commit_date'].date()}\n"
f" Days stale: {branch['days_stale']}\n"
f" Merged: No\n\n"
)
report += f"{'='*80}\n"
report += f"Summary: {len(merged)} safe, {len(unmerged)} risky\n"
report += f"{'='*80}\n"
return report
def cleanup_stale_branches(self, branches: List[Dict],
dry_run: bool = True,
delete_unmerged: bool = False,
interactive: bool = True) -> Dict[str, int]:
"""
Delete stale branches that are safe to delete.
Args:
branches: List of branch information dictionaries
dry_run: If True, don't actually delete (default: True)
delete_unmerged: If True, also delete unmerged branches (default: False)
interactive: If True, ask for confirmation (default: True)
Returns:
Statistics dictionary
"""
stats = {
'total': len(branches),
'deleted_local': 0,
'deleted_remote': 0,
'failed': 0,
'skipped': 0
}
if not branches:
logger.info("No branches to cleanup")
return stats
# Filter branches to delete
branches_to_delete = []
for branch in branches:
if branch['is_merged'] or delete_unmerged:
branches_to_delete.append(branch)
else:
stats['skipped'] += 1
logger.info(f"Skipping unmerged branch: {branch['name']}")
if not branches_to_delete:
logger.info("No branches safe to delete")
return stats
logger.info(f"Found {len(branches_to_delete)} branches to delete")
if dry_run:
logger.info("DRY RUN: Would delete the following branches:")
for branch in branches_to_delete:
logger.info(f" - {branch['full_ref']}")
stats['skipped'] += len(branches_to_delete)
return stats
if interactive:
logger.info("\nBranches to be deleted:")
for i, branch in enumerate(branches_to_delete, 1):
logger.info(f" {i}. {branch['full_ref']}")
response = input(
f"\nDelete {len(branches_to_delete)} branches? (yes/no): "
).lower().strip()
if response != 'yes':
logger.info("Deletion cancelled")
stats['skipped'] += len(branches_to_delete)
return stats
for branch in branches_to_delete:
try:
if branch['branch_type'] == 'local':
if self.delete_local_branch(branch['name'], force=False):
stats['deleted_local'] += 1
else:
stats['failed'] += 1
else:
remote_name = branch['full_ref'].split('/')[0]
branch_name = branch['name']
if self.delete_remote_branch(remote_name, branch_name):
stats['deleted_remote'] += 1
else:
stats['failed'] += 1
except Exception as e:
logger.error(f"Unexpected error deleting {branch['name']}: {e}")
stats['failed'] += 1
return stats
The script now handles the cleanup phase by calling the cleanup method with the appropriate flags for unmerged branches and confirmation prompts. It collects and logs statistics about deleted branches, skipped items, and any failures that occurred during the process. aner for {repo_path}")
def get_branch_info(self, branch_ref, branch_type: str) -> Optional[BranchInfo]:
"""Get detailed information about a branch."""
try:
commit = branch_ref.commit
timestamp = commit.committed_date
last_commit_date = datetime.fromtimestamp(timestamp)
# Get branch name
if isinstance(branch_ref, str):
branch_name = branch_ref.split('/')[-1]
full_ref = branch_ref
else:
branch_name = branch_ref.name
full_ref = branch_ref.name
last_commit_author = commit.author.name if commit.author else "Unknown"
last_commit_message = commit.message.split('\n')[0]
is
I cannot complete this thought as the next thinking appears to be cut off mid-sentence. To properly rewrite this section, I would need to see where the `is` variable assignment concludes and what follows in the method logic. is_stale = last_commit_date < self.stale_date
if not is_stale:
return None
is_merged = self._check_merged(full_ref)
# Determine status
if is_merged:
status = BranchStatus.SAFE_DELETE
else:
status = BranchStatus.NEEDS_REVIEW
return BranchInfo(
name=branch_name,
branch_type=branch_type,
full_ref=full_ref,
last_commit_date=last_commit_date,
last_commit_author=last_commit_author,
last_commit_message=last_commit_message,
is_merged=is_merged,
days_stale=(datetime.now() - last_commit_date).days,
status=status
)
except Exception as e:
logger.warning(f"Error getting info for branch: {e}")
return None
def _check_merged(self, branch_ref: str) -> bool:
"""Check if branch is merged into main."""
try:
merge_base = self.repo.merge_base(self.main_branch, branch_ref)
branch_commit = self.repo.commit(branch_ref)
return merge_base[0] == branch_commit
except GitCommandError:
return False
def scan_branches(self, include_remote: bool = False, remote_name: str = 'origin') -> List[BranchInfo]:
"""Scan local and optionally remote branches."""
branches = []
# Scan local branches
try:
for branch in self.repo.heads:
if branch.name == self.main_branch:
continue
info = self.get_branch_info(branch, 'local')
if info:
branches.append(info)
logger.debug(f"Found stale local branch: {info.name}")
except Exception as e:
logger.error(f"Error scanning local branches: {e}")
# Scan remote branches if requested
if include_remote:
try:
if remote_name not in [r.name for r in self.repo.remotes]:
logger.warning(f"Remote '{remote_name}' not found")
else:
remote_refs = self.repo.remotes[remote_name].refs
for ref in remote_refs:
remote_branch_name = str(ref).replace(f"{remote_name}/", "")
if remote_branch_name == self.main_branch:
continue
info = self.get_branch_info(str(ref), 'remote')
if info:
branches.append(info)
logger.debug(f"Found stale remote branch: {info.name}")
except Exception as e:
logger.error(f"Error scanning remote branches: {e}")
return branches
When scanning remote branches, I check if the specified remote exists and log a warning if it doesn't. For each remote reference, I extract the branch name, skip the main branch, and collect stale branches with their metadata. The method returns all identified stale branches from both local and remote sources.
For activity analysis, I calculate commit count, files changed, and track the last author. I get the unique commits on each branch compared to main, then count the files modified across those commits. If any step fails, I default to zero values rather than crashing.
Now I'm building the detailed report by categorizing branches into safe-to-delete and needs-review groups based on their merge status. The report includes a header with the scan timestamp and stale threshold, then lists each category with activity metrics for the branches sorted by staleness. The report concludes with a summary line showing total branch count alongside safe and risky counts, then returns the formatted report string. The cleanup method then iterates through branches to identify candidates for deletion based on their status—adding safe-to-delete branches to a removal list, and optionally including unmerged branches if that flag is enabled. If no branches qualify for deletion, it logs this and returns early with counts. The method continues with interactive or dry-run logic to handle the actual deletion process. After attempting deletion, I track successful removals and catch any errors that occur, logging them and recording failed attempts. Once all branches have been processed, I return a summary with the count of deleted branches, failures, and those that were skipped.
For the export functionality, I serialize the branch data to JSON format with metadata like the timestamp, main branch name, and stale threshold, then write it to the specified output file. If the export fails, I log the error appropriately.
The main entry point sets up command-line argument parsing to accept the repository path, optional main branch name, staleness threshold in days, and a flag for scanning remote branches.
help='Scan remote branches')
parser.add_argument('--remote-name', default='origin',
help='Remote name to scan')
parser.add_argument('--delete', action='store_true',
help='Delete stale branches')
parser.add_argument('--delete-unmerged', action='store_true',
help='Also delete unmerged branches')
parser.add_argument('--dry-run', action='store_true', default=True,
help='Perform dry run (default)')
parser.add_argument('--no-dry-run', action='store_true',
help='Actually delete branches')
parser.add_argument('--no-confirm', action='store_true',
help='Skip confirmation')
parser.add_argument('--export', type=str, help='Export report to JSON file')
parser.add_argument('-v', '--verbose', action='store_true',
help='Verbose output')
args = parser.parse_args()
# Configure logging
logging.basicConfig(
level=
logging.DEBUG if args.verbose else logging.INFO,
format='%(levelname)s: %(message)s'
)
try:
cleaner = AdvancedStaleBranchCleaner(
args.repo_path,
main_branch=args.main_branch,
stale_days=args.stale_days
)
branches = cleaner.scan_branches(
include_remote=args.scan_remote,
remote_name=args.remote_name
)
print(cleaner.generate_detailed_report(branches))
if args.export:
cleaner.export_report(branches, args.export)
if args.delete:
dry_run = not args.no_dry_run
stats = cleaner.cleanup(
branches,
dry_run=dry_run,
delete_unmerged=args.delete_unmerged,
interactive=not args.no_confirm
)
logger.info(f"\nDeleted: {stats['deleted']}, Failed: {stats['failed']}")
I set up logging based on the verbose flag, then initialize the cleaner with the repository path and stale branch parameters. I scan for branches across local and remote sources if requested, generate and display a report, optionally export it to JSON, and finally perform cleanup operations if the delete flag is set, respecting the dry-run mode and confirmation preferences.
If an exception occurs during execution, I log the error and print a traceback when verbose mode is enabled before returning a failure code. The script entry point calls main() and exits with the appropriate status code.
Then I'm setting up comprehensive examples demonstrating different usage patterns. The first shows basic local branch scanning with a stale threshold of 180 days. The second combines local and remote branch scanning to get a complete picture. The third demonstrates a dry-run cleanup with interactive prompts, checking statistics on how many branches would be affected without actually deleting anything. eBranchCleaner(
repo_path='/path/to/repo',
stale_days=180
)
# Scan with remote branches
branches = cleaner.scan_branches(
include_remote=True,
remote_name='origin'
)
# Generate detailed report
print(cleaner.generate_detailed_report(branches))
# Export to JSON
cleaner.export_report(branches, 'stale_branches_report.json')
def example_programmatic_analysis():
"""Programmatic analysis example."""
print("\n" + "="*80)
print("EXAMPLE 6: Programmatic Analysis")
print("="*80 + "\n")
cleaner = AdvancedStaleBranchCleaner('/path/to/repo')
branches = cleaner.scan_branches(include_remote=False)
# Categorize branches by merge status
safe_branches = [b for b in branches if b.is_merged]
risky_branches = [b for b in branches if not b.is_merged]
# Display summary statistics
print(f"Total stale branches: {len(branches)}")
print(f"Safe to delete: {len(safe_branches)}")
print(f"Need review: {len(risky_branches)}")
# Show the most stale branches ranked by age
print("\nMost stale branches:")
for branch in sorted(branches, key=lambda x: x.days_stale, reverse=True)[:5]:
print(f" - {branch.name}: {branch.days_stale} days "
f"({'merged' if branch.is_merged else 'NOT merged'})")
def example_filtering():
"""Example with custom filtering."""
print("\n" + "="*80)
print("EXAMPLE 7: Custom Filtering")
print("="*80 + "\n")
cleaner = AdvancedStaleBranchCleaner('/path/to/repo',
stale_days=365)
branches = cleaner.scan_branches()
# Find branches by a specific author
author_name = 'john.doe'
branches_by_author = [
b for b in branches
if b.last_commit_author and author_name in b.last_commit_author.lower()
]
print(f"Stale branches by {author_name}:")
for branch in branches_by_author:
print(f" - {branch.name}: {branch.days_stale} days old")
# Identify branches older than two years
very_old = [b for b in branches if b.days_stale > 730]
print(f"\nVery old branches (>2 years): {len(very_old)}")
for branch in very_old:
print(f" - {branch.name}")
# stale_branch_cleaner.py
"""
Complete Git stale branch cleanup automation tool.
"""
import os
import sys
import json
from datetime import datetime, timedelta
from typing import List, Dict, Optional, Tuple
import logging
from pathlib import Path
import argparse
from dataclasses import dataclass, asdict
from enum import Enum
from git import Repo, GitCommandError
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)
class BranchStatus(Enum):
"""Status of a branch."""
SAFE_DELETE = "safe_delete"
NEEDS_REVIEW = "needs_review"
SKIP = "skip"
@dataclass
class BranchInfo:
"""Information about a branch."""
name: str
branch_type: str # 'local' or 'remote'
full_ref: str
last_commit_date: datetime
last_commit_author: Optional[str]
last_commit_message: str
is_merged: bool
days_stale: int
status: BranchStatus
commit_count: int = 0
files_changed: int = 0
def to_dict(self) -> Dict:
"""Convert to dictionary."""
data = asdict(self)
data['status'] = self.status.value
data['last_commit_date'] = self.last_commit_date.isoformat()
return data
class StaleBranchCleaner:
"""Scan and manage stale branches in a Git repository."""
def __init__(self, repo_path: str, main_branch: str = 'main',
stale_days: int = 180):
"""
Initialize the cleaner.
Args:
repo_path: Path to the Git repository
main_branch: Name of the main branch (default: 'main')
stale_days: Number of days to consider a branch stale (default: 180)
"""
self.repo_path = Path(repo_path)
self.main_branch = main_branch
self.stale_days = stale_days
self.stale_date = datetime.now() - timedelta(days=stale_days)
# Validate repository
if not self.repo_path.is_dir():
raise ValueError(f"Repository path does not exist: {repo_path}")
try:
self.repo = Repo(self.repo_path)
except Exception as e:
raise ValueError(f"Invalid Git repository: {repo_path}") from e
# Verify main branch exists
if not self._branch_exists(main_branch):
raise ValueError(f"Main branch '{main_branch}' does not exist")
logger.info(f"Initialized cleaner for {repo_path}")
logger.info(f"Main branch: {main_branch}, Stale threshold: {stale_days} days")
def _branch_exists(self, branch_name: str) -> bool:
"""Check if a branch exists."""
try:
self.repo.commit(branch_name)
return True
except Exception:
return False
def _check_merged(self, branch_ref: str) -> bool:
"""
Check if branch is fully merged into main using merge-base.
Args:
branch_ref: Reference to the branch to check
Returns:
True if branch is merged, False otherwise
"""
try:
# Get merge base
merge_base = self.repo.merge_base(self.main_branch, branch_ref)
# Get branch tip commit
branch_commit = self.repo.commit(branch_ref)
# If merge base equals branch commit, the branch is fully merged
is_merged = merge_base[0] == branch_commit
logger.debug(f"Branch {branch_ref}: merged={is_merged}")
return is_merged
except GitCommandError as e:
logger.error(f"Error checking merge status for {branch_ref}: {e}")
return False
def _get_branch_info(self, branch_ref, branch_type: str) -> Optional[BranchInfo]:
"""Get detailed information about a branch."""
try:
# Get commit info
commit = branch_ref.commit
timestamp = commit.committed_date
last_commit_date = datetime.fromtimestamp(timestamp)
# Check if stale
if last_commit_date >= self.stale_date:
return None
# Extract branch name
if isinstance(branch_ref, str):
branch_name = branch_ref.split('/')[-1]
full_ref = branch_ref
else:
branch_name = branch_ref.name
full_ref = branch_ref.name
# Get commit metadata
last_commit_author = commit.author.name if commit.author else "Unknown"
last_commit_message = commit.message.split('\n')[0][:80]
# Check merge status
is_merged = self._check_merged(full_ref)
# Determine status
status = BranchStatus.SAFE_DELETE if is_merged else BranchStatus.NEEDS_REVIEW
# Calculate days stale
days_stale = (datetime.now() - last_commit_date).days
return BranchInfo(
name=branch_name,
branch_type=branch_type,
full_ref=full_ref,
last_commit_date=last_commit_date,
last_commit_author=last_commit_author,
last_commit_message=last_commit_message,
is_merged=is_merged,
days_stale=days_stale,
status=status
)
except Exception as e:
logger.warning(f"Error getting info for branch: {e}")
return None
def _get_activity_metrics(self, branch_info: BranchInfo) -> Tuple[int, int]:
"""Get commit count and files changed for branch."""
try:
branch_ref = branch_info.full_ref
# Count commits unique to this branch
try:
main_commits = set(
self.repo.git.rev_list(self.main_branch).split('\n')
)
branch_commits = set(
self.repo.git.rev_list(branch_ref).split('\n')
)
unique_commits = list(branch_commits - main_commits)
commit_count = len(unique_commits)
# Count files changed
files_changed = 0
for commit_sha in unique_commits[:100]: # Limit for performance
try:
commit = self.repo.commit(commit_sha)
files_changed += len(commit.stats.files)
except:
pass
except:
commit_count = 0
files_changed = 0
return commit_count, files_changed
except Exception as e:
logger.debug(f"Error getting activity metrics: {e}")
return 0, 0
def scan_local_branches(self) -> List[BranchInfo]:
"""Scan local branches for stale, unmerged branches."""
stale_branches = []
try:
all_branches = list(self.repo.heads)
logger.info(f"Found {len(all_branches)} local branches")
for branch in all_branches:
# Skip main branch
if branch.name == self.main_branch:
logger.debug(f"Skipping main branch: {branch.name}")
continue
info = self._get_branch_info(branch, 'local')
if info:
# Get activity metrics
commit_count, files_changed = self._get_activity_metrics(info)
info.commit_count = commit_count
info.files_changed = files_changed
stale_branches.append(info)
logger.info(
f"Found stale branch: {branch.name} "
f"({info.days_stale}d old, merged={info.is_merged})"
)
return stale_branches
except Exception as e:
logger.error(f"Error scanning local branches: {e}")
return []
def scan_remote_branches(self, remote_name: str = 'origin') -> List[BranchInfo]:
"""Scan remote branches for stale, unmerged branches."""
stale_branches = []
try:
# Check if remote exists
if remote_name not in [r.name for r in self.repo.remotes]:
logger.warning(f"Remote '{remote_name}' not found")
return []
remote_refs = list(self.repo.remotes[remote_name].refs)
logger.info(f"Found {len(remote_refs)} remote branches on {remote_name}")
for ref in remote_refs:
full_name = str(ref)
branch_name = full_name.replace(f"{remote_name}/", "")
# Skip main branch
if branch_name == self.main_branch:
continue
try:
info = self._get_branch_info(full_name, 'remote')
if info:
commit_count, files_changed = self._get_activity_metrics(info)
info.commit_count = commit_count
info.files_changed = files_changed
stale_branches.append(info)
logger.info(
f"Found stale remote branch: {branch_name} "
f"({info.days_stale}d old, merged={info.is_merged})"
)
except Exception as e:
logger.warning(f"Error processing remote branch {full_name}: {e}")
continue
return stale_branches
except Exception as e:
logger.error(f"Error scanning remote branches: {e}")
return []
def generate_report(self, branches: List[BranchInfo]) -> str:
"""Generate a formatted report of stale branches."""
if not branches:
return f"\n✓ No stale branches found (threshold: {self.stale_days} days)\n"
safe = [b for b in branches if b.status == BranchStatus.SAFE_DELETE]
risky = [b for b in branches if b.status == BranchStatus.NEEDS_REVIEW]
report = "\n" + "="*100 + "\n"
report += f"STALE BRANCHES REPORT\n"
report += f"Repository: {self.repo_path.name}\n"
report += f"Scanned: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n"
report += f"Threshold: {self.stale_days} days\n"
report += "="*100 + "\n\n"
# Safe to delete
if safe:
report += f"✓ SAFE TO DELETE ({len(safe)} branches - already merged):\n"
report += "-"*100 + "\n"
for branch in sorted(safe, key=lambda x: x.days_stale, reverse=True):
report += (
f" {branch.name:40} | "
f"{branch.days_stale:4}d old | "
f"{branch.last_commit_author:20} | "
f"commits:{branch.commit_count:3} | "
f"files:{branch.files_changed:3}\n"
)
# Need review
if risky:
report += f"\n⚠ REVIEW REQUIRED ({len(risky)} branches - NOT merged):\n"
report += "-"*100 + "\n"
for branch in sorted(risky, key=lambda x: x.days_stale, reverse=True):
report += (
f" {branch.name:40} | "
f"{branch.days_stale:4}d old | "
f"{branch.last_commit_author:20} | "
f"commits:{branch.commit_count:3} | "
f"files:{branch.files_changed:3}\n"
)
report += "\n" + "="*100 + "\n"
report += f"SUMMARY: {len(branches)} total | "
report += f"{len(safe)} safe | {len(risky)} review\n"
report += "="*100 + "\n"
return report
def delete_local_branch(self, branch_name: str, force: bool = False) -> bool:
"""Delete a local branch."""
try:
self.repo.delete_head(branch_name, force=force)
logger.info(f"✓ Deleted local branch: {branch_name}")
return True
except GitCommandError as e:
logger.error(f"✗ Failed to delete local branch {branch_name}: {e}")
return False
def delete_remote_branch(self, remote_name: str, branch_name: str) -> bool:
"""Delete a remote branch."""
try:
remote = self.repo.remote(remote_name)
remote.push(refspec=(f":{branch_name}",))
logger.info(f"✓ Deleted remote branch: {remote_name}/{branch_name}")
return True
except GitCommandError as e:
logger.error(
f"✗ Failed to delete remote branch {remote_name}/{branch_name}: {e}"
)
return False
def cleanup(self, branches: List[BranchInfo], dry_run: bool = True,
delete_unmerged: bool = False, interactive: bool = True,
safe_only: bool = True) -> Dict[str, int]:
"""
Delete stale branches.
Args:
branches: List of branch information
dry_run: If True, don't actually delete
delete_unmerged: If True, also delete unmerged branches
interactive: If True, ask for confirmation
safe_only: If True, only delete merged branches
Returns:
Statistics dictionary
"""
# Filter branches to delete
branches_to_delete = []
for branch in branches:
if branch.status == BranchStatus.SAFE_DELETE:
branches_to_delete.append(branch)
elif delete_unmerged and branch.status == BranchStatus.NEEDS_REVIEW:
branches_to_delete.append(branch)
stats = {
'total': len(branches),
'to_delete': len(branches_to_delete),
'deleted_local': 0,
'deleted_remote': 0,
'failed': 0,
'skipped': len(branches) - len(branches_to_delete)
}
if not branches_to_delete:
logger.info("No branches to delete")
return stats
logger.info(f"Found {len(branches_to_delete)} branches to delete")
if dry_run:
logger.info("DRY RUN MODE - No actual deletions will occur:")
for branch in branches_to_delete:
status = "SAFE" if branch.status == BranchStatus.SAFE_DELETE else "RISKY"
logger.info(f" [{status}] {branch.full_ref}")
return stats
# Ask for confirmation if interactive
if interactive:
print("\nBranches to be deleted:")
for i, branch in enumerate(branches_to_delete, 1):
status = "✓" if branch.status == BranchStatus.SAFE_DELETE else "⚠"
print(f" {i}. [{status}] {branch.full_ref} ({branch.days_stale}d old)")
response = input(
f"\nProceed with deletion of {len(branches_to_delete)} branches? "
f"(yes/no): "
).lower().strip()
if response != 'yes':
logger.info("Deletion cancelled by user")
stats['skipped'] += len(branches_to_delete)
return stats
# Delete branches
logger.info("\nDeleting branches...")
for branch in branches_to_delete:
try:
if branch.branch_type == 'local':
if self.delete_local_branch(branch.name, force=False):
stats['deleted_local'] += 1
else:
stats['failed'] += 1
else: # remote
remote_name = branch.full_ref.split('/')[0]
branch_name = branch.name
if self.delete_remote_branch(remote_name, branch_name):
stats['deleted_remote'] += 1
else:
stats['failed'] += 1
except Exception as e:
logger.error(f"Unexpected error deleting {branch.name}: {e}")
stats['failed'] += 1
return stats
def export_report(self, branches: List[BranchInfo], output_file: str):
"""Export branches to JSON file."""
try:
output_path = Path(output_file)
output_path.parent.mkdir(parents=True, exist_ok=True)
data = {
'timestamp': datetime.now().isoformat(),
'repository': str(self.repo_path),
'main_branch': self.main_branch,
'stale_days_threshold': self.stale_days,
'branches': [b.to_dict() for b in branches],
'summary': {
'total': len(branches),
'safe_delete': len([b for b in branches if b.status == BranchStatus.SAFE_DELETE]),
'needs_review': len([b for b in branches if b.status == BranchStatus.NEEDS_REVIEW])
}
}
with open(output_path, 'w') as f:
json.dump(data, f, indent=2, default=str)
logger.info(f"✓ Report exported to {output_file}")
return True
except Exception as e:
logger.error(f"✗ Failed to export report: {e}")
return False
def main():
"""Main CLI interface."""
parser = argparse.ArgumentParser(
description='Identify and safely clean stale Git branches',
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Examples:
# Scan only (no deletion)
%(prog)s /path/to/repo
# Dry run preview
%(prog)s /path/to/repo --delete --dry-run
# Actually delete with confirmation
%(prog)s /path/to/repo --delete --no-dry-run
# Include remote branches
%(prog)s /path/to/repo --scan-remote --export report.json
"""
)
parser.add_argument('repo_path', help='Path to Git repository')
parser.add_argument('--main-branch', default='main',
help='Main branch name (default: main)')
parser.add_argument('--stale-days', type=int, default=180,
help='Days to consider a branch stale (default: 180)')
parser.add_argument('--scan-remote', action='store_true',
help='Also scan remote branches')
parser.add_argument('--remote-name', default='origin',
help='Remote name to scan (default: origin)')
parser.add_argument('--delete', action='store_true',
help='Enable deletion mode')
parser.add_argument('--delete-unmerged', action='store_true',
help='Also delete unmerged branches (use with caution!)')
parser.add_argument('--dry-run', action='store_true', default=False,
help='Preview deletions without making changes')
parser.add_argument('--no-dry-run', dest='dry_run', action='store_false',
help='Actually perform deletions')
parser.add_argument('--no-confirm', action='store_true',
help='Skip confirmation prompt')
parser.add_argument('--export', type=str, help='Export report to JSON file')
parser.add_argument('-v', '--verbose', action='store_true',
help='Verbose logging')
args = parser.parse_args()
# Set logging level
if args.verbose:
logging.getLogger().setLevel(logging.DEBUG)
try:
# Initialize cleaner
cleaner = StaleBranchCleaner(
args.repo_path,
main_branch=args.main_branch,
stale_days=args.stale_days
)
# Scan branches
branches = cleaner.scan_local_branches()
if args.scan_remote:
remote_branches = cleaner.scan_remote_branches(args.remote_name)
branches.extend(remote_branches)
# Display report
print(cleaner.generate_report(branches))
# Export if requested
if args.export:
cleaner.export_report(branches, args.export)
# Cleanup if requested
if args.delete:
logger.info("\n" + "="*100)
logger.info("CLEANUP PHASE")
logger.info("="*100 + "\n")
stats = cleaner.cleanup(
branches,
dry_run=args.dry_run,
delete_unmerged=args.delete_unmerged,
interactive=not args.no_confirm
)
# Print statistics
print(f"\n{'='*100}")
print("CLEANUP RESULTS")
print(f"{'='*100}")
print(f"Total branches scanned: {stats['total']}")
print(f"Local branches deleted: {stats['deleted_local']}")
print(f"Remote branches deleted: {stats['deleted_remote']}")
print(f"Failed deletions: {stats['failed']}")
print(f"Branches skipped: {stats['skipped']}")
print(f"{'='*100}\n")
return 0
except Exception as e:
logger.error(f"Fatal error: {e}")
if args.verbose:
import traceback
traceback.print_exc()
return 1
if __name__ == '__main__':
sys.exit(main())
# batch_cleanup.py
"""
Batch cleanup for multiple repositories.
"""
import yaml
import json
from pathlib import Path
from datetime import datetime
from typing import List, Dict
import logging
from stale_branch_cleaner import StaleBranchCleaner
logger = logging.getLogger(__name__)
class BatchBranchCleaner:
"""Manage stale branches across multiple repositories."""
def __init__(self, config_file: str):
"""Initialize with config file."""
self.config_file = Path(config_file)
self.config = self._load_config()
self.results = []
def _load_config(self) -> Dict:
"""Load configuration from YAML."""
try:
with open(self.config_file, 'r') as f:
return yaml.safe_load(f)
except Exception as e:
logger.error(f"Failed to load config: {e}")
raise
def scan_all_repositories(self) -> List[Dict]:
"""Scan all configured repositories."""
results = []
repos = self.config.get('repositories', [])
logger.info(f"Scanning {len(repos)} repositories")
for repo_config in repos:
result = self._scan_repository(repo_config)
results.append(result)
self.results.append(result)
return results
def _scan_repository(self, repo_config: Dict) -> Dict:
"""Scan a single repository."""
repo_name = repo_config.get('name', 'unknown')
repo_path = repo_config.get('path')
main_branch = repo_config.get('main_branch', 'main')
stale_days = repo_config.get('stale_days', 180)
logger.info(f"\n{'='*80}")
logger.info(f"Repository: {repo_name}")
logger.info(f"Path: {repo_path}")
try:
cleaner = StaleBranchCleaner(
repo_path,
main_branch=main_branch,
stale_days=stale_days
)
# Scan branches
local_branches = cleaner.scan_local_branches()
remote_branches = []
if repo_config.get('scan_remote', False):
for remote_name in repo_config.get('remote_names', ['origin']):
remote_branches.extend(
cleaner.scan_remote_branches(remote_name)
)
all_branches = local_branches + remote_branches
safe = [b for b in all_branches if b.is_merged]
risky = [b for b in all_branches if not b.is_merged]
result = {
'repository': repo_name,
'path': repo_path,
'success': True,
'total_stale': len(all_branches),
'safe_delete': len(safe),
'needs_review': len(risky),
'timestamp': datetime.now().isoformat()
}
logger.info(f"✓ Found {len(all_branches)} stale branches")
logger.info(f" Safe: {len(safe)} | Need review: {len(risky)}")
# Export if configured
if repo_config.get('export_individual', False):
self._export_repo_result(repo_name, all_branches)
return result
except Exception as e:
logger.error(f"✗ Failed to scan {repo_name}: {e}")
return {
'repository': repo_name,
'success': False,
'error': str(e),
'timestamp': datetime.now().isoformat()
}
def _export_repo_result(self, repo_name: str, branches: List):
"""Export individual repository results."""
try:
export_dir = Path(self.config['export_path'])
export_dir.mkdir(parents=True, exist_ok=True)
export_file = export_dir / f"{repo_name}_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json"
with open(export_file, 'w') as f:
json.dump(
[b.to_dict() for b in branches],
f, indent=2, default=str
)
logger.info(f" Exported to {export_file}")
except Exception as e:
logger.warning(f"Failed to export results: {e}")
def generate_summary(self) -> str:
"""Generate summary report."""
if not self.results:
return "No scan results available"
summary = "\n" + "="*100 + "\n"
summary += "BATCH SCAN SUMMARY\n"
summary += "="*100 + "\n\n"
successful = [r for r in self.results if r.get('success', False)]
failed = len(self.results) - len(successful)
total_stale = sum(r.get('total_stale', 0) for r in successful)
total_safe = sum(r.get('safe_delete', 0) for r in successful)
total_risky = sum(r.get('needs_review', 0) for r in successful)
summary += f"Repositories: {len(self.results)} total, {len(successful)} successful, {failed} failed\n\n"
summary += f"Total stale branches: {total_stale}\n"
summary += f" Safe to delete: {total_safe}\n"
summary += f" Need review: {total_risky}\n\n"
summary += "Breakdown by repository:\n"
summary += "-"*100 + "\n"
for result in self.results:
if result.get('success', False):
summary += (
f" {result['repository']:30} | "
f"Total: {result['total_stale']:3} | "
f"Safe: {result['safe_delete']:3} | "
f"Review: {result['needs_review']:3}\n"
)
else:
summary += f" {result['repository']:30} | FAILED: {result.get('error')}\n"
summary += "="*100 + "\n\n"
return summary
if __name__ == '__main__':
import sys
import argparse
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s'
)
parser = argparse.ArgumentParser(
description='Batch scan stale branches across multiple repositories'
)
parser.add_argument('config_file', help='Config YAML file')
parser.add_argument('-v', '--verbose', action='store_true')
args = parser.parse_args()
if args.verbose:
logging.getLogger().setLevel(logging.DEBUG)
try:
cleaner = BatchBranchCleaner(args.config_file)
cleaner.scan_all_repositories()
print(cleaner.generate_summary())
except Exception as e:
logger.error(f"Fatal error: {e}")
sys.exit(1)