branch-cleanup

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Branch Cleanup

分支清理

Automated workflow to sync main with origin and clean up local branches that have merged PRs.
用于同步main分支与origin、清理包含已合并PR的本地分支的自动化工作流。

Quick Start

快速开始

When user asks to "clean up branches" or "delete merged branches":
  1. Pre-flight checks:
    • git fetch origin
      (update remote refs)
    • git branch --show-current
      (verify current branch)
    • If not on main: Ask user: "Should I switch to main? (Current: {branch})"
  2. Sync main:
    • git checkout main
    • git pull origin main --ff-only
    • If conflicts: ⚠️ Stop and report "Main has conflicts. Resolve manually."
  3. List local branches:
    • git branch --format='%(refname:short)'
    • Filter out:
      main
      ,
      master
      ,
      develop
      ,
      staging
      ,
      production
      ,
      archive*
    • If no branches: Report "No local branches to clean up" and STOP.
  4. Check PR status for each branch:
    • Get PR for branch:
      gh pr list --head {branch} --state merged --json number,title,url
    • If merged PR found: Add to cleanup list
    • If no PR or not merged: Skip
  5. Present cleanup list:
    • Show table with: branch name, PR number, PR title, PR URL
    • Ask user: "Delete these {count} branches? (y/n)"
    • If user declines: STOP.
  6. Delete branches:
    • For each approved branch:
      • git branch -d {branch}
        (safe delete)
      • If fails with unmerged warning: Show warning and skip
      • If succeeds: Report "✅ Deleted {branch}"
    • Final summary: "Deleted {count} branches, skipped {count} unmerged branches"
当用户要求"清理分支"或"删除已合并分支"时:
  1. 前置检查:
    • git fetch origin
      (更新远程引用)
    • git branch --show-current
      (校验当前分支)
    • 若不在main分支:询问用户:"是否需要切换到main分支?(当前分支:{branch})"
  2. 同步main分支:
    • git checkout main
    • git pull origin main --ff-only
    • 如果出现冲突: ⚠️ 停止操作并提示"main分支存在冲突,请手动解决。"
  3. 列出本地分支:
    • git branch --format='%(refname:short)'
    • 过滤排除:
      main
      master
      develop
      staging
      production
      archive*
    • 如果没有符合条件的分支: 提示"没有可清理的本地分支"并终止流程。
  4. 检查每个分支的PR状态:
    • 获取分支对应的PR:
      gh pr list --head {branch} --state merged --json number,title,url
    • 如果找到已合并的PR: 添加到待清理列表
    • 如果没有对应PR或PR未合并: 跳过
  5. 展示待清理列表:
    • 展示表格,包含:分支名称、PR编号、PR标题、PR链接
    • 询问用户:"是否删除这{count}个分支?(y/n)"
    • 如果用户拒绝: 终止流程。
  6. 删除分支:
    • 对每个确认删除的分支:
      • git branch -d {branch}
        (安全删除)
      • 如果因未合并警告删除失败: 展示警告并跳过
      • 如果删除成功: 提示"✅ 已删除 {branch}"
    • 最终汇总:"已删除{count}个分支,跳过{count}个未合并分支"

Workflow Details

工作流详情

Step 1: Pre-flight Checks

步骤1:前置检查

bash
undefined
bash
undefined

Fetch latest remote refs

拉取最新的远程引用

git fetch origin
git fetch origin

Check current branch

检查当前分支

CURRENT_BRANCH=$(git branch --show-current)

**If not on main:**
- Show: "Currently on `{CURRENT_BRANCH}`. Switch to main?"
- Wait for user confirmation

**Safety:**
- Never switch branches with uncommitted changes
- Check: `git status --porcelain` (must be empty)
CURRENT_BRANCH=$(git branch --show-current)

**如果不在main分支:**
- 提示:"当前在 `{CURRENT_BRANCH}` 分支,是否切换到main分支?"
- 等待用户确认

**安全规则:**
- 存在未提交变更时绝不切换分支
- 校验:`git status --porcelain`(输出必须为空)

Step 2: Sync Main

步骤2:同步main分支

bash
undefined
bash
undefined

Switch to main

切换到main分支

git checkout main
git checkout main

Fast-forward merge only (no conflicts)

仅执行快进合并(无冲突)

git pull origin main --ff-only

**If fast-forward fails:**
- ⚠️ Stop with error: "Main branch has diverged from origin. Manual resolution required."
- Do NOT attempt merge or rebase
git pull origin main --ff-only

**如果快进合并失败:**
- ⚠️ 停止操作并报错:"main分支与origin分支已分叉,需要手动解决。"
- 不要尝试执行merge或rebase操作

Step 3: Identify Merged Branches

