基准数据类型/控件映射/数据库/字段类型映射/常用字段的增删改查 + getKeyList + 数据同步四条 + 接口变量下拉;新表 base_data_type_mapping / base_data_base / base_data_type_relation / base_data_interface_variate(官方 DDL 逐字)⇒ tables 57。 影响:dataCenter 五个页面能真跑;数据同步四条明确拒绝(本仓内嵌单库,无驱动层), 不再假装成功。回归测试 tests/batch14_it.rs 7 条。 五族形状一致 ⇒ 抽了声明式 Flat(一份声明 + 五个薄壳),不再逐族手抄。 过程中修掉扫描器两个同源缺陷:check-contract-scan / fe-gap 都只认每条 .route() 的**第一个**方法 ⇒ 链式 get().post() 的后半段静默消失(契约写 implemented、 代码被判「没有这条路由」)。现在按 .route( 切块取全部方法。 写路径的两处语义也一并钉住:判重是「每列各自唯一」不是「联合唯一」; 列表把 typeId 覆盖成名称而详情必须返回真 id。
168 lines
6.7 KiB
Python
168 lines
6.7 KiB
Python
#!/usr/bin/env python3
|
||
"""fe-gap.py —— 前端接口清单 × 后端路由表 的**差距报告**。
|
||
|
||
用途:驱动「从 web 端逐个 API 突破」。输入是 `scripts/fe-api-inventory.py` 产出的
|
||
`docs/fe/endpoints.tsv`(前端声明了什么),对照后端 `src/backend/src/routes.rs` +
|
||
`src/backend/src/modules/*.rs` 里**真实注册**的路由(后端实现了什么),输出缺口。
|
||
|
||
用法:
|
||
python3 scripts/fe-gap.py # 汇总:按 api 目录给出 已实现/缺口
|
||
python3 scripts/fe-gap.py --module permission # 明细:某个目录的逐条缺口
|
||
python3 scripts/fe-gap.py --tsv out.tsv # 明细全量导出
|
||
|
||
判定口径(**故意保守**):
|
||
- 路径参数一律归一成 `{}`:前端 `{param}` / `:id` / `${x}`、后端 `{id}` 都算同一段。
|
||
- 面 A(`/api/ssw/...`)**不参与**比对——它是本项目自研契约,前端不用。
|
||
- 后端 **catch-all**(`/api/{}/{}/{}`)不算实现,否则会把所有缺口掩盖成 0。
|
||
- 方法不同即不同端点(`GET`/`POST`/`PUT`/`DELETE` 分别判定)。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import argparse
|
||
import collections
|
||
import pathlib
|
||
import re
|
||
import sys
|
||
|
||
ROOT = pathlib.Path(__file__).resolve().parent.parent
|
||
ENDPOINTS = ROOT / "docs" / "fe" / "endpoints.tsv"
|
||
BACKEND_SRC = ROOT / "src" / "backend" / "src"
|
||
|
||
# 后端路由字面量:`"/api/..."` 后面紧跟方法(同一条 `.route(` 链上)
|
||
ROUTE_LIT = re.compile(r'"(/api/[^"]*)"')
|
||
# 同一 `.route(` 调用里出现的方法
|
||
METHOD_CALL = re.compile(r"\b(get|post|put|delete|patch)\s*\(")
|
||
PARAM_SEG = re.compile(r"\{[^/}]*\}|:[A-Za-z_][A-Za-z0-9_]*|\$\{[^}]*\}")
|
||
|
||
|
||
def norm(path: str) -> str:
|
||
"""把路径参数归一成 `{}`,去掉尾部 `/`,小写化方法无关部分。"""
|
||
path = path.split("?")[0].strip()
|
||
path = PARAM_SEG.sub("{}", path)
|
||
return path.rstrip("/") or "/"
|
||
|
||
|
||
def read_endpoints() -> list[tuple[str, str, str, str]]:
|
||
if not ENDPOINTS.exists():
|
||
sys.exit(f"缺少 {ENDPOINTS};先跑 scripts/fe-api-inventory.py")
|
||
rows = []
|
||
with ENDPOINTS.open(encoding="utf-8") as fh:
|
||
header = fh.readline()
|
||
if not header.startswith("METHOD"):
|
||
sys.exit(f"{ENDPOINTS} 首行不是表头:{header!r}")
|
||
for line in fh:
|
||
parts = line.rstrip("\n").split("\t")
|
||
if len(parts) < 4:
|
||
continue
|
||
method, path, func, where = parts[0], parts[1], parts[2], parts[3]
|
||
rows.append((method.upper(), path, func, where))
|
||
return rows
|
||
|
||
|
||
def read_backend() -> tuple[set[tuple[str, str]], list[str]]:
|
||
"""扫后端全部 .rs,抽出 (METHOD, 归一化路径)。返回 (集合, 警告)。"""
|
||
found: set[tuple[str, str]] = set()
|
||
warns: list[str] = []
|
||
files = list(BACKEND_SRC.rglob("*.rs"))
|
||
for f in files:
|
||
text = f.read_text(encoding="utf-8", errors="replace")
|
||
# 只认**真正注册**的那些:以含 `route(` 的行为锚,往后看 3 行(覆盖
|
||
# `.route(\n "/api/x",\n get(h),\n)` 这种折行写法)。
|
||
# 🔴 不能见 `"/api/..."` 就收 —— `routes.rs` 里还有大量「期望路径」字符串
|
||
# 数组(自检用),照收会把未实现的路由误判成已实现。
|
||
# 🔴 按 `.route(` **切块**再逐块取路径与方法:一条 `.route()` 里可以链多个方法
|
||
# (`.route(p, get(a).post(b))` —— axum 同一个 path 只准注册一次,所以
|
||
# 「列表 GET + 新建 POST」必然链在一起)。
|
||
# 旧实现只看 4 行窗口里的**第一个**方法 ⇒ 后半段方法被漏掉,
|
||
# 已实现的端点仍被报成缺口。
|
||
for chunk in text.split(".route(")[1:]:
|
||
m = ROUTE_LIT.search(chunk)
|
||
if not m:
|
||
continue
|
||
path = m.group(1)
|
||
rest = chunk[m.end() :]
|
||
methods = {mm.group(1).upper() for mm in METHOD_CALL.finditer(rest)}
|
||
if not methods:
|
||
warns.append(f"{f.relative_to(ROOT)} 路径 {path} 找不到方法")
|
||
continue
|
||
for meth in methods:
|
||
found.add((meth, norm(path)))
|
||
return found, warns
|
||
|
||
|
||
def main() -> int:
|
||
ap = argparse.ArgumentParser()
|
||
ap.add_argument("--module", help="只看某个 api 子目录,如 permission")
|
||
ap.add_argument("--tsv", help="把明细写到文件")
|
||
ap.add_argument("--only-missing", action="store_true", help="明细里只列缺口")
|
||
args = ap.parse_args()
|
||
|
||
eps = read_endpoints()
|
||
impl, warns = read_backend()
|
||
|
||
for w in warns:
|
||
print(f"⚠ {w}", file=sys.stderr)
|
||
|
||
rows = []
|
||
for method, path, func, where in eps:
|
||
if path.startswith("/api/ssw/"):
|
||
continue # 面 A,前端不用
|
||
mod = where.split("/")[1] if "/" in where else where
|
||
key = (method, norm(path))
|
||
# catch-all 不算实现
|
||
hit = key in impl or (method, "{}") in impl
|
||
rows.append(
|
||
{
|
||
"module": mod,
|
||
"method": method,
|
||
"path": path,
|
||
"func": func,
|
||
"where": where,
|
||
"impl": hit,
|
||
}
|
||
)
|
||
|
||
if args.module:
|
||
rows = [r for r in rows if r["module"] == args.module]
|
||
|
||
# ---- 汇总 ----
|
||
agg: dict[str, list[int]] = collections.defaultdict(lambda: [0, 0])
|
||
for r in rows:
|
||
agg[r["module"]][0 if r["impl"] else 1] += 1
|
||
agg[r["module"]][1 if r["impl"] else 0] += 0
|
||
print(f"{'模块':<14}{'已实现':>7}{'缺口':>7}{'合计':>7} 完成度")
|
||
print("-" * 48)
|
||
tot_i = tot_g = 0
|
||
for mod in sorted(agg, key=lambda m: -(agg[m][0] + agg[m][1])):
|
||
# agg[mod] = [命中数, 未命中数] 需重算
|
||
i = sum(1 for r in rows if r["module"] == mod and r["impl"])
|
||
g = sum(1 for r in rows if r["module"] == mod and not r["impl"])
|
||
tot_i += i
|
||
tot_g += g
|
||
tot = i + g
|
||
pct = 100.0 * i / tot if tot else 0.0
|
||
print(f"{mod:<14}{i:>7}{g:>7}{tot:>7} {pct:5.1f}%")
|
||
print("-" * 48)
|
||
tot = tot_i + tot_g
|
||
print(f"{'合计':<14}{tot_i:>7}{tot_g:>7}{tot:>7} {100.0 * tot_i / tot if tot else 0:5.1f}%")
|
||
|
||
if args.tsv:
|
||
out = pathlib.Path(args.tsv)
|
||
with out.open("w", encoding="utf-8") as fh:
|
||
fh.write("MODULE\tMETHOD\tPATH\tFUNC\tWHERE\tIMPL\n")
|
||
for r in rows:
|
||
if args.only_missing and r["impl"]:
|
||
continue
|
||
fh.write(
|
||
f"{r['module']}\t{r['method']}\t{r['path']}\t{r['func']}\t{r['where']}\t"
|
||
f"{'Y' if r['impl'] else 'N'}\n"
|
||
)
|
||
print(f"\n明细已写 {out}({sum(1 for r in rows if not r['impl'])} 条缺口)")
|
||
|
||
return 0
|
||
|
||
|
||
if __name__ == "__main__":
|
||
raise SystemExit(main())
|