#!/usr/bin/env python3 """Show every work branch against origin/dev: what is unpushed, merged, stale or deployed. Read-only by default. `--prune` deletes local branches whose commits are all in origin/dev and that no worktree has checked out; remote branches and worktrees are never touched. """ import argparse import json from datetime import datetime, timezone from pathlib import Path import re import subprocess import sys import unicodedata ROOT = Path(__file__).resolve().parents[1] BASE = 'origin/dev' PROTECTED = {'dev', 'poc', 'main', 'master', 'HEAD'} STALE_DAYS = 7 STACKED_COMMITS = 30 CARD = re.compile(r'^\.scratch/[^/]+/work\.md$') def git(*args, check=True): out = subprocess.run(['git', *args], cwd=ROOT, capture_output=True, text=True) if check and out.returncode != 0: # Remote URLs may carry credentials; never echo them. raise SystemExit(re.sub(r'//[^@/\s]+@', '//@', out.stderr.strip())) return out.stdout.strip() if out.returncode == 0 else None def count(rng): return int(git('rev-list', '--count', rng)) def worktrees(): """{branch: path} for checked-out branches, plus every worktree path (including detached ones).""" paths, every, path = {}, [], None for line in git('worktree', 'list', '--porcelain').splitlines(): if line.startswith('worktree '): path = line[9:] every.append(path) elif line.startswith('branch refs/heads/'): paths[line[18:]] = path return paths, every def branches(): refs = {} for line in git('for-each-ref', '--format=%(refname)', 'refs/heads', 'refs/remotes/origin').splitlines(): if line.startswith('refs/heads/'): refs.setdefault(line[11:], {})['local'] = line else: refs.setdefault(line[20:], {})['remote'] = line return {name: r for name, r in refs.items() if name not in PROTECTED} def card(ref): """The task card this branch adds under .scratch//work.md, as {field: value}.""" names = git('diff', '--name-only', f'{BASE}...{ref}', check=False) or '' for name in names.splitlines(): if CARD.match(name): text = git('show', f'{ref}:{name}', check=False) or '' fields = dict(re.findall(r'^([A-Za-z-]+):\s*(.+)$', text, re.M)) fields['path'] = name return fields return None def describe(name, refs, trees): local, remote = refs.get('local'), refs.get('remote') tip = local or remote b = {'name': name, 'local': bool(local), 'remote': bool(remote), 'worktree': trees.get(name)} b['ahead'] = count(f'{BASE}..{tip}') b['behind'] = count(f'{tip}..{BASE}') # Rebased or squash-merged work: every commit already has an equivalent patch in dev. cherry = git('cherry', BASE, tip).splitlines() if b['ahead'] else [] b['merged'] = b['ahead'] == 0 or bool(cherry) and all(line.startswith('-') for line in cherry) b['unpushed'] = count(f'{remote}..{local}') if local and remote else (b['ahead'] if local else 0) b['remoteOnly'] = count(f'{local}..{remote}') if local and remote else 0 stamp = int(git('log', '-1', '--format=%ct', tip)) b['lastCommit'] = datetime.fromtimestamp(stamp, timezone.utc).date().isoformat() b['ageDays'] = (datetime.now(timezone.utc) - datetime.fromtimestamp(stamp, timezone.utc)).days b['card'] = None if b['merged'] else card(tip) if b['worktree'] and not b['merged']: b['dirty'] = bool(git('-C', b['worktree'], 'status', '--porcelain', check=False)) return b def problems(b): out = [] if b['unpushed'] and b['remoteOnly']: out.append(f'本地和远端分叉(本地多 {b["unpushed"]},远端多 {b["remoteOnly"]})') elif b['unpushed']: out.append(f'{b["unpushed"]} 个提交未推送' if b['remote'] else '从未推送') elif b['remoteOnly']: out.append(f'远端多 {b["remoteOnly"]} 个提交,本地未同步') if not b['card']: out.append('缺登记卡') if b['ahead'] > STACKED_COMMITS: out.append(f'领先 dev {b["ahead"]} 个提交,可能叠在别的未合并分支上') if b['ageDays'] > STALE_DAYS: out.append(f'{b["ageDays"]} 天没有新提交') if b.get('dirty'): out.append('worktree 有未提交改动') return out def deployed(checkouts): """Newest release record that reached the cluster. release.py writes its ledger under the checkout it ran from, so records are spread across worktrees; read them all. """ best = None for checkout in checkouts: for path in Path(checkout, 'local-data/releases').glob('*/release.json'): try: r = json.loads(path.read_text()) except (OSError, ValueError): continue if str(r.get('state', '')).startswith(('deployed', 'accepted')) and r.get('commit'): if not best or r.get('createdAt', '') > best.get('createdAt', ''): best = dict(r, ledger=str(path.parent.parent)) if not best: return None commit = best['commit'] inside = git('merge-base', '--is-ancestor', commit, BASE, check=False) is not None holders = [] if inside else [ line.strip().removeprefix('origin/') for line in (git('branch', '-r', '--contains', commit, check=False) or '').splitlines()] return {'id': best.get('id'), 'commit': commit[:8], 'state': best.get('state'), 'date': best.get('createdAt', '')[:10], 'inDev': inside, 'branches': sorted(set(holders)), 'ledger': best['ledger']} def prune(rows): current = git('branch', '--show-current', check=False) done = [] for b in rows: # Only strict ancestry: the commits themselves stay reachable from dev after deletion. if b['local'] and b['ahead'] == 0 and not b['worktree'] and b['name'] != current: git('branch', '-D', b['name']) done.append(b['name']) return done def width(text): return sum(2 if unicodedata.east_asian_width(c) in 'WF' else 1 for c in text) def table(rows, cols): cells = [[str(c[0]) for c in cols]] + [[str(c[1](r)) for c in cols] for r in rows] widths = [max(width(row[i]) for row in cells) for i in range(len(cols))] return '\n'.join(' ' + ' '.join(cell + ' ' * (w - width(cell)) for cell, w in zip(row, widths)).rstrip() for row in cells) def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--no-fetch', action='store_true', help='use the remote refs already on disk') parser.add_argument('--all', action='store_true', help='also list merged branches one by one') parser.add_argument('--json', action='store_true', help='machine-readable output') parser.add_argument('--prune', action='store_true', help='delete local branches fully contained in origin/dev') args = parser.parse_args() if not args.no_fetch: git('fetch', '--prune', '--quiet', 'origin') trees, checkouts = worktrees() rows = sorted((describe(n, r, trees) for n, r in branches().items()), key=lambda b: (b['merged'], -b['ageDays'] if b['merged'] else b['ageDays'], b['name'])) release = deployed(checkouts) pruned = prune(rows) if args.prune else [] if args.json: print(json.dumps({'base': git('rev-parse', '--short', BASE), 'deployed': release, 'branches': rows, 'pruned': pruned}, ensure_ascii=False, indent=2)) return active = [b for b in rows if not b['merged']] merged = [b for b in rows if b['merged']] print(f'基线 {BASE} = {git("rev-parse", "--short", BASE)}') if release: print(f'\n线上最近一次发布:{release["id"]} 提交 {release["commit"]} {release["date"]} {release["state"]}') print(f' 记录位置:{release["ledger"]}') if not release['inDev']: where = '、'.join(release['branches']) or '没有任何远端分支' print(f' ! 这个提交不在 dev 里,只存在于:{where}') else: print('\n本机所有 worktree 里都没有发布记录(local-data/releases)。') print(f'\n进行中的分支({len(active)})') if active: print(table(active, [ ('分支', lambda b: b['name']), ('领先/落后 dev', lambda b: f'+{b["ahead"]} / -{b["behind"]}'), ('最后提交', lambda b: b['lastCommit']), ('目标', lambda b: (b['card'] or {}).get('Goal', '-')[:40]), ('需要处理', lambda b: ';'.join(problems(b)) or '-'), ])) removable = [b for b in merged if b['local'] and b['ahead'] == 0 and not b['worktree']] print(f'\n已合并进 dev({len(merged)}),其中 {len(removable)} 个本地分支可直接删除' + ('' if args.prune else ':运行 --prune')) if args.all and merged: print(table(merged, [ ('分支', lambda b: b['name']), ('位置', lambda b: '/'.join(k for k in ('local', 'remote') if b[k])), ('worktree', lambda b: b['worktree'] or '-'), ])) if pruned: print(f'\n已删除 {len(pruned)} 个本地分支:' + '、'.join(pruned)) held = [b for b in merged if b['worktree']] if held: print(f'\n{len(held)} 个已合并分支仍被 worktree 占用,确认无未提交改动后用 git worktree remove 清理:') for b in held: print(f' {b["name"]} {b["worktree"]}') if __name__ == '__main__': sys.exit(main())