步骤3:识别已合并分支

For each local branch:
bash
undefined
对每个本地分支:
bash
undefined

Get merged PR for branch

获取分支对应的已合并PR

gh pr list --head {branch} --state merged --json number,title,url --limit 1

**Branch categories:**

| Status | Action |
|--------|--------|
| Merged PR found | Add to cleanup list |
| Open PR found | Skip (not merged) |
| No PR found | Skip (might be local work) |
| Protected branch | Skip (main, master, etc.) |

**Protected branches:**
- `main`, `master`, `develop`, `staging`, `production`
- Any branch starting with `archive` (e.g., `archive-2024`, `archive/old`)
- Any branch matching `origin/*`
gh pr list --head {branch} --state merged --json number,title,url --limit 1

**分支分类规则:**

| 状态 | 操作 |
|--------|--------|
| 找到已合并PR | 添加到待清理列表 |
| 找到未关闭PR | 跳过(未合并) |
| 未找到对应PR | 跳过(可能是本地开发分支) |
| 受保护分支 | 跳过(main、master等) |

**受保护分支:**
- `main`、`master`、`develop`、`staging`、`production`
- 所有以`archive`开头的分支(例如`archive-2024`、`archive/old`)
- 所有匹配`origin/*`的分支

Step 4: Present Cleanup List

步骤4:展示待清理列表

Format as markdown table:
markdown
undefined
格式为markdown表格:
markdown
undefined

Branches with merged PRs

包含已合并PR的分支

BranchPRTitle
fxstein/AIT-12-feature#45Feature implementation
oliver/ait-8-bugfix#38Fix login bug
Total: 2 branches

**User prompt:**
"Delete these branches? They have merged PRs and are safe to remove. (y/n)"
分支PR标题
fxstein/AIT-12-feature#45功能实现
oliver/ait-8-bugfix#38修复登录bug
总计:2个分支

**用户提示:**
"是否删除这些分支?它们对应的PR已合并,可安全移除。(y/n)"

Step 5: Safe Deletion

步骤5:安全删除

bash
undefined
bash
undefined

Safe delete (only if fully merged)

安全删除(仅当分支已完全合并时生效)

git branch -d {branch}

**If `git branch -d` fails:**
- Shows: "The branch '{branch}' is not fully merged."
- **Action:** Skip and report to user
- **Reason:** Prevents data loss

**Force delete (`-D`) is NEVER used automatically.**
git branch -d {branch}

**如果`git branch -d`执行失败:**
- 提示:"分支 '{branch}' 未完全合并。"
- **操作:** 跳过该分支并告知用户
- **原因:** 防止数据丢失

**绝不自动使用强制删除(`-D`)。**

Edge Cases

边缘情况处理

No Merged Branches

没有已合并分支

If no branches qualify for cleanup:
✅ All local branches are up to date.
No merged branches found for cleanup.
如果没有符合清理条件的分支:
✅ 所有本地分支均为最新状态。
未找到可清理的已合并分支。

Partially Merged Branches

部分合并的分支

If branch has commits not in main but PR is merged:
  • git branch -d
    will fail (expected)
  • Report: "⚠️ Skipped {branch}: has unmerged commits (possible rebase)"
  • User can manually verify with:
    git log main..{branch}
如果分支包含未合入main的提交但PR已合并:
  • git branch -d
    会执行失败(预期行为)
  • 提示:"⚠️ 跳过 {branch}:存在未合并的提交(可能是rebase导致)"
  • 用户可手动执行校验:
    git log main..{branch}

Archive Branches

归档分支

Branches starting with
archive
are preserved:
  • ❌ Skip:
    archive-2024
    ,
    archive/backup
    ,
    archive-old-features
  • Reason: Archive branches contain historical work that should be manually managed
archive
开头的分支会被保留:
  • ❌ 跳过:
    archive-2024
    archive/backup
    archive-old-features
  • 原因: 归档分支包含历史工作内容,需要手动管理

Remote Tracking Branches

远程跟踪分支

Only delete local branches, never remote refs:
  • ✅ Delete:
    fxstein/AIT-12-feature
  • ❌ Skip:
    origin/fxstein/AIT-12-feature
Use
git push origin --delete {branch}
only if user explicitly requests remote deletion.
仅删除本地分支,绝不操作远程引用:
  • ✅ 删除:
    fxstein/AIT-12-feature
  • ❌ 跳过:
    origin/fxstein/AIT-12-feature
仅当用户明确要求删除远程分支时,才执行
git push origin --delete {branch}

Error Handling

错误处理

If ANY error occurs:
  1. STOP IMMEDIATELY
  2. Report the specific error
  3. Show current state: branch name, operation attempted
  4. WAIT for user input
