Files
ssw-platform/scripts/gen-function-catalog.py
T
admin 94d05f4649 refactor(arch): M2 平台核心下沉 —— 19 模块迁入 crates/sspf-core + 闸门扫真源
平台能力全迁 crates/ 迁移计划第 2 批(docs/CRATES-MIGRATION.md,基线 tag v0.1.0)。
本批次 = M2:平台核心从 src/backend/src/platform/ 下沉到 crates/sspf-core/。

搬迁:
- 19 个模块 git mv 进 crates/sspf-core/src/(保留历史):
  auth/authorization/cipher/config/crud/db/entity/envelope/guard/ids/menu/
  monitor/registry/route/seed/session/state/sys/variate_catalog
- src/backend/src/platform/*.rs 全改成 pub use sspf_core::<mod>::* 转发壳(5 行/个)
  ⇒ 上层零感知:routes / modules / 695 个测试的 import 一个没改
- crate 内路径改写 crate::platform::X → crate::X(compat 除外,那是 M3/M4)
- pub(crate) → pub(10 处,跨 crate 后失效)

闸门改造(🔴 本批最大风险不是代码是闸门 —— 搬迁后闸门扫空壳 = 虚假安全感):
- 纪律 = 「两处都扫」:真源 crates/sspf-core/src/(管实现)+ 转发壳(防塞私货)
- check-arch.sh AR9/AR10 扫两处;反自证 2/6、5/6 两处注入探针且按路径分别验
- check-boundary.sh 新增 PLATFORM_CORE;CP1/CP2 两处扫;CP6 的 seed.rs 改读真源
- check-contract-scan.py 的 plat_files 两处都收、重名键拼接(覆盖会丢函数 ⇒ 推不出守卫)
- check-module.sh 的 CRUD 改读 crates/sspf-core/src/crud.rs(软删契约要看 SQL)
- gen-function-catalog.py 的 OUT 改写真源(否则覆盖转发壳 ⇒ 上层 import 全断)
- 反向验证:只往 crates/sspf-core/ 塞违规 ⇒ AR9/AR10 都报红(证明真在扫真源)

测试归属调整:crud.rs 3 个测试原依赖 crate::modules::all_specs()(业务层)
⇒ 改用契约层合成 spec 参数化测试;registry.rs 测试改自建库 + seed::ensure_base(db, &[])。
顺带记录技术债:write_cast 的 numeric 映射是列名枚举而非 spec 声明。

影响:功能零变化(路由、响应形状、语义均未动),纯结构下沉。
验证:cargo build 零警告;cargo test --workspace 695 passed / 0 failed(与基线一致);
check-arch 14/14;--self-test 6/6;check-boundary 11/11;check-contract 10/10(反自证 12 例全过);
check-module 123/123;check-citations 4/4;verify --smoke 14 步全绿(512.3s)。
2026-11-03 15:49:00 +08:00

293 lines
10 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 -*-
"""gen-function-catalog.py —— 从官方 Java 枚举**生成**本仓的函数/变量目录。
为什么要生成而不是手抄
--------------------
`FunctionTypeEnum`(100+ 条)与 `SystemVariateEnum`(18 条)是**纯数据**:
公式编辑器(`variate.ts` 的三个元数据端点)靠它们出下拉与帮助文本。手抄两条风险:
① 漏条 —— 前端某个函数在帮助里点不开,但没人发现;
② 抄错 HTML 描述 —— 帮助面板显示成乱码/错行,且没有闸门能发现。
所以:**官方枚举是唯一真源**,本脚本把它转成 `crates/sspf-core/src/variate_catalog.rs`。
改了官方枚举就重跑;`--check` 用于闸门(生成物与真源不一致 ⇒ 非零退出)。
用法
----
python3 scripts/gen-function-catalog.py # 写入(生成物)
python3 scripts/gen-function-catalog.py --check # 只校验,不写
退出码:0 一致 / 1 有差异 / 2 前置缺失
"""
from __future__ import annotations
import pathlib
import re
import sys
ROOT = pathlib.Path(__file__).resolve().parent.parent
JAVA_DIR = pathlib.Path(
"/Users/xs/Desktop/workspace/jnpf/jnpf-java-boot/jnpf-system/"
"jnpf-system-entity/src/main/java/jnpf/base/model/variate"
)
# 🔴 **M2 起生成物的真源在 `crates/sspf-core/src/variate_catalog.rs`** ——
# 写旧路径会**覆盖转发壳**(`pub use sspf_core::*`)⇒ 上层 import 全断。
OUT = ROOT / "crates" / "sspf-core" / "src" / "variate_catalog.rs"
def read(path: pathlib.Path) -> str:
if not path.exists():
sys.exit(f"缺少官方真源:{path}")
return path.read_text(encoding="utf-8", errors="replace")
def split_top_level(body: str) -> list[str]:
"""按**顶层**逗号切分(跳过字符串字面量与括号)。"""
parts: list[str] = []
buf: list[str] = []
depth = 0
i = 0
in_str = False
while i < len(body):
c = body[i]
if in_str:
buf.append(c)
if c == "\\":
buf.append(body[i + 1])
i += 2
continue
if c == '"':
in_str = False
i += 1
continue
if c == '"':
in_str = True
buf.append(c)
elif c == "(":
depth += 1
buf.append(c)
elif c == ")":
depth -= 1
buf.append(c)
elif c == "," and depth == 0:
parts.append("".join(buf).strip())
buf = []
else:
buf.append(c)
i += 1
tail = "".join(buf).strip()
if tail:
parts.append(tail)
return parts
def parse_java_string(expr: str) -> str:
"""把 Java 的字符串表达式(含 `+` 拼接)求值成纯文本。"""
expr = expr.strip()
chunks = re.findall(r'"((?:[^"\\]|\\.)*)"', expr)
out = []
for chunk in chunks:
out.append(
chunk.replace("\\n", "\n")
.replace("\\t", "\t")
.replace('\\"', '"')
.replace("\\\\", "\\")
)
return "".join(out)
def rust_str(s: str) -> str:
"""Rust 字符串字面量(用 r#"…"# 避免 HTML 里的引号转义地狱)。"""
if '"#' not in s:
return 'r#"' + s + '"#'
return '"' + s.replace("\\", "\\\\").replace('"', '\\"').replace("\n", "\\n") + '"'
def parse_enum_entries(text: str, enum_name: str) -> list[tuple[str, list[str]]]:
"""解析 `enum X { A(...), B(...); ... }` ⇒ [(枚举名, [参数原文…]), …]。"""
start = text.index(f"enum {enum_name}")
brace = text.index("{", start)
depth = 0
end = brace
for i in range(brace, len(text)):
if text[i] == "{":
depth += 1
elif text[i] == "}":
depth -= 1
if depth == 0:
end = i
break
body = text[brace + 1 : end]
# 枚举体在第一个**顶层** `;` 处结束(之后是字段与方法)
depth = 0
in_str = False
cut = len(body)
i = 0
while i < len(body):
c = body[i]
if in_str:
if c == "\\":
i += 2
continue
if c == '"':
in_str = False
elif c == '"':
in_str = True
elif c in "([{":
depth += 1
elif c in ")]}":
depth -= 1
elif c == ";" and depth == 0:
cut = i
break
i += 1
entries_text = body[:cut]
entries: list[list[str]] = []
depth = 0
in_str = False
buf: list[str] = []
i = 0
while i < len(entries_text):
c = entries_text[i]
if in_str:
buf.append(c)
if c == "\\":
buf.append(entries_text[i + 1])
i += 2
continue
if c == '"':
in_str = False
i += 1
continue
if c == '"':
in_str = True
buf.append(c)
elif c == "(":
depth += 1
buf.append(c)
elif c == ")":
depth -= 1
buf.append(c)
if depth == 0:
raw = "".join(buf)
head = raw[: raw.index("(")].strip()
args = raw[raw.index("(") + 1 : raw.rindex(")")]
entries.append((head, split_top_level(args)))
buf = []
elif depth == 0:
# 条目名与空白:丢掉(名字只是 Java 侧标识)
if c not in ",\n\r\t ":
buf.append(c)
else:
buf.append(c)
i += 1
return entries
def gen() -> str:
funcs_text = read(JAVA_DIR / "FunctionTypeEnum.java")
variates_text = read(JAVA_DIR / "SystemVariateEnum.java")
categories_text = read(JAVA_DIR / "FunctionCategory.java")
cats = parse_enum_entries(categories_text, "FunctionCategory")
cat_map = {name: parse_java_string(args[0]) for name, args in cats}
funcs = parse_enum_entries(funcs_text, "FunctionTypeEnum")
variates = parse_enum_entries(variates_text, "SystemVariateEnum")
lines: list[str] = []
lines.append("//! 公式编辑器的**函数目录**与**系统变量目录**。")
lines.append("//!")
lines.append("//! 🔴 **本文件是生成物,不许手改** —— 由 `scripts/gen-function-catalog.py`")
lines.append("//! 从官方 Java 枚举逐条转出:")
lines.append("//! `jnpf-system-entity/.../model/variate/{FunctionTypeEnum,SystemVariateEnum}.java`")
lines.append("//! 改了官方枚举就重跑脚本;`gen-function-catalog.py --check` 是闸门。")
lines.append("//!")
lines.append("//! 为什么值得生成:这 100+ 条是**前端公式编辑器的下拉与帮助文本**(含 HTML),")
lines.append("//! 手抄漏一条不会有任何编译/测试报错,只会让某个函数在帮助里点不开。")
lines.append("")
lines.append("/// 一条公式函数。")
lines.append("pub struct FuncEntry {")
lines.append(" /// 函数名(`SUM` / `ROUND` …),也是表达式里的写法。")
lines.append(" pub name: &'static str,")
lines.append(" /// 帮助文本(**HTML 片段**,前端直接 v-html 渲染)。")
lines.append(" pub description: &'static str,")
lines.append(" /// 分类枚举名(`MATH` / `TIME` …)。")
lines.append(" pub category: &'static str,")
lines.append(" /// 分类中文名(`数学函数` …)—— 与 `category` 一一对应,冗余存一份。")
lines.append(" pub sub_category: &'static str,")
lines.append("}")
lines.append("")
lines.append("/// 一条系统变量(`@userId` 之类,公式里可直接引用)。")
lines.append("pub struct VariateEntry {")
lines.append(" /// 变量名(含 `@` 前缀)。")
lines.append(" pub field: &'static str,")
lines.append(" /// 中文说明。")
lines.append(" pub description: &'static str,")
lines.append("}")
lines.append("")
# 分类(含「全部函数」——官方 `FunctionCategory.ALL` 在树里被排除)
lines.append("/// 函数分类(官方 `FunctionCategory` 全量,**含** `ALL`)。")
lines.append("pub const FUNCTION_CATEGORIES: &[(&str, &str)] = &[")
for name, label in cat_map.items():
lines.append(f" ({rust_str(name)}, {rust_str(label)}),")
lines.append("];")
lines.append("")
lines.append(f"/// 公式函数目录({len(funcs)} 条,官方 `FunctionTypeEnum` 逐条)。")
lines.append("pub const FUNCTIONS: &[FuncEntry] = &[")
for _name, args in funcs:
if len(args) < 4:
continue
fname = parse_java_string(args[0])
desc = parse_java_string(args[1])
cat = args[2].strip().split(".")[-1]
sub = parse_java_string(args[3])
lines.append(" FuncEntry {")
lines.append(f" name: {rust_str(fname)},")
lines.append(f" description: {rust_str(desc)},")
lines.append(f" category: {rust_str(cat)},")
lines.append(f" sub_category: {rust_str(sub)},")
lines.append(" },")
lines.append("];")
lines.append("")
lines.append(f"/// 系统变量目录({len(variates)} 条,官方 `SystemVariateEnum` 逐条)。")
lines.append("pub const SYSTEM_VARIATES: &[VariateEntry] = &[")
for _name, args in variates:
if len(args) < 2:
continue
field = parse_java_string(args[0])
desc = parse_java_string(args[1])
lines.append(" VariateEntry {")
lines.append(f" field: {rust_str(field)},")
lines.append(f" description: {rust_str(desc)},")
lines.append(" },")
lines.append("];")
lines.append("")
return "\n".join(lines)
def main() -> int:
text = gen()
if "--check" in sys.argv:
if not OUT.exists():
print(f"❌ 生成物不存在:{OUT}")
return 1
current = OUT.read_text(encoding="utf-8")
if current != text:
print("❌ 生成物与官方枚举不一致,请重跑 scripts/gen-function-catalog.py")
return 1
print("✅ 函数/变量目录与官方枚举一致")
return 0
OUT.write_text(text, encoding="utf-8")
print(f"已写入 {OUT}({len(text.splitlines())} 行)")
return 0
if __name__ == "__main__":
raise SystemExit(main())