К основному содержанию
команда

branch-cleanup — команда для Claude Code: чистка веток git

Слэш-команда для Claude, которая находит слитые и устаревшие ветки, проверяет их перед удалением и наводит порядок в локальном и удалённом репозитории.

Установить в Claude Code · Через claude-code-templates Все способы и платформы ↓
npx claude-code-templates@latest --command git-workflow/branch-cleanup
Открыть на GitHub

Что делает branch-cleanup

Команда собирает состояние репозитория: список всех веток, десять последних по дате коммита, удалённые ветки, слитые в main или master, и текущую ветку. Дальше она раскладывает их по категориям — что можно удалить, что требует проверки, что трогать нельзя. В защищённых числятся main, master, develop, staging, production, ветки release/* и текущая рабочая ветка.

Режимы задаются аргументом. Без него команда показывает анализ и спрашивает подтверждение перед каждым удалением. --dry-run только печатает, что было бы удалено. --force удаляет слитые ветки без вопросов и отката не предусматривает. --remote-only и --local-only ограничивают работу одной стороной. Перед удалением команда проверяет через git merge-base, что ветка действительно слита, и смотрит, нет ли в ней незапушенных коммитов.

Для удалённых ссылок используется git remote prune origin. Если установлен GitHub CLI, команда сверяет статус пул-реквестов перед удалением ветки — это заметно снижает шанс снести ветку, по которой ещё идёт работа. В отчёте выводятся SHA-хэши верхушек удалённых веток и команды для восстановления через reflog, так что случайное удаление откатывается вручную.

Какие задачи решает

  • удалить локальные ветки, уже слитые в main
  • убрать устаревшие remote-tracking ссылки после удаления веток на сервере
  • посмотреть заранее, что будет удалено, без изменений в репозитории
  • найти ветки без активности дольше 30 дней
  • разложить feature/, hotfix/ и release/ по категориям и проверить upstream-трекинг

Примеры запросов агенту

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

Как установить branch-cleanup

1Через claude-code-templates

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

2Вручную: положить файлы

.claude/commands/branch-cleanup.md

Вызов — /branch-cleanup. Для всех проектов — ~/.claude/commands/

Из того же набора205

Весь набор →
code-review-checklist Скилл ведёт ревьюера по шагам: контекст, функциональность, качество, безопасность, производительность и тесты. Пригодится на пул-реквестах и аудитах. 365установок vercel-environment-sync Хук проверяет переменные окружения после правки .env и подсказывает, как перенести их в Vercel. Пригодится, если локальные и деплойные значения расходятся. 363установок log Переносит отчёт о выполненной задаче во внешние трекеры и заметки: время, статус, коммиты. Пригодится, когда работа идёт в Claude, а учёт — в Linear или Obsidian. 351установок create-worktrees Собирает все открытые пул-реквесты через GitHub CLI и разворачивает под каждую ветку отдельный git worktree в папке ./tree/. Пригодится, когда надо смотреть несколько PR сразу, не переключая ветки в основном чекауте. 351установок pentest-checklist Скилл проводит через планирование пентеста: цели, границы, подготовка среды, выбор исполнителей и мониторинг. Пригодится перед проверкой на проникновение. 336установок create-database-migrations Слэш-команда для Claude, которая создаёт файлы миграций базы данных с версионированием и методами отката. Пригодится, когда меняете схему и не хотите писать up/down вручную. 329установок nia-oracle Субагент для Claude, который ищет репозитории и документацию через инструменты Nia, индексирует найденное и достаёт оттуда ответы. 329установок setup-visual-testing Слэш-команда разворачивает визуальное регрессионное тестирование: снимки компонентов и страниц, адаптивные брейкпоинты, проверка доступности. 300установок

Похожие

github-sensitive-data-cleanup daymade Ищет и удаляет секреты, токены и приватные данные из истории Git, а затем безопасно пушит изменения в GitHub. Пригодится при случайной утечке ключей в публичный репозиторий. CX Codex +1 353установок git-branch-cleanup gotalab Разбирает локальные ветки по статусу слияния и удалённому трекингу, а потом удаляет лишние после подтверждения. Пригодится, когда в git branch уже не разобраться. CX Codex +1 ★ 418звёзд репо gh-cli trailofbits Скилл заставляет ИИ использовать аутентифицированный gh CLI вместо curl и fetch при работе с репозиториями, PR и issues GitHub. Нужен для приватных репо и выше лимитов API. CX Codex +1 6 600установок gh cli Учит агента вызывать GitHub CLI: структурированный JSON, пагинация, поиск issues и PR, загрузка файлов. CX Codex +1 2 600установок stack kitlangton Скилл для работы со стеками PR и MR там, где ветки вливаются squash-мержем и удаляются. Помогает чинить и синхронизировать цепочки изменений. CX Codex +1 474установок creating-pr spencerpauly Скилл проводит агента по шагам создания пул-реквеста: подготовка ветки, заголовок, описание, самопроверка и запрос ревьюеров. CX Codex +1 465установок

Рядом в теме «Git и GitHub»

Все слэш-команды по теме «Git и GitHub» →

Вопросы о branch-cleanup

Как установить branch-cleanup в Claude?

Через шаблоны: npx claude-code-templates@latest --command git-workflow/branch-cleanup. Команда появится в .claude/commands/branch-cleanup.md.

Что делает branch-cleanup?

Ищет слитые и устаревшие ветки, проверяет их на незапушенные коммиты и удаляет по подтверждению. Заодно чистит remote-tracking ссылки и подсказывает команды восстановления.

Чем опасен режим --force?

Он удаляет слитые ветки без подтверждения, и отмены у него нет. Восстанавливать придётся вручную по SHA-хэшам из отчёта, поэтому сначала стоит прогнать --dry-run.

Исходный текст

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

Смотрите также

Спонсоры проекта

Компании, которые помогают держать аналитику открытой