Common errors:
ErrorCauseAction
"Not on main"Current branch not mainAsk to switch
"Fast-forward failed"Main diverged from originStop, manual resolution
"gh command not found"GitHub CLI not installedStop, ask user to install
"Branch not fully merged"Branch has unmerged commitsSkip branch
如果发生任何错误:
  1. 立即终止流程
  2. 告知具体错误信息
  3. 展示当前状态:分支名称、尝试执行的操作
  4. 等待用户输入
常见错误:
错误原因处理方式
"不在main分支"当前分支不是main询问是否切换
"快进合并失败"main分支与origin已分叉停止,需手动解决
"未找到gh命令"未安装GitHub CLI停止,要求用户安装
"分支未完全合并"分支存在未合并的提交跳过该分支

Safety Guarantees

安全保证

  • ✅ Never force-delete (
    -D
    ) branches
  • ✅ Never delete without user confirmation
  • ✅ Never modify remote branches
  • ✅ Never switch branches with uncommitted changes
  • ✅ Always use
    --ff-only
    for main sync
  • ✅ 绝不强制删除(
    -D
    )分支
  • ✅ 未获得用户确认前绝不删除分支
  • ✅ 绝不修改远程分支
  • ✅ 存在未提交变更时绝不切换分支
  • ✅ 同步main分支时始终使用
    --ff-only
    参数

Output Format

输出格式

Success

成功执行

🔄 Syncing main with origin...
✅ Main is up to date

📋 Found 3 branches with merged PRs:
- fxstein/AIT-12-feature (PR #45)
- oliver/ait-8-bugfix (PR #38)
- fxstein/AIT-10-docs (PR #42)

🗑️  Deleting branches...
✅ Deleted fxstein/AIT-12-feature
✅ Deleted oliver/ait-8-bugfix
✅ Deleted fxstein/AIT-10-docs

✨ Cleanup complete: 3 branches deleted
🔄 正在同步main分支与origin...
✅ main分支已为最新状态

📋 找到3个包含已合并PR的分支:
- fxstein/AIT-12-feature (PR #45)
- oliver/ait-8-bugfix (PR #38)
- fxstein/AIT-10-docs (PR #42)

🗑️  正在删除分支...
✅ 已删除 fxstein/AIT-12-feature
✅ 已删除 oliver/ait-8-bugfix
✅ 已删除 fxstein/AIT-10-docs

✨ 清理完成:已删除3个分支

With Skipped Branches

存在跳过的分支

🗑️  Deleting branches...
✅ Deleted fxstein/AIT-12-feature
⚠️  Skipped fxstein/AIT-15-wip: not fully merged
✅ Deleted oliver/ait-8-bugfix

✨ Cleanup complete: 2 deleted, 1 skipped
🗑️  正在删除分支...
✅ 已删除 fxstein/AIT-12-feature
⚠️  跳过 fxstein/AIT-15-wip:未完全合并
✅ 已删除 oliver/ait-8-bugfix

✨ 清理完成:已删除2个,跳过1个

Additional Features

额外功能

Dry Run Mode

试运行模式

If user asks for "preview" or "dry run":
  • Execute steps 1-4 only
  • Show cleanup list
  • STOP before deletion
如果用户要求"预览"或"试运行":
  • 仅执行步骤1-4
  • 展示待清理列表
  • 在删除步骤前终止流程

Delete Remote Branches

删除远程分支

If user explicitly asks to "delete remote branches too":
  • After local deletion succeeds
  • For each deleted branch:
    bash
    git push origin --delete {branch}
  • Report: "✅ Deleted {branch} (local + remote)"
如果用户明确要求"同时删除远程分支":
  • 在本地删除成功后
  • 对每个已删除的本地分支执行:
    bash
    git push origin --delete {branch}
  • 提示:"✅ 已删除 {branch}(本地+远程)"

Requirements

依赖要求

  • Git: Version 2.0+
  • GitHub CLI (gh): Required for PR status checks
  • Repository: Must be a git repository with GitHub remote
  • Git: 2.0及以上版本
  • GitHub CLI (gh): PR状态校验必须依赖
  • 仓库: 必须是绑定GitHub远程仓库的git仓库

Forbidden Actions

禁止操作

  • ❌ Never use
    git branch -D
    (force delete)
  • ❌ Never delete branches without user confirmation
  • ❌ Never modify
    main
    ,
    master
    , or protected branches
  • ❌ Never attempt merge/rebase to resolve conflicts
  • ❌ 绝不使用
    git branch -D
    (强制删除)
  • ❌ 未获得用户确认前绝不删除分支
  • ❌ 绝不修改
    main
    master
    或其他受保护分支
  • ❌ 绝不尝试通过merge/rebase解决冲突