| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161 |
- #!/usr/bin/env python3
- # -*- coding: utf-8 -*-
- """主工作树 vs 远程主线漂移检测(只读,不改任何文件)
- 背景:本仓库多会话/多 agent 并发在同一个主工作树(E:/cfc)里工作,反复出现
- 「本地看到 bug、远程其实已修」的误判 —— 根因是工作树里的 tracked 文件停留在旧版本,
- 而修复已在 origin/cfclub。三次实证:购物车 4 文件、profile.vue、health-survey.vue。
- 用法:
- python docs/scripts/worktree_drift_check.py # 全仓扫描
- python docs/scripts/worktree_drift_check.py cfc-frontend/ # 只看某路径
- python docs/scripts/worktree_drift_check.py --base origin/cfclub --limit 20
- python docs/scripts/worktree_drift_check.py --json out.json # 机器可读全量
- 分类:
- REVERT_RISK index 已是远程版,但工作树被改回旧版(裸 add+commit 会覆盖远程修复)★最危险
- SAFE_ALIGN 工作树 == index == HEAD,只是本地 HEAD 落后远程(可安全对齐)
- LOCAL_WIP 本地有独有改动且与远程不同(需人工判断是否有价值)
- LOCAL_DELETED 远程有、本地工作树删掉了(裸 commit 会删远程文件)
- 退出码:0 = 无 REVERT_RISK;1 = 存在 REVERT_RISK;2 = 参数/环境错误
- """
- import argparse
- import json
- import os
- import subprocess
- import sys
- def git(*args):
- p = subprocess.run(["git"] + list(args), capture_output=True)
- if p.returncode != 0:
- raise RuntimeError("git %s failed: %s" % (" ".join(args), p.stderr.decode("utf-8", "replace").strip()))
- return p.stdout
- def git_try(*args):
- p = subprocess.run(["git"] + list(args), capture_output=True)
- return p.stdout.decode("utf-8", "replace") if p.returncode == 0 else ""
- def split0(raw):
- if isinstance(raw, bytes):
- raw = raw.decode("utf-8", "replace")
- return [x for x in raw.split("\0") if x]
- def main():
- ap = argparse.ArgumentParser()
- ap.add_argument("paths", nargs="*", help="限定路径(默认全仓)")
- ap.add_argument("--base", default="origin/cfclub", help="远程基线 ref(默认 origin/cfclub)")
- ap.add_argument("--limit", type=int, default=15, help="每类打印条数上限(默认 15,0=全量)")
- ap.add_argument("--json", dest="json_out", default="", help="把全量结果写入 JSON 文件")
- args = ap.parse_args()
- base = args.base
- if not git_try("rev-parse", "--verify", "-q", base + "^{commit}").strip():
- sys.stderr.write("基线 ref 不存在:%s(先 git fetch origin cfclub)\n" % base)
- return 2
- pathfilter = ["--"] + args.paths if args.paths else []
- # 工作树 vs base:状态与路径(-z 防中文/空格路径被转义)
- raw = git_try("diff", "--name-status", "-z", "--no-renames", base, *pathfilter)
- toks = split0(raw)
- worktree_diff = {} # path -> status(M/D)
- for i in range(0, len(toks) - 1, 2):
- st, p = toks[i], toks[i + 1]
- worktree_diff[p] = st[:1]
- wt_vs_index = set(split0(git_try("diff", "--name-only", "-z", *pathfilter)))
- index_vs_head = set(split0(git_try("diff", "--cached", "--name-only", "-z", *pathfilter)))
- index_blobs = {}
- for rec in split0(git_try("ls-files", "-s", "-z", *pathfilter)):
- meta, _, p = rec.partition("\t")
- parts = meta.split()
- if len(parts) == 3:
- index_blobs[p] = parts[1]
- base_blobs = {}
- tree = git_try("ls-tree", "-r", "-z", base)
- for rec in split0(tree):
- meta, _, p = rec.partition("\t")
- parts = meta.split()
- if len(parts) == 3:
- base_blobs[p] = parts[2]
- head_blobs = {}
- for rec in split0(git_try("ls-tree", "-r", "-z", "HEAD")):
- meta, _, p = rec.partition("\t")
- parts = meta.split()
- if len(parts) == 3:
- head_blobs[p] = parts[2]
- buckets = {"REVERT_RISK": [], "SAFE_ALIGN": [], "LOCAL_WIP": [], "LOCAL_DELETED": [], "ALIGNED_ON_DISK": []}
- def disk_blob_matches_origin(p):
- """本地磁盘文件已存在且 blob == origin blob(恢复后 git 可能因 untracked 看不见它)"""
- lp = os.path.join(os.getcwd(), p.replace("/", os.sep))
- if not os.path.isfile(lp):
- return False
- h = subprocess.run(["git", "hash-object", "--path=" + p, p], capture_output=True)
- return h.returncode == 0 and h.stdout.decode().strip() == (base_blobs.get(p) or "")
- for p, st in sorted(worktree_diff.items()):
- if st == "D":
- # 磁盘实际存在且内容已对齐 origin(untracked 恢复文件)→ 不是真删除
- if disk_blob_matches_origin(p):
- buckets["ALIGNED_ON_DISK"].append(p)
- else:
- buckets["LOCAL_DELETED"].append(p)
- continue
- ob = base_blobs.get(p)
- ib = index_blobs.get(p)
- if ob and ib and ib == ob and p in wt_vs_index:
- # index 已是远程版本,工作树又偏离 —— 提交会覆盖远程修复
- buckets["REVERT_RISK"].append(p)
- elif p not in wt_vs_index and p not in index_vs_head:
- buckets["SAFE_ALIGN"].append(p)
- else:
- buckets["LOCAL_WIP"].append(p)
- total = sum(len(v) for v in buckets.values())
- print("基线 %s | 与远程不同的 tracked 文件:%d" % (base, total))
- print("=" * 72)
- order = [
- ("REVERT_RISK", "🔴 index=远程版 但工作树被改回 → 裸 commit 会覆盖远程修复(先对齐)"),
- ("LOCAL_DELETED", "🟠 本地删除了远程存在的文件 → 裸 commit 会删远程文件"),
- ("LOCAL_WIP", "🟡 本地独有改动、与远程不同 → 人工判断价值,勿直接覆盖"),
- ("SAFE_ALIGN", "🟢 仅落后远程(本地无独有改动)→ 可安全对齐"),
- ("ALIGNED_ON_DISK", "⚪ 磁盘已恢复为远程版,但 index 未更新(git 视为 untracked,不影响恢复结果)"),
- ]
- for key, title in order:
- items = buckets[key]
- print("\n[%s] %d 个 %s" % (key, len(items), title))
- show = items if args.limit == 0 else items[: args.limit]
- for p in show:
- print(" " + p)
- if len(items) > len(show):
- print(" ... 其余 %d 个(--limit 0 看全量)" % (len(items) - len(show)))
- print("\n" + "=" * 72)
- print("处置建议:")
- print(" REVERT_RISK → 先备份本地文件,再 git cat-file blob %s:<path> 覆盖(勿只 git checkout HEAD)" % base)
- print(" SAFE_ALIGN → 追平基线即可(git merge --ff-only 或用基线的 blob 覆盖)")
- print(" LOCAL_WIP → 先 git diff %s -- <path> 判断是\"有效新改动\"还是\"退化旧版\"再决定" % base)
- print(" LOCAL_DELETED→ 确认是否有意删除(参考资料类多为误删,建议恢复)")
- print("\n铁律:主工作树存在以上任一类时,禁止在 E:/cfc 裸 git add/commit。")
- print(" 改动一律走独立 worktree + 分支,入库用临时索引法(GIT_INDEX_FILE)。")
- if args.json_out:
- with open(args.json_out, "w", encoding="utf-8") as fh:
- json.dump({"base": base, "buckets": buckets}, fh, ensure_ascii=False, indent=2)
- print("\n全量结果已写入 %s" % args.json_out)
- return 1 if buckets["REVERT_RISK"] else 0
- if __name__ == "__main__":
- sys.exit(main())
|