- axum 0.8 + pglite:12 张表,多应用按 App-Code 头解析 f_system_id 隔离 - 面 A(ssw/react 形状)+ 面 B(官方 JNPF 形状,Vue-Version: 3)双契约并存 - 业务模块 asset/DataResource;面 B 用户 CRUD 9 条已落地 - 六道闸门 + 两把运行时尺子(perm-smoke 43 / perm-smoke-jnpf 23) - scripts/:前端接口清单、页面依赖反查、运行时探针
165 lines
6.4 KiB
Python
165 lines
6.4 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` 里还有大量「期望路径」字符串
|
||
# 数组(自检用),照收会把未实现的路由误判成已实现。
|
||
lines = text.splitlines()
|
||
for i, line in enumerate(lines):
|
||
if "route(" not in line:
|
||
continue
|
||
window = "\n".join(lines[i : i + 4])
|
||
m = ROUTE_LIT.search(window)
|
||
if not m:
|
||
continue
|
||
path = m.group(1)
|
||
mm = METHOD_CALL.search(window[m.end() :])
|
||
if not mm:
|
||
warns.append(f"{f.relative_to(ROOT)}:{i + 1} 路径 {path} 找不到方法")
|
||
continue
|
||
found.add((mm.group(1).upper(), 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())
|