当前位置: 首页 > Skill >

Phy Git Branch Janitor

Phy Git Branch Janitor

Phy Git Branch Janitor

Git 分支清理助手,审计本地和远程分支,将其分为可安全删除(已合并)、陈旧未合并(老旧无开放PR)或活跃分支。

1.0.3 2026.11.25 825
获取Skill文件查看使用说明
作 者:顾知 许可证: 更新时间:2026.11.25
本文目录展开

Git Branch Janitor

Audit every branch in your repo — local and remote — and produce a prioritized cleanup plan. Find branches that are already merged, branches that have gone stale with no activity, and branches that never made it to the remote. Get one copy-paste command to clean them all up safely.

Works on any Git repo. Optional GitHub CLI for PR cross-reference. Zero config.

Trigger Phrases

  • "clean up branches", "branch cleanup", "delete old branches"
  • "stale branches", "orphaned branches", "branch audit"
  • "git housekeeping", "which branches can I delete"
  • "/git-branch-janitor"

Step 1: Fetch Latest State

# Sync remote branch state (prune deleted remote branches from local tracking)
git fetch --all --prune

# Show current branch (to avoid deleting it)
git branch --show-current

Important: Never delete the current branch, main, master, develop, or release/* — these are protected.

Step 2: Inventory All Branches

Run all three simultaneously to build a complete picture:

# Local branches
git branch --format='%(refname:short)' | sort

# Remote branches
git branch -r --format='%(refname:short)' | sed 's/origin///' | sort

# All branches with last commit metadata
git for-each-ref --sort=committerdate 
  --format='%(refname:short)|%(committerdate:relative)|%(committerdate:iso)|%(authorname)|%(subject)' 
  refs/heads refs/remotes/origin 
  | grep -v "HEAD$" 
  | sort -t'|' -k3

Parse each branch's:

  • Last commit date → age bucket (< 7 days, 7-30 days, 30-90 days, > 90 days)
  • Author → who owns this branch
  • Subject → last commit message (hint about what the branch was for)

Step 3: Classify Each Branch

Class 1: SAFE-TO-DELETE (Merged)

Branches that are fully merged into the default branch:

# Branches merged into main (replace 'main' with your default branch)
DEFAULT=$(git symbolic-ref refs/remotes/origin/HEAD 2>/dev/null | sed 's/refs/remotes/origin///' || echo "main")

# Local merged branches
git branch --merged "$DEFAULT" | grep -v "^*" | grep -vE "^s*(main|master|develop|release/)" | sed 's/^  //'

# Remote merged branches
git branch -r --merged "origin/$DEFAULT" | grep -v "HEAD" | grep -vE "(main|master|develop|release/)" | sed 's/origin///' | sed 's/^  //'

Rule: If a branch has been fully merged into the default branch, it's safe to delete.

Class 2: STALE-UNMERGED (Review Required)

Branches NOT merged but with no recent activity:

# Branches NOT merged into main, older than 30 days
git for-each-ref 
  --format='%(refname:short)|%(committerdate:iso)|%(committerdate:relative)' 
  refs/heads 
  | while IFS='|' read -r branch date reldate; do
      # Skip protected branches
      echo "$branch" | grep -qE "^(main|master|develop|release/)" && continue
      # Check if merged
      git merge-base --is-ancestor "$branch" "$DEFAULT" 2>/dev/null && continue
      # Check age > 30 days
      DAYS=$(( ($(date +%s) - $(date -d "$date" +%s 2>/dev/null || date -j -f "%Y-%m-%d %H:%M:%S %z" "$date" "+%s" 2>/dev/null)) / 86400 ))
      [ "$DAYS" -gt 30 ] && echo "$branch|${DAYS}d old|$reldate"
  done

Rule: These need human review — was this branch abandoned? Did it become a draft PR?

Class 3: ORPHANED (Local only, never pushed)

Branches that exist locally but have no remote tracking branch:

git branch -vv | grep ": gone]" | awk '{print $1}'
# These had a remote, but remote was deleted (PR merged via GitHub UI)

git branch -vv | grep -v "[origin" | grep -v "^*" | awk '{print $1}'
# These were never pushed at all

Class 4: AHEAD-ONLY (Unpushed work)

Branches that have commits not on remote — don't delete these:

# Check which branches have commits ahead of remote
git branch -vv | grep "ahead"

Step 4: Cross-Reference PRs (Optional — requires gh CLI)

If gh is available, enhance stale-unmerged branches with PR status:

# Check if a branch has an open or merged PR
for branch in $STALE_BRANCHES; do
  PR=$(gh pr list --head "$branch" --state all --json number,state,title --jq '.[0]' 2>/dev/null)
  if [ -n "$PR" ]; then
    STATE=$(echo "$PR" | python3 -c "import sys,json; d=json.load(sys.stdin); print(d['state'])")
    TITLE=$(echo "$PR" | python3 -c "import sys,json; d=json.load(sys.stdin); print(d['title'][:50])")
    NUMBER=$(echo "$PR" | python3 -c "import sys,json; d=json.load(sys.stdin); print(d['number'])")
    echo "$branch → PR #$NUMBER ($STATE): $TITLE"
  else
    echo "$branch → No PR found"
  fi
done

With PR context:

  • MERGED PR → definitely safe to delete
  • CLOSED PR → was abandoned, confirm with user before deleting
  • OPEN PR → active work in progress — never delete
  • No PR → was this work captured elsewhere? Ask user.

Step 5: Generate Cleanup Commands

Produce three batches of commands:

Batch 1: Auto-Safe Deletes

# Delete merged local branches
git branch -d feat/add-login feat/fix-typo chore/update-deps

# Delete merged remote branches
git push origin --delete feat/add-login feat/fix-typo chore/update-deps

Batch 2: Gone-Remote Cleanup (Orphaned)

# These had remotes that were already deleted (usually by GitHub after PR merge)
git branch -d fix/header-bug refactor/auth-service

Batch 3: Stale-Unmerged (Review First)

# ⚠️ Review these before running — they were never merged
# Branch: wip/new-feature (last commit: 47 days ago, no PR found)
# git branch -D wip/new-feature  # -D forces delete of unmerged branch
# git push origin --delete wip/new-feature

Output Report

Always produce this report structure:

## Git Branch Janitor Report
Repo: [repo name] | Default branch: main | $(date)

### Summary
| Category | Local | Remote |
|----------|-------|--------|
| 🟢 Safe-to-delete (merged) | 8 | 6 |
| 🟠 Stale unmerged (>30 days, no open PR) | 3 | 2 |
| 🔵 Orphaned (remote gone) | 4 | — |
| ⚠️ Ahead-only (unpushed work) | 2 | — |
| ✅ Active (recent commits) | 5 | 7 |

---

### 🟢 Safe to Delete — Already Merged

| Branch | Last Commit | Author | Merged Via |
|--------|-------------|--------|-----------|
| feat/add-login | 12 days ago | alice | PR #142 (merged) |
| fix/header-bug | 23 days ago | bob | PR #138 (merged) |
| chore/bump-deps | 31 days ago | alice | Direct merge |

**One command to clean all:**
```bash
# Local
git branch -d feat/add-login fix/header-bug chore/bump-deps

# Remote
git push origin --delete feat/add-login fix/header-bug chore/bump-deps

🔵 Orphaned — Remote Already Deleted

These branches exist locally but their remote was deleted (e.g., GitHub merged the PR):

Branch Last Commit Author
feat/dark-mode 8 days ago carol
fix/mobile-nav 15 days ago alice
git branch -d feat/dark-mode fix/mobile-nav

🟠 Stale Unmerged — Review Before Deleting

Branch Age Author PR Status
wip/new-dashboard 47 days bob No PR found
experiment/redis-cache 62 days carol PR #120 (closed, abandoned)

⚠️ These were never merged. Confirm with owner before deleting:

# Only run after confirming work is captured or abandoned:
git branch -D wip/new-dashboard
git push origin --delete wip/new-dashboard

⚠️ Skipped — Has Unpushed Work

Branch Commits Ahead Last Commit
feat/user-settings 7 commits 2 days ago
fix/payment-flow 2 commits yesterday

Not deleted — these have unpushed commits. Push or open a PR first.

Cleanup Summary

After running the safe commands above, you'll free:

  • 15 local branches removed
  • 8 remote branches removed
  • Estimated git fetch speed improvement: ~30% (fewer refs to sync)

---

## Age Thresholds (Configurable)

By default, branches are flagged as "stale" after:

| Category | Default Threshold |
|----------|------------------|
| Stale (review recommended) | > 30 days since last commit |
| Very stale (safe to flag) | > 90 days since last commit |
| Ancient (definitely dead) | > 6 months |

User can override: "show branches older than 2 weeks" or "flag anything over 60 days."

---

## Protected Branches (Never Delete)

The following patterns are always excluded from cleanup suggestions:

main, master, develop, staging, production release/, hotfix/, v*.. HEAD


---

## Quick Mode

When user just wants a fast count:

Quick Branch Audit: 🟢 12 merged (safe to delete) 🔵 5 orphaned (remote gone) 🟠 3 stale unmerged (>30d, no open PR) ⚠️ 2 with unpushed commits (skip)

Safe to clean: 17 branches Run /git-branch-janitor --full for delete commands


---

## Why Not Just `git branch -d`?

`git branch -d` only deletes branches merged into the current HEAD — it misses:

- Branches merged on GitHub/GitLab via squash or rebase (not a standard merge commit)
- Remote tracking refs left behind after the remote branch was deleted
- Branches with PRs that were closed without merging
- Branches that diverged from main and were superseded by a re-implementation

This skill handles all four cases.

---

## Author

**[Canlah AI](https://canlah.ai)** — Run performance marketing without breaking your brand.

- GitHub: [github.com/PHY041](https://github.com/PHY041)
- All Skills: [clawhub.ai/PHY041](https://clawhub.ai/PHY041)

推荐文章

更多
PHP时间戳与日期字符串相互转换方法详解

本文介绍PHP中时间数值(Unix时间戳)与日期字符串之间的相互转换方法。通过strtotime和date函数,实现将当前时间、指定日期转换为时间戳,以及将时间戳格式化为可读的日期时间字符串,并提供相关在线计算工具推荐。

2025.11.30 1,034
PHP日期转时间戳时区偏差怎么解决

在 PHP 中将日期字符串转换为时间戳时,若未显式指定时区,默认使用脚本配置的 date.timezone 或系统时区。当服务器时区与业务逻辑预期(如 UTC )不一致时,会产生偏差。解决核心是确保输入字符串携带明确时区信息,或在转换前统一设置时区上下文。

2026.10.24 1,031
PHP跨域配置:怎么安全地允许指定域名而非使用通配符

在 PHP 中安全地允许指定域名跨域,核心是解析请求头中的 Origin ,验证其是否在白名单内,然后动态设置 Access-Control-Allow-Origin 响应头。不要使用通配符 * ,也不要硬编码单一域名。

2025.03.29 1,018
JavaScript中利用replace结合正则实现replaceAll效果

JavaScript原生仅支持replace()进行单次或全局替换,缺乏类似Java的replaceAll()便捷方法。本文总结四种在JS中实现全量替换的方案:使用带g标志的正则、带gm标志的正则、扩展String原型以及split后join。通过对比代码示例,展示各方法的实现细节与适用场景,帮助开发者根据需求选择最优解。

2025.04.29 1,017
OpenAI的Jalapeno芯片未落地,教你分辨300兆瓦算力消息

OpenAI计划在SB Energy租赁的数据中心部署约300兆瓦自研Jalapeno推理芯片,但目前双方仍处于洽谈阶段,交易细节与上线时间表均未公布。本文带你按报道原文核实项目所处阶段,厘清芯片发布、电力功率与实际推理算力的边界,并将融资意向与签约、开工、投运节点分开追踪,避免误将规划容量计入现有算力。

2026.12.02 1,013
PHP实现基础文件上传:HTML表单与$_FILES处理流程

在 HTML 表单中设置 enctype="multipart/form-data" ,并在 PHP 后端通过 $_FILES 数组接收文件,调用 move_uploaded_file() 将临时文件移动到目标目录即可完成上传。

2026.09.07 1,013
Skill 文件
  • SKILL.md
    • Git Branch Janitor
    • Trigger Phrases
    • Step 1: Fetch Latest State
    • Step 2: Inventory All Branches
    • Step 3: Classify Each Branch
      • Class 1: SAFE-TO-DELETE (Merged)
      • Class 2: STALE-UNMERGED (Review Required)
      • Class 3: ORPHANED (Local only, never pushed)
      • Class 4: AHEAD-ONLY (Unpushed work)
    • Step 4: Cross-Reference PRs (Optional — requires gh CLI)
    • Step 5: Generate Cleanup Commands
      • Batch 1: Auto-Safe Deletes
      • Batch 2: Gone-Remote Cleanup (Orphaned)
      • Batch 3: Stale-Unmerged (Review First)
    • Output Report
      • 🔵 Orphaned — Remote Already Deleted
      • 🟠 Stale Unmerged — Review Before Deleting
      • ⚠️ Skipped — Has Unpushed Work
      • Cleanup Summary
  • 项目或源文件

相关 Skill

更多
service-qa-coach service-qa-coach Review support quality for chat, email, phone, social DM, or marketplace service teams. Use when a team needs a QA scorecard, failure-mode analysis, coaching plan, calibration checklist, or service-improvement brief without live ticketing, CRM, or contact-center system access.
高中数学作业批改助手 高中数学作业批改助手 >图片识别 直接读取学生手写作答照片,识别公式、符号、步骤 🧮 自动推导 根据题目自动生成参考答案和评分细则,无需教师预设 📊 逐步给分 每个关键步骤独立评分,体现过程分 📝 结构化报告 输出含识别内容、参考答案、逐步评分、改进建议的完整报告 🗂 批量批改 支持一次性批改多道题,最终汇总得分表
Vibration Analysis Vibration Analysis 分析来自CMS趋势、RMS/峰值、频谱及SCADA报警的风机传动链(主轴、齿轮箱、发电机)振动数据。
Traditional Bone Tool Making Basics Traditional Bone Tool Making Basics Use when you need custom, durable, repairable tools like awls, needles, scrapers, harpoons, or fishing hooks made from local animal bones or antlers and comm...
音频混音工具 音频混音工具 名称:Sound Mixing Tool(标识 sound-mixing-tool) 短简介(≤60字):音乐/音效响度精确对齐 + 融合混音工作流:用 ffmpeg 两段式 loudnorm 把多组素材 LUFS 偏差压到 <0.10,再最小干预融合、导出可进引擎的独立分轨。 标签/关键词:音频混音 响度匹配 LUFS ffmpeg 游戏音频 音效设计 Wwise FMOD 分轨导出 后期处理 触发词:混音 · 响度匹配 · LUFS 对齐 · MIX 版本 · 音乐音效分轨 · 融合 · 不打架 · 不能盖住 适用场景 :游戏音频集成、影视短视频配乐、播客后期