#!/usr/bin/env python3 # -*- coding: utf-8 -*- """check-contract-scan —— **契约 ↔ 代码** 对账扫描器。 🔴 为什么存在: `docs/contract.md` 的端点表原先是**散文表格**(§6.1–§6.5), 代码里的路由注册是**另一处**(`routes.rs` / `modules/*.rs`)⇒ 加端点、改路径、改守卫 ⇒ 契约与代码**各改各的** ⇒ 漂移没人发现。 本脚本把契约的机器可读区段 `[ENDPOINT]` / `[FACE]` 与**代码里真实注册的路由** 逐条对账,**双向**都查(契约多 / 代码多 / 方法不符 / 归属层不符 / 守卫不符)。 🔴 **只做静态检查**:不启动后端、不发请求。纯 `python3`(macOS 自带)。 用法: check-contract-scan.py --contract <契约文件> --src <后端 src 目录> check-contract-scan.py --self-test 输出协议(制表符分隔,逐行一条): CHECK\t\t\t<说明> WARN\t\t<说明> # 推不出守卫之类的「非失败但要看见」 退出码:0 = 扫完(可能有 DRIFT,看输出)/ 2 = 致命错误(契约读不出来等) """ import io import os import re import shutil import sys import tempfile HERE = os.path.dirname(os.path.abspath(__file__)) ROOT = os.path.dirname(HERE) if HERE not in sys.path: sys.path.insert(0, HERE) import contract_expect # noqa: E402 (同目录) # ---------------------------------------------------------------- Rust 源码扫描 # 路由注册:`.route("/api/x", get(handler))`(允许跨行) # 🔴 路径是**字符串字面量** ⇒ 在 masked 里是空白 ⇒ 只在 masked 里定位 `.route(`, # 再用**同一偏移**去原文取路径与方法。 ROUTE_CALL_RE = re.compile(r'\.route\(') # 路由后面的 handler 表达式:`sys::user_list` / `demo_item_list` / `|State(..)| ..`(闭包) HANDLER_RE = re.compile(r'\s*(?:([A-Za-z_][A-Za-z0-9_]*)::)?([A-Za-z_][A-Za-z0-9_]*)') # 契约表里 `{param}` ⇒ 代码里的通配 PARAM_RE = re.compile(r'\{[A-Za-z_][A-Za-z0-9_]*\}') # 测试用的固定路径前缀(**不在契约端点表里** ⇒ 全部扫描都排除) TEST_PATH_PREFIX = "/api/__test__/" def mask_rust(text): """把字符串字面量 / 注释**挖空**(保持长度不变)⇒ 结构扫描不会被注释/字面量骗。 挖空后拿到的偏移量与原文一一对应 ⇒ 需要字面量的值时,用同一偏移去原文里取。 """ out = list(text) n = len(text) def blank(a, b): for k in range(a, b): if out[k] != "\n": out[k] = " " i = 0 while i < n: c = text[i] if c == "/" and i + 1 < n and text[i + 1] == "/": j = text.find("\n", i) j = n if j < 0 else j blank(i, j) i = j continue if c == "/" and i + 1 < n and text[i + 1] == "*": depth, j = 1, i + 2 while j < n and depth: if text.startswith("/*", j): depth += 1 j += 2 elif text.startswith("*/", j): depth -= 1 j += 2 else: j += 1 blank(i, j) i = j continue if c == "r" and i + 1 < n and text[i + 1] in '#"': m = re.match(r'r(#*)"', text[i:]) if m: hashes = m.group(1) end = text.find('"' + hashes, i + m.end()) j = n if end < 0 else end + 1 + len(hashes) blank(i, j) i = j continue if c == '"': j = i + 1 while j < n: if text[j] == "\\": j += 2 continue if text[j] == '"': j += 1 break j += 1 blank(i, j) i = j continue if c == "'": m = re.match(r"'(\\.|[^\\'])'", text[i:]) if m: blank(i, i + m.end()) i += m.end() continue i += 1 # 生命周期(`'a`)不是字面量 ⇒ 留着 continue i += 1 return "".join(out) def read(path): with io.open(path, encoding="utf-8") as fh: return fh.read() def brace_span(masked, start): """从 `start`(`{` 的位置)开始做括号配对 ⇒ 返回 body 的 (开, 闭) 区间。""" depth = 0 i = start n = len(masked) while i < n: c = masked[i] if c == "{": depth += 1 elif c == "}": depth -= 1 if depth == 0: return start, i + 1 i += 1 return start, n def find_fn_body(masked, fname): """找 `fn (` 的函数体区间 ⇒ 返回 (start, end) 或 None。""" m = re.search(r"\bfn\s+" + re.escape(fname) + r"\s*\(", masked) if not m: return None i = masked.find("{", m.end()) if i < 0: return None return brace_span(masked, i) def scan_routes(path, owner): """扫一个源文件里的 `.route(...)` ⇒ [{path, method, handler_mod, handler_fn, closure}]。""" orig = read(path) masked = mask_rust(orig) out = [] for m in ROUTE_CALL_RE.finditer(masked): p = m.end() while p < len(orig) and orig[p] in " \t\r\n": p += 1 if p >= len(orig) or orig[p] != '"': continue q = p + 1 while q < len(orig) and orig[q] != '"': if orig[q] == "\\": q += 1 q += 1 if q >= len(orig): continue route = orig[p + 1:q] p = q + 1 while p < len(orig) and orig[p] in " \t\r\n": p += 1 if p < len(orig) and orig[p] == ",": p += 1 while p < len(orig) and orig[p] in " \t\r\n": p += 1 mm = re.match(r"(get|post|put|delete)\s*\(", orig[p:]) if not mm: continue if masked[p:p + len(mm.group(1))] != mm.group(1): continue # 方法名其实落在字符串里(误报) method = mm.group(1).upper() after = p + mm.end() if route.startswith(TEST_PATH_PREFIX): continue # 仅测试构建存在的端点 ⇒ 不在契约端点表里 rest = orig[after:after + 240] hm = HANDLER_RE.match(rest) mod, fn, closure = None, None, True if hm and hm.group(2): mod, fn = hm.group(1), hm.group(2) closure = False out.append({ "path": route, "method": method, "mod": mod, "fn": fn, "closure": closure, "owner": owner, "file": path, }) return out, orig, masked def resolve_const(orig, masked, name): """`const NAME: &str = "value";` ⇒ value(取原文里的字面量)。""" m = re.search(r"\bconst\s+" + re.escape(name) + r"\b[^=]*=\s*\"([^\"]*)\"", orig) return m.group(1) if m else None def guard_of_platform(plat_files, mod, fn): """平台层 handler 的守卫 ⇒ 菜单 key / 点权限编码 / 登录 / 无;推不出 ⇒ None。 `plat_files` = {"sys": (orig, masked), "jnpf": (orig, masked), ...} """ if mod == "auth" and fn == "login_handler": return "无" if mod is None: # routes.rs 里自己定义的 handler(如 `health`)⇒ 没有守卫调用 ⇒ 无 pair = plat_files.get("__routes__") if not pair: return None orig, masked = pair span = find_fn_body(masked, fn) if not span: return None body = masked[span[0]:span[1]] if re.search(r"require_(login|module|login_jnpf)\s*\(", body) or re.search(r"\bguard\s*\(", body): return None return "无" pair = plat_files.get(mod) if not pair: return None orig, masked = pair span = find_fn_body(masked, fn) if not span: return None body = masked[span[0]:span[1]] if mod == "sys": m = re.search(r"require_module\(\s*&state\s*,\s*&headers\s*,\s*([A-Z_][A-Z0-9_]*)\s*\)", body) if m: return resolve_const(orig, masked, m.group(1)) if re.search(r"require_login(_any)?\s*\(", body): return "登录" return None if mod == "jnpf": m = re.search(r"guard\(\s*&state\s*,\s*&headers\s*,\s*([A-Z_][A-Z0-9_]*)\s*\)", body) if m: return resolve_const(orig, masked, m.group(1)) if re.search(r"require_login_jnpf\s*\(", body): return "登录" return None return None def guard_of_closure(orig, masked, rest): """闭包 handler(只有 `CurrentUser` 一处)⇒ 看它调了谁。""" if "auth::current_user" in rest: return "登录" return None def guard_of_module(orig, masked): """业务模块的守卫 ⇒ 它的 `EntitySpec.module_key`(None ⇒ 仅登录)。 🔴 在 **masked** 里定位 `module_key:`(注释里的假 mention 被挖空了), 再用**同一偏移**去原文取真值(字面量在 masked 里是空格)。 """ for m in re.finditer(r"module_key:", masked): tail = orig[m.end():m.end() + 60] if re.match(r"\s*None", tail): return "登录" mm = re.match(r'\s*Some\(\s*"([^"]*)"\s*\)', tail) if mm: return mm.group(1) return None def parse_str_array(orig, masked, decl_re): """从 `const X: [&str; N] = [ "a", "b" ];` 里取字符串数组(原文字面量)。""" m = re.search(decl_re, masked) if not m: return None i = masked.find("[", m.end()) if i < 0: return None j = masked.find("]", i) if j < 0: return None return re.findall(r'"([^"]*)"', orig[i:j]) def path_to_regex(pattern): """`/a/{id}/b` ⇒ 正则(`{id}` 当通配)⇒ 用来对钉子测试里的具体路径。""" parts = [] last = 0 for m in PARAM_RE.finditer(pattern): parts.append(re.escape(pattern[last:m.start()])) parts.append("[^/]+") last = m.end() parts.append(re.escape(pattern[last:])) return re.compile("^" + "".join(parts) + "$") # ---------------------------------------------------------------- 对账 class Report(object): def __init__(self): self.checks = [] self.warns = [] self.infos = [] def add(self, cid, ok, detail): self.checks.append((cid, "OK" if ok else "DRIFT", detail)) def warn(self, cid, detail): self.warns.append((cid, detail)) def info(self, cid, detail): """**不计入 PASS/FAIL** 的进度信息(例:官方端点覆盖 N/M)。""" self.infos.append((cid, detail)) def lines(self): out = [] for cid, status, detail in self.checks: out.append("CHECK\t%s\t%s\t%s" % (cid, status, detail.replace("\t", " "))) for cid, detail in self.warns: out.append("WARN\t%s\t%s" % (cid, detail.replace("\t", " "))) for cid, detail in self.infos: out.append("INFO\t%s\t%s" % (cid, detail.replace("\t", " "))) return out def analyze(contract_path, src_dir): """契约 ↔ 代码 对账主体。返回 (Report, 诊断用数据)。""" rep = Report() sections = contract_expect.load_sections(contract_path) eps = sections["ENDPOINT"] faces = sections["FACE"] # ---- 代码侧:平台层 + 业务层 ---- routes_path = os.path.join(src_dir, "routes.rs") plat, plat_orig, plat_masked = scan_routes(routes_path, "platform") plat_dir = os.path.join(src_dir, "platform") plat_files = {"__routes__": (plat_orig, plat_masked)} if os.path.isdir(plat_dir): for name in sorted(os.listdir(plat_dir)): if name.endswith(".rs"): p = os.path.join(plat_dir, name) o = read(p) plat_files[name[:-3]] = (o, mask_rust(o)) mod_dir = os.path.join(src_dir, "modules") mod_files = [] if os.path.isdir(mod_dir): for name in sorted(os.listdir(mod_dir)): if name.endswith(".rs") and name != "mod.rs": mod_files.append((name[:-3], os.path.join(mod_dir, name))) biz = [] mod_orig = {} mod_masked = {} for app, path in mod_files: rs, orig, masked = scan_routes(path, app) biz.extend(rs) mod_orig[app] = orig mod_masked[app] = masked code = plat + biz code_index = {} for r in code: code_index.setdefault((r["method"], r["path"]), r) # ---- CC2 端点总数 ---- ok = len(eps) == len(code) rep.add("CC2", ok, "契约 %d 条 / 代码 %d 条" % (len(eps), len(code))) # ---- CC3 契约 → 代码(存在 + 方法一致)---- bad3 = [] for row in eps: key = (row["method"], row["path"]) if key in code_index: continue other = [k for k in code_index if k[1] == row["path"]] if other: bad3.append("%s %s:契约方法 %s,代码是 %s" % (row["method"], row["path"], row["method"], "/".join(k[0] for k in other))) else: bad3.append("%s %s:代码里没有这条路由" % (row["method"], row["path"])) rep.add("CC3", not bad3, "契约的 %d 条端点在代码里都能找到(且方法一致)" % len(eps) if not bad3 else "契约→代码 漂移 %d 条" % len(bad3)) for d in bad3: rep.warn("CC3", d) # ---- CC4 代码 → 契约(代码多出来的)---- bad4 = [] for r in code: if (r["method"], r["path"]) not in {(x["method"], x["path"]) for x in eps}: bad4.append("%s %s(%s)" % (r["method"], r["path"], r["owner"])) rep.add("CC4", not bad4, "代码里的 %d 条路由都在契约端点表里" % len(code) if not bad4 else "代码→契约 漂移 %d 条" % len(bad4)) for d in bad4: rep.warn("CC4", d) # ---- CC5 归属层 ---- bad5 = [] for row in eps: hit = code_index.get((row["method"], row["path"])) if hit and hit["owner"] != row["owner"]: bad5.append("%s %s:契约写 %s,代码在 %s" % (row["method"], row["path"], row["owner"], hit["owner"])) rep.add("CC5", not bad5, "每条端点的归属层与代码所在文件一致" if not bad5 else "归属层漂移 %d 条" % len(bad5)) for d in bad5: rep.warn("CC5", d) # ---- CC6 守卫 ---- bad6 = [] unknown6 = [] for row in eps: hit = code_index.get((row["method"], row["path"])) if not hit: continue derived = None if hit["owner"] == "platform": if hit["closure"]: tail = plat_orig[plat_orig.find(hit["path"]):][:400] derived = guard_of_closure(plat_orig, plat_masked, tail) else: derived = guard_of_platform(plat_files, hit["mod"], hit["fn"]) else: derived = guard_of_module(mod_orig[hit["owner"]], mod_masked[hit["owner"]]) if derived is None: unknown6.append("%s %s:推不出守卫" % (row["method"], row["path"])) elif derived != row["guard"]: bad6.append("%s %s:契约写 %s,代码是 %s" % (row["method"], row["path"], row["guard"], derived)) rep.add("CC6", not bad6, "每条端点的守卫与代码静态推导一致" if not bad6 else "守卫漂移 %d 条" % len(bad6)) for d in bad6: rep.warn("CC6", d) for d in unknown6: rep.warn("CC6", d + "(**推不出 ≠ 一致**,请人工核对)") # ---- CC7 钉子测试清单 ↔ 代码注册路由(双向覆盖)---- pins = [] for name in ("REGISTERED", "JNPF_REGISTERED"): arr = parse_str_array(plat_orig, plat_masked, r"const\s+" + name + r"\s*:\s*\[&str;\s*\d+\]\s*=") if arr is not None: pins.extend(arr) # 🔴 钉子测试的**字面量清单**(`REGISTERED` / `JNPF_REGISTERED`)只覆盖**平台层**路由; # 业务路由在钉子测试里是**遍历 `modules::ALL_ROUTES`** ⇒ 归 CC8 对账。 plat_routes = [r for r in code if r["owner"] == "platform"] unmatched_pin = [] for p in pins: if not any(path_to_regex(r["path"]).match(p) for r in plat_routes): unmatched_pin.append(p) unmatched_code = [] for r in plat_routes: if not any(path_to_regex(r["path"]).match(p) for p in pins): unmatched_code.append("%s %s" % (r["method"], r["path"])) ok7 = not unmatched_pin and not unmatched_code rep.add("CC7", ok7, "钉子测试的 %d 条路径与代码注册的 %d 条平台路由双向覆盖" % (len(pins), len(plat_routes)) if ok7 else "钉子测试清单与代码路由对不上:清单多 %d / 代码多 %d" % (len(unmatched_pin), len(unmatched_code))) for d in unmatched_pin: rep.warn("CC7", "钉子测试里的 %s 在代码里没有对应路由" % d) for d in unmatched_code: rep.warn("CC7", "代码里的 %s 没被钉子测试覆盖" % d) # ---- CC8 业务路由三处一致(ROUTES 常量 / router() / ALL_ROUTES)---- bad8 = [] all_routes = [] for app, path in mod_files: orig, masked = mod_orig[app], mod_masked[app] const = parse_str_array(orig, masked, r"pub\s+const\s+ROUTES\s*:\s*\[&str;\s*\d+\]\s*=") rs = [r for r in biz if r["owner"] == app] reg = [r["path"] for r in rs] if const is None: bad8.append("%s:没有 ROUTES 常量" % app) continue if const != reg: bad8.append("%s:ROUTES 常量 %s ≠ router() 注册 %s" % (app, const, reg)) all_routes.extend(const) # modules/mod.rs 的 ALL_ROUTES(形如 demo::ROUTES[0])⇒ 解析成具体路径 mod_mod = os.path.join(mod_dir, "mod.rs") if os.path.isfile(mod_mod): orig = read(mod_mod) masked = mask_rust(orig) m = re.search(r"pub\s+const\s+ALL_ROUTES\s*:\s*&\[&str\]\s*=\s*&\[", masked) if m: # 🔴 数组本体是 `&[ ... ]` ⇒ 要**配对**找结尾的 `]`(不能 find 第一个 `]`) open_at = masked.find("[", m.end() - 1) depth = 0 close_at = -1 for k in range(open_at, len(masked)): if masked[k] == "[": depth += 1 elif masked[k] == "]": depth -= 1 if depth == 0: close_at = k break entries = re.findall(r"([a-z_]+)::ROUTES\[(\d+)\]", orig[open_at:close_at]) resolved = [] for app, idx in entries: pair = (mod_orig.get(app, ""), mod_masked.get(app, "")) c = parse_str_array(pair[0], pair[1], r"pub\s+const\s+ROUTES\s*:\s*\[&str;\s*\d+\]\s*=") if c and int(idx) < len(c): resolved.append(c[int(idx)]) # 🔴 比**集合**不比你序(`mod_files` 是按文件名排序的,ALL_ROUTES 是按声明序的) if sorted(resolved) != sorted(all_routes): bad8.append("modules/mod.rs 的 ALL_ROUTES %s ≠ 各模块 ROUTES 拼接 %s" % (sorted(resolved), sorted(all_routes))) else: bad8.append("modules/mod.rs 里找不到 ALL_ROUTES") rep.add("CC8", not bad8, "业务路由三处一致(各模块 ROUTES 常量 / router() 注册 / ALL_ROUTES)" if not bad8 else "业务路由清单对不上 %d 处" % len(bad8)) for d in bad8: rep.warn("CC8", d) # ---- CC9 契约面计数自洽 ---- bad9 = [] for row in faces: actual = sum(1 for e in eps if e["face"] == row["face"]) if str(actual) != row["count"]: bad9.append("面 %s:契约 [FACE] 登记 %s 条,[ENDPOINT] 里实际 %d 条" % (row["face"], row["count"], actual)) total_face = sum(int(r["count"]) for r in faces) if total_face != len(eps): bad9.append("[FACE] 合计 %d ≠ [ENDPOINT] 行数 %d" % (total_face, len(eps))) rep.add("CC9", not bad9, "各契约面的条数与 [ENDPOINT] 自洽(A/B/AB 合计 %d)" % total_face if not bad9 else "契约面计数不自洽 %d 处" % len(bad9)) for d in bad9: rep.warn("CC9", d) # ---- CC10 官方端点台账 ↔ 代码真实路由(双向)---- # # 🔴 为什么要它:面 B 的「做了多少」原先只有**尺子的断言数**(18/18)这一个信号, # 而**官方端点全表**(JNPF_SOURCE_AUDIT.md §4)是**散文表格** ⇒ 官方端点做没做、 # 做到什么程度,**没有机器可读的账** ⇒ 「覆盖率」只能靠人读散文。 # 本检查把契约附录 A 的 [OFFICIAL](机器可读)当成**账本**, # 与代码里**真实注册**的路由双向对账,并打印覆盖 N/M。 off = sections["OFFICIAL"] def norm_path(p): # `{param}` 归一 ⇒ 官方台账与代码的**参数名不同**也不算漂移 return re.sub(r"\{[^/{}]*\}", "{}", p) code_norm = {} for r in code: code_norm.setdefault((r["method"], norm_path(r["path"])), r) eps_face = {} for e in eps: eps_face[(e["method"], norm_path(e["path"]))] = e["face"] bad10 = [] counts = {"implemented": 0, "partial": 0, "absent": 0, "oos": 0} for row in off: method, path, status = row["method"], row["path"], row["status"] if status not in counts: bad10.append("台账状态非法 %r(%s %s)" % (status, method, path)) continue if method == "*" or path.endswith("/**"): # 「一族端点」的范围声明(如数据权限链接)⇒ 不做存在性对账,只计入 oos counts["oos"] += 1 continue hit = code_norm.get((method, norm_path(path))) if status in ("implemented", "partial"): counts[status] += 1 if hit is None: bad10.append("台账写 %s(%s %s),代码里**没有**这条路由" % (status, method, path)) else: counts[status] += 1 if hit is not None: bad10.append("台账写 %s(%s %s),代码里却**注册了**这条路由" % (status, method, path)) # 反向:代码里**面 B / 共用**的每条路由,都必须在台账里**有账**(防止"实现了但没记账") off_index = set((r["method"], norm_path(r["path"])) for r in off if r["method"] != "*") for r in code: key = (r["method"], norm_path(r["path"])) if eps_face.get(key) in ("B", "AB") and key not in off_index: bad10.append("代码注册了面 %s 路由 %s %s,但官方端点台账里**没有这一条**" % (eps_face.get(key), r["method"], r["path"])) covered = counts["implemented"] + counts["partial"] total = covered + counts["absent"] rep.add("CC10", not bad10, "官方端点台账与代码真实路由双向对得上(已落地 %d / 在范围 %d)" % (covered, total) if not bad10 else "官方端点台账漂移 %d 处" % len(bad10)) for d in bad10: rep.warn("CC10", d) rep.info("CC10-COVER", "官方端点覆盖 %d/%d(implemented %d / partial %d / absent %d;oos %d 单列,不进分母)" % (covered, total, counts["implemented"], counts["partial"], counts["absent"], counts["oos"])) return rep # ---------------------------------------------------------------- 反自证 def self_test(): """🔴 **反自证**:造几种已知漂移 ⇒ 必须被抓到;再验一遍真实契约**没有**漂移。 永远返回「干净」的尺子 = 没有尺子 ⇒ 这一段是尺子可信的前提。 """ contract = os.path.join(ROOT, "docs", "contract.md") src_dir = os.path.join(ROOT, "src", "backend", "src") if not os.path.isfile(contract): sys.stderr.write("check-contract-scan: 找不到契约 %s\n" % contract) return 2 base = analyze(contract, src_dir) drifts = [c for c in base.checks if c[1] == "DRIFT"] if drifts: for cid, _s, detail in drifts: sys.stderr.write("check-contract-scan: 真实契约就有漂移(%s: %s)\n" % (cid, detail)) return 1 with io.open(contract, encoding="utf-8") as fh: text = fh.read() def mutate(fn): return fn(text) cases = [] def add_row(t): return t.replace("[ENDPOINT]\n", "[ENDPOINT]\nA\tGET\t/api/zzz/Fake/List\t登录\tplatform\n", 1) def drop_row(t): return t.replace("A\tGET\t/api/health\t无\tplatform\n", "", 1) def bad_method(t): return t.replace("A\tGET\t/api/health\t无\tplatform\n", "A\tPOST\t/api/health\t无\tplatform\n", 1) def bad_guard(t): return t.replace("A\tGET\t/api/ssw/sys/User/List\tsystem/User\tplatform\n", "A\tGET\t/api/ssw/sys/User/List\t登录\tplatform\n", 1) def bad_owner(t): return t.replace("A\tGET\t/api/ssw/demo/DemoItem/List\t登录\tdemo\n", "A\tGET\t/api/ssw/demo/DemoItem/List\t登录\tplatform\n", 1) def bad_face(t): # 🔴 **动态取现值再减 1**(别写死数字):加端点会让 [FACE] 的 A 条数变化, # 写死的锚点会过期 ⇒ 反自证用例静默失效(「改不动契约」)。 m = re.search(r"(?m)^A\t(\d+)\t", t) if not m: return t return t[: m.start(1)] + str(int(m.group(1)) - 1) + t[m.end(1):] # ---- CC10 的三类漂移(官方端点台账 ↔ 代码真实路由)---- def off_says_absent(t): # 台账把「代码里有」的端点说成未实现 return t.replace( "GET\t/api/permission/Users\timplemented\t", "GET\t/api/permission/Users\tabsent\t", 1) def off_fake_path(t): # 台账说已实现,但那条路径代码里根本没有 return t.replace( "GET\t/api/system/Menu/ModuleBySystem\timplemented\t", "GET\t/api/system/Menu/ModuleBySystemXX\timplemented\t", 1) def off_drop_row(t): # 代码里有面 B 路由,但台账里没记账("实现了但没记账") return t.replace( "GET\t/api/permission/Role\timplemented\tRoleController.java:99-100\t" "面 B 已落地:PageListVO 形状\n", "", 1) cases.append(("契约多一条端点", add_row, "CC3")) cases.append(("契约少一条端点", drop_row, "CC2")) cases.append(("方法写错", bad_method, "CC3")) cases.append(("守卫写错", bad_guard, "CC6")) cases.append(("归属层写错", bad_owner, "CC5")) cases.append(("契约面计数写错", bad_face, "CC9")) cases.append(("台账把已实现的端点说成未实现", off_says_absent, "CC10")) cases.append(("台账写了代码里没有的端点", off_fake_path, "CC10")) cases.append(("面 B 路由没记账", off_drop_row, "CC10")) failed = 0 for name, fn, expect in cases: mutated = mutate(fn) if mutated == text: sys.stderr.write("check-contract-scan: 反自证用例「%s」改不动契约(锚点没了)\n" % name) failed += 1 continue tmpdir = tempfile.mkdtemp(prefix="cc-selftest-") tmp = os.path.join(tmpdir, "contract.md") with io.open(tmp, "w", encoding="utf-8") as fh: fh.write(mutated) try: rep = analyze(tmp, src_dir) except Exception as exc: # noqa: BLE001 sys.stderr.write("check-contract-scan: 反自证用例「%s」分析异常:%s\n" % (name, exc)) failed += 1 continue finally: shutil.rmtree(tmpdir, ignore_errors=True) hit = [c for c in rep.checks if c[0] == expect and c[1] == "DRIFT"] if hit: print(" ✅ 反自证「%s」被 %s 抓到" % (name, expect)) else: print(" ❌ 反自证「%s」**没**被 %s 抓到(尺子被改弱了?)" % (name, expect)) failed += 1 if failed: sys.stderr.write("check-contract-scan: 反自证失败 %d 例\n" % failed) return 1 print("反自证 %d 例全部通过(真实契约零漂移 + 每种注入漂移都被抓到)" % len(cases)) return 0 def main(argv): if "--self-test" in argv: return self_test() contract = os.path.join(ROOT, "docs", "contract.md") src_dir = os.path.join(ROOT, "src", "backend", "src") i = 1 while i < len(argv): if argv[i] == "--contract" and i + 1 < len(argv): contract = argv[i + 1] i += 2 continue if argv[i] == "--src" and i + 1 < len(argv): src_dir = argv[i + 1] i += 2 continue sys.stderr.write("check-contract-scan: 未知参数 %r\n" % argv[i]) return 2 try: rep = analyze(contract, src_dir) except contract_expect.ContractError as exc: sys.stderr.write("check-contract-scan: %s\n" % exc) return 2 for line in rep.lines(): print(line) return 0 if __name__ == "__main__": sys.exit(main(sys.argv))