Files
pricing_review/test/界面体检/清单差异.py

107 lines
3.9 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""功能清单(主人填写).md 版本存档与差异工具(零依赖)。
规矩(2026-10-20 主人定):
- 只保留一份主人的上一版:版本存档/上一版.md(永远只有这一份,不按次数累积)
- 只保留一份差异:版本存档/差异.md(每次覆盖)
- 对 功能清单(主人填写).md 只读,绝不写入
用法:
python 清单差异.py # 读取:与上一版.md 对比 → 打印/存差异 → 把当前版覆盖为新的上一版
python 清单差异.py 快照 # 快照:不对比,直接把当前版覆盖为上一版
"""
import sys, json, hashlib, difflib
from datetime import datetime
from pathlib import Path
try:
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
except Exception:
pass
HERE = Path(__file__).resolve().parent
TARGET = HERE / "功能清单(主人填写).md"
ARC = HERE / "版本存档"
PREV = ARC / "上一版.md"
DIFF = ARC / "差异.md"
MAN = ARC / "manifest.json"
DIFF_CAP = 300
def sha256(p: Path) -> str:
return hashlib.sha256(p.read_bytes()).hexdigest()
def save_man(now, cur, note=""):
m = {"v": 2, "hash_algo": "sha256", "last_snapshot": PREV.name,
"last_hash": cur, "updated": now.strftime("%Y-%m-%d %H:%M"), "note": note}
MAN.write_text(json.dumps(m, ensure_ascii=False, indent=1), encoding="utf-8")
def heading_of(lines, pos):
for i in range(min(pos, len(lines)) - 1, -1, -1):
s = lines[i].lstrip()
if s.startswith("#"):
return s.strip()[:70]
return "(文件头)"
def render_diff(old_lines, new_lines):
out, n = [], 0
sm = difflib.SequenceMatcher(a=old_lines, b=new_lines, autojunk=False)
for tag, i1, i2, j1, j2 in sm.get_opcodes():
if tag == "equal":
continue
n += 1
out.append(f"\n@@ 差异{n}|旧L{i1+1}-L{i2} → 新L{j1+1}-L{j2}|{heading_of(new_lines, j1)}")
out.extend(" - " + l for l in old_lines[i1:i2])
out.extend(" + " + l for l in new_lines[j1:j2])
if n >= DIFF_CAP:
out.append(f"...(差异处超 {DIFF_CAP},截断)")
break
if not n:
out.append("(内容零差异——仅哈希基准不同)")
return "\n".join(out)
def main():
mode = "快照" if (len(sys.argv) > 1 and "快" in sys.argv[1]) else "读取"
if not TARGET.exists():
sys.exit(f"找不到 {TARGET}")
ARC.mkdir(exist_ok=True)
cur = sha256(TARGET)
now = datetime.now()
if mode == "快照" or not PREV.exists():
PREV.write_bytes(TARGET.read_bytes())
save_man(now, cur, "快照" if mode == "快照" else "首个基线")
print(f"[{'快照' if mode == '快照' else '首个基线'}] 已存 {PREV.name}({cur[:12]}…)"
+ (";下次改动可出差异。" if mode != "快照" else "。"))
return
prev_hash = sha256(PREV)
if prev_hash == cur:
save_man(now, cur, "无变化")
print(f"功能清单无变化({cur[:12]}…,对比 {PREV.name})。")
return
old_txt = PREV.read_text(encoding="utf-8", errors="replace").splitlines()
new_txt = TARGET.read_text(encoding="utf-8", errors="replace").splitlines()
txt = render_diff(old_txt, new_txt)
print(f"[读取] 新旧哈希 {prev_hash[:12]}… → {cur[:12]}…,差异如下:")
print(txt)
DIFF.write_text(
f"# 功能清单差异({now.strftime('%Y-%m-%d %H:%M')})\n\n"
f"- 上一版:`{PREV.name}`({prev_hash[:12]}…)\n"
f"- 本次:`功能清单(主人填写).md`({cur[:12]}…)\n\n{txt}\n",
encoding="utf-8")
# 只留一份:当前版覆盖上一版;差异已在 差异.md
PREV.write_bytes(TARGET.read_bytes())
save_man(now, cur, "有差异,上一版已更新")
print(f"[存档] 差异已存 {DIFF.name};{PREV.name} 已更新为当前版(只留一份)。")
if __name__ == "__main__":
main()