Files
ssw-platform/scripts/contract_expect.py
T
admin ce30c5b2f6 feat(pack): 框架固定包 + 加模块一条命令(批次 12 + 12.5)
把「内核怎么知道有这个包」从手写改成生成,漏接直接报错而不是静默 404。

- crates/sspf-plugin:load_static() 收掉装配样板,bootstrap 的 load_packs 缩成一行

- 包统一出口:pub struct Pack + pub const DDLS(生成器不必理解各包常量命名)

- 业务 DDL 跟包走(packs/*/schema/*.sql 经 include_str! 编进二进制)

- packs_gen.rs / modules/mod.rs 5 段 / Cargo.toml / contract.md 三段改由 pack-sync.py 生成

- scripts/new-pack.sh:一条命令产出 5 个后端文件 + 接线 + 可选前端三件套

- scripts/verify.sh 静态闸门一键跑;.workbuddy 记忆与 HANDOFF 见下一提交
2026-11-01 23:04:53 +08:00

234 lines
9.5 KiB
Python
Executable File
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 -*-
"""contract_expect —— 读 `docs/contract.md` 里的**机器可读期望值**区段。
🔴 为什么存在:
期望值(菜单表 / 菜单树 / 业务模块清单 / 各尺子的断言数)原先散落在
**契约文档(散文表格)+ 尺子脚本(硬编码)** 两处 ⇒ 改一处忘另一处 ⇒ 漂移。
本脚本把 `docs/contract.md` 附录 A 的 `<!-- BEGIN CONTRACT-EXPECT -->` 块
解析成结构化数据,**所有尺子都从那里读期望值** ⇒ 单一真源 + 自动对账。
用法:
contract_expect.py sections # 列出所有区段名
contract_expect.py dump # 打印全部(调试用)
contract_expect.py rows <SECTION> # 打印整段(表头行 + 数据行,制表符分隔)
contract_expect.py menu-tree # 期望菜单树字符串(一行)
contract_expect.py menu <id> <column> # 某菜单的某列
contract_expect.py module <app> <column> # 某业务模块的某列
contract_expect.py endpoint <path> <column> # 某端点的某列
contract_expect.py endpoints # 全部端点(method\tpath)
contract_expect.py face <name> <column> # 某契约面的某列
contract_expect.py official # 官方端点台账全表(method/path/status/src/note)
contract_expect.py official-coverage # 官方端点覆盖 N/M(+ implemented/partial/absent/oos 计数)
contract_expect.py ruler <name> # 某把尺子的期望断言数
退出码:0 = 查到 / 2 = 契约里没有这一项(🔴 绝**不**返回空串冒充「查到了」)
"""
import io
import os
import sys
BEGIN = "<!-- BEGIN CONTRACT-EXPECT"
END = "<!-- END CONTRACT-EXPECT"
FENCE = "```"
HERE = os.path.dirname(os.path.abspath(__file__))
ROOT = os.path.dirname(HERE)
CONTRACT = os.path.join(ROOT, "docs", "contract.md")
# 区段 → (行键列, 列名列表);列名与契约附录 A 的表头注释一一对应。
# None 表示该区段没有「行键列」(整行就是值,例如 MENU_TREE)。
SCHEMAS = {
"MENU": (0, ["id", "fullName", "enCode", "urlAddress", "parentId", "type", "icon", "sortCode"]),
"MENU_TREE": (None, ["value"]),
"MODULE": (0, ["app", "entity", "table", "urlAddress", "moduleKey", "menuId", "apiFile", "rsFile"]),
"ENDPOINT": (2, ["face", "method", "path", "guard", "owner"]),
"FACE": (0, ["face", "count", "desc"]),
"OFFICIAL": (1, ["method", "path", "status", "src", "note"]),
"RULER": (0, ["name", "assertions"]),
}
# 🔴 [OFFICIAL] 的状态词表(**穷举**)—— 写错状态码尺子会直接判失败。
OFFICIAL_STATUS = ("implemented", "partial", "absent", "oos")
def die(msg, code=2):
sys.stderr.write("contract_expect: %s\n" % msg)
sys.exit(code)
class ContractError(Exception):
"""契约读不出来(库用法;CLI 侧转成 `die` ⇒ 退出码 2)。"""
def load_sections(path=None):
"""解析契约文件 ⇒ {SECTION: [ {col: value, ...}, ... ]}。
`path` 给定时读那个文件(`check-contract-scan.py` 的反自证要读改坏的副本)。
"""
contract = path or CONTRACT
if not os.path.isfile(contract):
raise ContractError("找不到契约文件 %s" % contract)
with io.open(contract, encoding="utf-8") as fh:
text = fh.read()
i = text.find(BEGIN)
if i < 0:
raise ContractError("契约里没有 %s 标记(期望值区段缺失 ⇒ 尺子无法对账)" % BEGIN)
j = text.find(END, i)
if j < 0:
raise ContractError("契约里没有 %s 标记(期望值区段未闭合)" % END)
chunk = text[i:j]
# 只取标记之后**第一个**围栏代码块的内容。
f1 = chunk.find(FENCE)
if f1 < 0:
raise ContractError("期望值区段里没有围栏代码块")
body_start = chunk.find("\n", f1) + 1
f2 = chunk.find(FENCE, body_start)
if f2 < 0:
raise ContractError("期望值区段里的围栏代码块没有闭合")
body = chunk[body_start:f2]
sections = {}
cur = None
for raw in body.split("\n"):
line = raw.rstrip("\r")
if not line.strip():
continue
if line.lstrip().startswith("#"):
continue # 注释行
# 🔴 **HTML 注释行**(`<!-- PACK:BEGIN -->` / `<!-- PACK:END -->`):
# `scripts/pack-sync.py` 用它包住**生成段**(批次 12 交付物 ④)。
# ⇒ 必须在这里跳过,否则它会被当成「只有 1 列的数据行」⇒
# 列数校验立刻抛 `ContractError` ⇒ **整把尺子读不出契约**。
if line.lstrip().startswith("<!--"):
continue
if line.startswith("["):
name = line[1:line.index("]")].strip()
if name not in SCHEMAS:
raise ContractError("未知区段 [%s](已知:%s)" % (name, ", ".join(sorted(SCHEMAS))))
cur = name
sections.setdefault(cur, [])
continue
if cur is None:
raise ContractError("区段外的非注释行:%r" % line)
cols = line.split("\t")
key_col, names = SCHEMAS[cur]
if key_col is None:
sections[cur].append({names[0]: "\t".join(cols)})
continue
if len(cols) != len(names):
raise ContractError("区段 [%s] 的行 %r 有 %d 列,期望 %d 列(%s)"
% (cur, line, len(cols), len(names), "/".join(names)))
sections[cur].append(dict(zip(names, cols)))
for name in SCHEMAS:
if name not in sections:
raise ContractError("期望值区段缺 [%s](契约文件不完整)" % name)
return sections
def pick(sections, section, key, column):
key_col, names = SCHEMAS[section]
if column not in names:
die("区段 [%s] 没有列 %r(已知:%s)" % (section, column, "/".join(names)))
for row in sections[section]:
if key_col is None:
if key in ("", "-", "*"):
return row[names[0]]
continue
if row[names[key_col]] == key:
return row[column]
die("区段 [%s] 里没有 %r=%r" % (section, names[key_col] if key_col is not None else "key", key))
def main(argv):
if len(argv) < 2:
die("用法见文件头注释")
cmd = argv[1]
try:
sections = load_sections()
except ContractError as exc:
die(str(exc))
if cmd == "sections":
for name in sorted(sections):
print(name)
return 0
if cmd == "dump":
for name in sorted(sections):
print("[%s]" % name)
for row in sections[name]:
print("\t".join(row[n] for n in SCHEMAS[name][1]))
print("")
return 0
if cmd == "menu-tree":
print(pick(sections, "MENU_TREE", "", "value"))
return 0
if cmd == "rows":
# 打印整个区段(**表头行 + 数据行**,制表符分隔)⇒ bash 侧一次调用取全表。
if len(argv) != 3:
die("用法:contract_expect.py rows <SECTION>")
sec = argv[2]
if sec not in SCHEMAS:
die("未知区段 %r(已知:%s)" % (sec, ", ".join(sorted(SCHEMAS))))
names = SCHEMAS[sec][1]
print("\t".join(names))
for row in sections[sec]:
print("\t".join(row[n] for n in names))
return 0
if cmd == "menu":
if len(argv) != 4:
die("用法:contract_expect.py menu <id> <column>")
print(pick(sections, "MENU", argv[2], argv[3]))
return 0
if cmd == "module":
if len(argv) != 4:
die("用法:contract_expect.py module <app> <column>")
print(pick(sections, "MODULE", argv[2], argv[3]))
return 0
if cmd == "endpoint":
if len(argv) != 4:
die("用法:contract_expect.py endpoint <path> <column>")
print(pick(sections, "ENDPOINT", argv[2], argv[3]))
return 0
if cmd == "endpoints":
for row in sections["ENDPOINT"]:
print("%s\t%s" % (row["method"], row["path"]))
return 0
if cmd == "face":
if len(argv) != 4:
die("用法:contract_expect.py face <name> <column>")
print(pick(sections, "FACE", argv[2], argv[3]))
return 0
if cmd == "official":
# 官方端点台账全表(method / path / status / src / note)
for row in sections["OFFICIAL"]:
print("\t".join(row[n] for n in SCHEMAS["OFFICIAL"][1]))
return 0
if cmd == "official-coverage":
# 「已落地 / 在范围总数」+ oos 单列(oos 不进分母:v1 明确不做)
n = {"implemented": 0, "partial": 0, "absent": 0, "oos": 0}
for row in sections["OFFICIAL"]:
st = row["status"]
if st not in n:
die("[OFFICIAL] 里有非法状态 %r(合法:%s)" % (st, "/".join(OFFICIAL_STATUS)))
n[st] += 1
covered = n["implemented"] + n["partial"]
total = covered + n["absent"]
print("%d/%d\t%d\t%d\t%d\t%d"
% (covered, total, n["implemented"], n["partial"], n["absent"], n["oos"]))
return 0
if cmd == "ruler":
if len(argv) != 3:
die("用法:contract_expect.py ruler <name>")
print(pick(sections, "RULER", argv[2], "assertions"))
return 0
die("未知命令 %r(可用:sections / dump / menu-tree / menu / module / endpoint / endpoints / face / official / official-coverage / ruler)" % cmd)
if __name__ == "__main__":
sys.exit(main(sys.argv))