Skip to main content
command

branch-cleanup — Claude Code command: clean up git branches

A Claude slash command that finds merged and stale branches, checks them before deletion, and tidies up both local and remote refs.

Install into Claude Code · claude-code-templates All methods and platforms ↓
npx claude-code-templates@latest --command git-workflow/branch-cleanup
Open on GitHub

What branch-cleanup does

The command reads the repository state first: every branch, the ten most recently committed, remote branches, branches already merged into main or master, and the current branch. It then sorts them into categories — safe to delete, needs review, keep. Protected names include main, master, develop, staging, production, release/* branches and whatever branch you are on.

Modes come from the argument. Run it bare and you get the analysis plus a confirmation prompt before each deletion. --dry-run prints what would go and changes nothing. --force deletes merged branches without asking, and there is no undo. --remote-only and --local-only keep the work on one side. Before deleting anything the command verifies the merge with git merge-base and checks for unpushed commits.

Remote refs get pruned with git remote prune origin. If the GitHub CLI is installed, the command checks pull request status before removing a branch, which is what keeps you from killing a branch someone still has open. The report lists SHA hashes for the tips of deleted branches and reflog recovery commands, so a wrong deletion can be walked back by hand.

What it helps with

  • delete local branches already merged into main
  • drop stale remote-tracking refs after branches disappear on the server
  • preview the cleanup without touching the repository
  • spot branches with no activity for over 30 days
  • sort feature/, hotfix/ and release/ branches and check their upstream tracking

Example prompts for the agent

  • /branch-cleanup --dry-run
  • /branch-cleanup --remote-only
  • /branch-cleanup --force

How to install branch-cleanup

1claude-code-templates

npx claude-code-templates@latest --command git-workflow/branch-cleanup

2Manually: put the files in place

.claude/commands/branch-cleanup.md

Call it with /branch-cleanup. For all projects use ~/.claude/commands/

Questions about branch-cleanup

How do I install branch-cleanup in Claude?

Run npx claude-code-templates@latest --command git-workflow/branch-cleanup. It drops the command at .claude/commands/branch-cleanup.md.

What does branch-cleanup do?

It finds merged and stale branches, checks them for unpushed commits, and deletes them after confirmation. It also prunes remote-tracking refs and prints recovery commands.

What is risky about --force?

It deletes merged branches with no confirmation and no undo. Recovery means using the SHA hashes from the report, so run --dry-run first.

Source text

branch-cleanup.md · MIT
---
allowed-tools: Bash(git branch:*), Bash(git checkout:*), Bash(git push:*), Bash(git merge:*), Bash(gh:*), Read, Grep
argument-hint: "[--dry-run] | [--force] | [--remote-only] | [--local-only]"
description: Use PROACTIVELY to clean up merged branches, stale remotes, and organize branch structure
---

# Git Branch Cleanup & Organization

Clean up merged branches and organize repository structure: $ARGUMENTS

## Current Repository State

- All branches: !`git branch -a`
- Recent branches: !`git for-each-ref --count=10 --sort=-committerdate refs/heads/ --format='%(refname:short) - %(committerdate:relative)'`
- Remote branches: !`git branch -r`
- Merged branches: !`git branch --merged main 2>/dev/null || git branch --merged master 2>/dev/null || echo "No main/master branch found"`
- Current branch: !`git branch --show-current`

## Task

Perform comprehensive branch cleanup and organization based on the repository state and provided arguments.

## Cleanup Operations

### 1. Identify Branches for Cleanup
- **Merged branches**: Find local branches already merged into main/master
- **Stale remote branches**: Identify remote-tracking branches that no longer exist
- **Old branches**: Detect branches with no recent activity (>30 days)
- **Feature branches**: Organize feature/* hotfix/* release/* branches

### 2. Safety Checks Before Deletion
- Verify branches are actually merged using `git merge-base`
- Check if branches have unpushed commits
- Confirm branches aren't the current working branch
- Validate against protected branch patterns

### 3. Branch Categories to Handle
- **Safe to delete**: Merged feature branches, old hotfix branches
- **Needs review**: Unmerged branches with old commits
- **Keep**: Main branches (main, master, develop), active feature branches
- **Archive**: Long-running branches that might need preservation

### 4. Remote Branch Synchronization
- Remove remote-tracking branches for deleted remotes
- Prune remote references with `git remote prune origin`
- Update branch tracking relationships
- Clean up remote branch references

## Command Modes

### Default Mode (Interactive)
1. Show branch analysis with recommendations
2. Ask for confirmation before each deletion
3. Provide summary of actions taken
4. Offer to push deletions to remote

### Dry Run Mode (`--dry-run`)
1. Show what would be deleted without making changes
2. Display branch analysis and recommendations
3. Provide cleanup statistics
4. Exit without modifying repository

### Force Mode (`--force`)
1. Delete merged branches without confirmation
2. Clean up stale remotes automatically
3. Provide summary of all actions taken
4. Use with caution - no undo capability

### Remote Only (`--remote-only`)
1. Only clean up remote-tracking branches
2. Synchronize with actual remote state
3. Remove stale remote references
4. Keep all local branches intact

### Local Only (`--local-only`)
1. Only clean up local branches
2. Don't affect remote-tracking branches
3. Keep remote synchronization intact
4. Focus on local workspace organization

## Safety Features

### Pre-cleanup Validation
- Ensure working directory is clean
- Check for uncommitted changes
- Verify current branch is safe (not target for deletion)
- Create backup references if requested

### Protected Branches
Never delete branches matching these patterns:
- `main`, `master`, `develop`, `staging`, `production`
- `release/*` (unless explicitly confirmed)
- Current working branch
- Branches with unpushed commits (unless forced)

### Recovery Information
- Display git reflog references for deleted branches
- Provide commands to recover accidentally deleted branches
- Show SHA hashes for branch tips before deletion
- Create recovery script if multiple branches deleted

## Branch Organization Features

### Naming Convention Enforcement
- Suggest renaming branches to follow team conventions
- Organize branches by type (feature/, bugfix/, hotfix/)
- Identify branches that don't follow naming patterns
- Provide batch renaming suggestions

### Branch Tracking Setup
- Set up proper upstream tracking for feature branches
- Configure push/pull behavior for new branches
- Identify branches missing upstream configuration
- Fix broken tracking relationships

## Output and Reporting

### Cleanup Summary
```
Branch Cleanup Summary:
✅ Deleted 3 merged feature branches
✅ Removed 5 stale remote references
✅ Cleaned up 2 old hotfix branches
⚠️  Found 1 unmerged branch requiring attention
📊 Repository now has 8 active branches (was 18)
```

### Recovery Instructions
```
Branch Recovery Commands:
git checkout -b feature/user-auth 1a2b3c4d  # Recover feature/user-auth
git push origin feature/user-auth            # Restore to remote
```

## Best Practices

### Regular Maintenance Schedule
- Run cleanup weekly for active repositories
- Use `--dry-run` first to review changes
- Coordinate with team before major cleanups
- Document any non-standard branches to preserve

### Team Coordination
- Communicate branch deletion plans with team
- Check if anyone has work-in-progress on old branches
- Use GitHub/GitLab branch protection rules
- Maintain shared documentation of branch policies

### Branch Lifecycle Management
- Delete feature branches immediately after merge
- Keep release branches until next major release
- Archive long-term experimental branches
- Use tags to mark important branch states before deletion

## Example Usage

```bash
# Safe interactive cleanup
/branch-cleanup

# See what would be cleaned without changes
/branch-cleanup --dry-run

# Clean only remote tracking branches
/branch-cleanup --remote-only

# Force cleanup of merged branches
/branch-cleanup --force

# Clean only local branches
/branch-cleanup --local-only
```

## Integration with GitHub/GitLab

If GitHub CLI or GitLab CLI is available:
- Check PR status before deleting branches
- Verify branches are actually merged in web interface
- Clean up both local and remote branches consistently
- Update branch protection rules if needed

© davila7 · MIT · davila7/claude-code-templates

Similar slash commands

All slash commands for Git and GitHub →

From the same set205

The whole set →
code-review-checklist A skill that walks a reviewer through context, functionality, quality, security, performance and tests. Useful on pull requests and audits. 365installs vercel-environment-sync A hook that inspects environment variables after an .env edit and points you to the right Vercel sync commands. Useful when local and deployed values drift apart. 363installs log Writes a finished task's report into your tracker or notes: time spent, status, commits. Useful when the coding happens in Claude but the record lives in Linear or Obsidian. 351installs create-worktrees Pulls every open pull request through GitHub CLI and sets up a separate git worktree for each branch under ./tree/. Useful when you want several PRs checked out at once without switching branches in the main checkout. 351installs pentest-checklist A skill that walks you through pentest planning: objectives, scope, environment prep, tester selection and monitoring. Useful before a security assessment. 336installs create-database-migrations A Claude slash command that generates database migration files with versioning and rollback methods. Useful when you change a schema and don't want to hand-write up/down. 329installs nia-oracle A Claude subagent that finds repositories and documentation through Nia tools, indexes them, and pulls answers back out. 329installs setup-visual-testing A slash command that wires up visual regression testing: component and page snapshots, responsive breakpoints, accessibility checks. 300installs

Project sponsors

Companies that keep this analytics open
Gold sponsor

Impressions, clicks and code copies — open statistics. We keep the numbers public for the same reason NeBlask itself is public. Become a sponsor