worktree_drift_check.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """主工作树 vs 远程主线漂移检测(只读,不改任何文件)
  4. 背景:本仓库多会话/多 agent 并发在同一个主工作树(E:/cfc)里工作,反复出现
  5. 「本地看到 bug、远程其实已修」的误判 —— 根因是工作树里的 tracked 文件停留在旧版本,
  6. 而修复已在 origin/cfclub。三次实证:购物车 4 文件、profile.vue、health-survey.vue。
  7. 用法:
  8. python docs/scripts/worktree_drift_check.py # 全仓扫描
  9. python docs/scripts/worktree_drift_check.py cfc-frontend/ # 只看某路径
  10. python docs/scripts/worktree_drift_check.py --base origin/cfclub --limit 20
  11. python docs/scripts/worktree_drift_check.py --json out.json # 机器可读全量
  12. 分类:
  13. REVERT_RISK index 已是远程版,但工作树被改回旧版(裸 add+commit 会覆盖远程修复)★最危险
  14. SAFE_ALIGN 工作树 == index == HEAD,只是本地 HEAD 落后远程(可安全对齐)
  15. LOCAL_WIP 本地有独有改动且与远程不同(需人工判断是否有价值)
  16. LOCAL_DELETED 远程有、本地工作树删掉了(裸 commit 会删远程文件)
  17. 退出码:0 = 无 REVERT_RISK;1 = 存在 REVERT_RISK;2 = 参数/环境错误
  18. """
  19. import argparse
  20. import json
  21. import os
  22. import subprocess
  23. import sys
  24. def git(*args):
  25. p = subprocess.run(["git"] + list(args), capture_output=True)
  26. if p.returncode != 0:
  27. raise RuntimeError("git %s failed: %s" % (" ".join(args), p.stderr.decode("utf-8", "replace").strip()))
  28. return p.stdout
  29. def git_try(*args):
  30. p = subprocess.run(["git"] + list(args), capture_output=True)
  31. return p.stdout.decode("utf-8", "replace") if p.returncode == 0 else ""
  32. def split0(raw):
  33. if isinstance(raw, bytes):
  34. raw = raw.decode("utf-8", "replace")
  35. return [x for x in raw.split("\0") if x]
  36. def main():
  37. ap = argparse.ArgumentParser()
  38. ap.add_argument("paths", nargs="*", help="限定路径(默认全仓)")
  39. ap.add_argument("--base", default="origin/cfclub", help="远程基线 ref(默认 origin/cfclub)")
  40. ap.add_argument("--limit", type=int, default=15, help="每类打印条数上限(默认 15,0=全量)")
  41. ap.add_argument("--json", dest="json_out", default="", help="把全量结果写入 JSON 文件")
  42. args = ap.parse_args()
  43. base = args.base
  44. if not git_try("rev-parse", "--verify", "-q", base + "^{commit}").strip():
  45. sys.stderr.write("基线 ref 不存在:%s(先 git fetch origin cfclub)\n" % base)
  46. return 2
  47. pathfilter = ["--"] + args.paths if args.paths else []
  48. # 工作树 vs base:状态与路径(-z 防中文/空格路径被转义)
  49. raw = git_try("diff", "--name-status", "-z", "--no-renames", base, *pathfilter)
  50. toks = split0(raw)
  51. worktree_diff = {} # path -> status(M/D)
  52. for i in range(0, len(toks) - 1, 2):
  53. st, p = toks[i], toks[i + 1]
  54. worktree_diff[p] = st[:1]
  55. wt_vs_index = set(split0(git_try("diff", "--name-only", "-z", *pathfilter)))
  56. index_vs_head = set(split0(git_try("diff", "--cached", "--name-only", "-z", *pathfilter)))
  57. index_blobs = {}
  58. for rec in split0(git_try("ls-files", "-s", "-z", *pathfilter)):
  59. meta, _, p = rec.partition("\t")
  60. parts = meta.split()
  61. if len(parts) == 3:
  62. index_blobs[p] = parts[1]
  63. base_blobs = {}
  64. tree = git_try("ls-tree", "-r", "-z", base)
  65. for rec in split0(tree):
  66. meta, _, p = rec.partition("\t")
  67. parts = meta.split()
  68. if len(parts) == 3:
  69. base_blobs[p] = parts[2]
  70. head_blobs = {}
  71. for rec in split0(git_try("ls-tree", "-r", "-z", "HEAD")):
  72. meta, _, p = rec.partition("\t")
  73. parts = meta.split()
  74. if len(parts) == 3:
  75. head_blobs[p] = parts[2]
  76. buckets = {"REVERT_RISK": [], "SAFE_ALIGN": [], "LOCAL_WIP": [], "LOCAL_DELETED": [], "ALIGNED_ON_DISK": []}
  77. def disk_blob_matches_origin(p):
  78. """本地磁盘文件已存在且 blob == origin blob(恢复后 git 可能因 untracked 看不见它)"""
  79. lp = os.path.join(os.getcwd(), p.replace("/", os.sep))
  80. if not os.path.isfile(lp):
  81. return False
  82. h = subprocess.run(["git", "hash-object", "--path=" + p, p], capture_output=True)
  83. return h.returncode == 0 and h.stdout.decode().strip() == (base_blobs.get(p) or "")
  84. for p, st in sorted(worktree_diff.items()):
  85. if st == "D":
  86. # 磁盘实际存在且内容已对齐 origin(untracked 恢复文件)→ 不是真删除
  87. if disk_blob_matches_origin(p):
  88. buckets["ALIGNED_ON_DISK"].append(p)
  89. else:
  90. buckets["LOCAL_DELETED"].append(p)
  91. continue
  92. ob = base_blobs.get(p)
  93. ib = index_blobs.get(p)
  94. if ob and ib and ib == ob and p in wt_vs_index:
  95. # index 已是远程版本,工作树又偏离 —— 提交会覆盖远程修复
  96. buckets["REVERT_RISK"].append(p)
  97. elif p not in wt_vs_index and p not in index_vs_head:
  98. buckets["SAFE_ALIGN"].append(p)
  99. else:
  100. buckets["LOCAL_WIP"].append(p)
  101. total = sum(len(v) for v in buckets.values())
  102. print("基线 %s | 与远程不同的 tracked 文件:%d" % (base, total))
  103. print("=" * 72)
  104. order = [
  105. ("REVERT_RISK", "🔴 index=远程版 但工作树被改回 → 裸 commit 会覆盖远程修复(先对齐)"),
  106. ("LOCAL_DELETED", "🟠 本地删除了远程存在的文件 → 裸 commit 会删远程文件"),
  107. ("LOCAL_WIP", "🟡 本地独有改动、与远程不同 → 人工判断价值,勿直接覆盖"),
  108. ("SAFE_ALIGN", "🟢 仅落后远程(本地无独有改动)→ 可安全对齐"),
  109. ("ALIGNED_ON_DISK", "⚪ 磁盘已恢复为远程版,但 index 未更新(git 视为 untracked,不影响恢复结果)"),
  110. ]
  111. for key, title in order:
  112. items = buckets[key]
  113. print("\n[%s] %d 个 %s" % (key, len(items), title))
  114. show = items if args.limit == 0 else items[: args.limit]
  115. for p in show:
  116. print(" " + p)
  117. if len(items) > len(show):
  118. print(" ... 其余 %d 个(--limit 0 看全量)" % (len(items) - len(show)))
  119. print("\n" + "=" * 72)
  120. print("处置建议:")
  121. print(" REVERT_RISK → 先备份本地文件,再 git cat-file blob %s:<path> 覆盖(勿只 git checkout HEAD)" % base)
  122. print(" SAFE_ALIGN → 追平基线即可(git merge --ff-only 或用基线的 blob 覆盖)")
  123. print(" LOCAL_WIP → 先 git diff %s -- <path> 判断是\"有效新改动\"还是\"退化旧版\"再决定" % base)
  124. print(" LOCAL_DELETED→ 确认是否有意删除(参考资料类多为误删,建议恢复)")
  125. print("\n铁律:主工作树存在以上任一类时,禁止在 E:/cfc 裸 git add/commit。")
  126. print(" 改动一律走独立 worktree + 分支,入库用临时索引法(GIT_INDEX_FILE)。")
  127. if args.json_out:
  128. with open(args.json_out, "w", encoding="utf-8") as fh:
  129. json.dump({"base": base, "buckets": buckets}, fh, ensure_ascii=False, indent=2)
  130. print("\n全量结果已写入 %s" % args.json_out)
  131. return 1 if buckets["REVERT_RISK"] else 0
  132. if __name__ == "__main__":
  133. sys.exit(main())