Files
ssw-platform/scripts/new-pack-gen.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

1012 lines
39 KiB
Python
Executable File
Raw Permalink 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 -*-
"""new-pack-gen —— 「加一个业务包」的生成器(`scripts/new-pack.sh` 的实现)。
🔴 **为什么存在**(HANDOFF §3 批次 12.5):
批次 12 把「spec 搬进 `packs/<app>/`」之后,加一个业务模块的成本从「改 6~8 处」
降到了「写一个包目录」。但**写那个包目录仍然是手抄**:`Cargo.toml` /
`pack.toml` / `schema/*.sql` / `src/lib.rs` / `modules/<app>.rs` 五个文件,
每个都有「抄漏一处就不对」的形状(漏 `f_tenant_id`、漏守卫、漏 `DDLS` 条目…)。
⇒ 本脚本把这五个文件**按真源生成**,再让 `pack-sync.py` 把内核接线补齐。
🔴 **真源是什么**:**业务决策**(app / 实体名 / 中文名 / 列清单)。
其余全部是推导:
- 表名 `<app>_<snake(实体)>`;`json_key` = 列名去 `f_` 转驼峰;
- 菜单 `url_address` = `<app>/<Entity>`,`en_code` = `permission.<app>.<entity>`
—— 两者**必须**与 spec 的 `module_key`、前端 Route、守卫编码一致(三处一字不差);
- `DDLS` 的键 = 表名,值 = `include_str!` 的 DDL。
🔴 **不猜**:列清单要么显式给(`--columns`),要么从一份 DDL 读(`--from-ddl`)。
两者都没有 ⇒ 拒绝生成(空的业务表没有意义,而且会掩盖「忘了给列」)。
用法(一般通过 `scripts/new-pack.sh` 调用,它负责找 python 与参数透传):
python3 scripts/new-pack-gen.py <app> <Entity> --name "中文名" \\
--columns "name:VARCHAR(200),price:DECIMAL(18,2),memo:TEXT" \\
[--table <物理表>] [--from-ddl <sql>] [--sort <菜单排序>] \\
[--with-frontend] [--dry-run] [--force]
退出码:0 生成完成 / 2 前置不满足(已存在 / 参数非法 / 列清单空)
"""
import io
import os
import re
import subprocess
import sys
HERE = os.path.dirname(os.path.abspath(__file__))
ROOT = os.path.dirname(HERE)
PACKS_DIR = os.path.join(ROOT, "packs")
MODULES_DIR = os.path.join(ROOT, "src", "backend", "src", "modules")
SCHEMA_SQL = os.path.join(ROOT, "src", "backend", "db", "schema.sql")
# 🔴 与 `bootstrap.rs` 的 `CONTRACT_VERSION` 同一口径(包的 `kernel_req` 校验它)。
KERNEL_REQ = ">=0.4,<0.5"
# 🔴 与 `rust-toolchain.toml` 的 `channel` 一致(L3 动态库要求内核与插件同一 rustc)。
TOOLCHAIN = "1.95.0"
# 物理表**必带**的平台列(顺序 = 响应 JSON 的键序,与 asset 一致)。
# 🔴 `f_tenant_id` **不许省** —— 官方 `base_*` 表全部带它,且参与复合主键。
PLATFORM_COLUMNS = [
{"col": "f_id", "ddl": "f_id VARCHAR(50) NOT NULL", "default": None, "numeric": False},
{"col": "f_creator_user_id", "ddl": "f_creator_user_id VARCHAR(50)", "default": None, "numeric": False},
{"col": "f_creator_time", "ddl": "f_creator_time TIMESTAMP(0) WITHOUT TIME ZONE", "default": None, "numeric": False},
{"col": "f_delete_mark", "ddl": "f_delete_mark INTEGER DEFAULT 0", "default": "0", "numeric": False},
{"col": "f_tenant_id", "ddl": "f_tenant_id VARCHAR(50) DEFAULT '0' NOT NULL", "default": "0", "numeric": False},
]
# 数值类型 ⇒ `numeric: true`(决定 body 里的值是原样拼 SQL 还是当字符串转义)。
NUMERIC_TYPES = (
"DECIMAL", "NUMERIC", "MONEY", "INT", "INTEGER", "BIGINT", "SMALLINT",
"TINYINT", "REAL", "DOUBLE", "FLOAT",
)
class GenError(Exception):
"""前置不满足(参数非法 / 已存在 / 列清单空)。"""
# ---------------------------------------------------------------- 小工具
def die(msg):
sys.stderr.write("new-pack: %s\n" % msg)
raise SystemExit(2)
def snake(name):
"""`DataResource` → `data_resource`(用于表名 / 函数名)。"""
out = []
for i, ch in enumerate(name):
if ch.isupper() and i > 0:
out.append("_")
out.append(ch.lower())
return "".join(out)
def upper_snake(name):
"""`DataResource` → `DATA_RESOURCE`(用于常量名)。"""
return snake(name).upper()
def json_key_of(col):
"""列名去 `f_` + 下划线转驼峰(`f_register_time` → `registerTime`)。
🔴 **必须与 `db::column_to_json_key` 逐字一致** —— 不一致 ⇒ 投影别名与
body 键对不上,而且**静默**(接口 200、字段是 null)。
`modules/mod.rs` 的 `every_json_key_matches_the_contract_mapping` 钉住这条。
"""
s = col[2:] if col.startswith("f_") else col
parts = s.split("_")
return parts[0] + "".join(p[:1].upper() + p[1:] for p in parts[1:] if p)
def read(path):
with io.open(path, encoding="utf-8") as fh:
return fh.read()
def write(path, text):
d = os.path.dirname(path)
if d and not os.path.isdir(d):
os.makedirs(d)
with io.open(path, "w", encoding="utf-8") as fh:
fh.write(text)
# ---------------------------------------------------------------- 列清单
def split_columns_arg(raw):
"""按**括号外的逗号**切分列清单。
🔴 直接 `raw.split(",")` 会把 `DECIMAL(18,2)` 切成 `DECIMAL(18` + `2)`
—— 这是真踩过的坑(报错还很难懂:`列 '2)' 缺类型`)。
"""
out, cur, depth = [], [], 0
for ch in raw:
if ch == "(":
depth += 1
elif ch == ")":
depth = max(0, depth - 1)
if ch == "," and depth == 0:
out.append("".join(cur))
cur = []
else:
cur.append(ch)
out.append("".join(cur))
return [s.strip() for s in out if s.strip()]
def parse_columns_arg(raw):
"""`"name:VARCHAR(200),price:DECIMAL(18,2)"` ⇒ 列定义列表。
🔴 **列名自动补 `f_` 前缀**(官方习惯)—— 但你写 `f_name` 也不会变成 `f_f_name`。
🔴 **类型必填**:没有类型的列在 PG 里建不出来;而且「猜类型」= 猜错就是
静默的精度丢失(`DECIMAL` 变 `VARCHAR`)⇒ 宁可拒绝。
"""
cols = []
for item in split_columns_arg(raw):
if ":" not in item:
raise GenError(
"列 %r 缺类型(写成 `name:VARCHAR(200)`)—— 不猜类型:"
"猜错会静默丢精度" % item)
name, typ = item.split(":", 1)
name = name.strip()
typ = typ.strip()
if not name or not typ:
raise GenError("列 %r 形状不对(要 `名字:类型`)" % item)
if not name.startswith("f_"):
name = "f_" + name
if not re.match(r"^[A-Za-z_][A-Za-z0-9_]*$", name):
raise GenError("列名 %r 不是合法标识符(只允许字母/数字/下划线)" % name)
cols.append(make_column(name, typ))
return cols
def make_column(col, typ):
"""列名 + 类型 ⇒ 列定义(`ddl` 里带上 DEFAULT / NOT NULL 修饰)。"""
first = re.split(r"[\s(]", typ.strip(), maxsplit=1)[0].upper()
return {
"col": col,
"ddl": "%s %s" % (col, typ.strip()),
"default": "0" if first in NUMERIC_TYPES else None,
"numeric": first in NUMERIC_TYPES,
}
def parse_ddl(path, table):
"""从一份已有 DDL 里读出 `table` 的列 ⇒ 列定义列表(**只取列名 + 类型**)。
🔴 **明确丢掉的东西**:索引 / 唯一约束 / 外键 / 注释 / 表级约束。
本函数的产出会被**重新排版**成包的 `schema/001_init.sql`
⇒ 丢掉的东西会**显式打印**出来,不静默吞掉。
"""
text = read(path)
pat = re.compile(
r"CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?([A-Za-z_][\w]*)\s*\(([\s\S]*?)\n\s*\);",
re.I,
)
found = None
for m in pat.finditer(text):
if table and m.group(1) != table:
continue
found = m
break
if found is None:
raise GenError(
"在 %s 里找不到表 %s 的 `CREATE TABLE … (…);`\n"
" ⇒ 用 `--table <表名>` 指定,或者改用 `--columns` 直接给列清单。"
% (path, table or "(任意)"))
table = found.group(1)
skipped = []
cols = []
for line in found.group(2).split("\n"):
line = line.strip().rstrip(",").strip()
if not line:
continue
if re.match(r"(?i)^(primary|unique|constraint|foreign|check|key|index)\b", line):
skipped.append(line)
continue
m = re.match(r'^"?([A-Za-z_][\w]*)"?\s+(\S.*)$', line)
if not m:
skipped.append(line)
continue
cols.append(make_column(m.group(1), m.group(2).strip()))
if not cols:
raise GenError("%s 里表 %s 一个列都没解析出来" % (path, table))
return table, cols, skipped
def merge_columns(business):
"""业务列 + 平台列 ⇒ 完整列清单(`f_id` 在最前,平台列在最后)。
🔴 **业务列里不许出现平台列名**(`f_id` / `f_tenant_id` …)——
重复定义会让 DDL 直接报错;更糟的是「业务自己建了个 f_id 但类型不对」。
"""
plat_names = {c["col"] for c in PLATFORM_COLUMNS}
seen = set()
clean = []
for c in business:
if c["col"] in plat_names:
raise GenError(
"列 %s 是平台列(由 new-pack 自动生成)⇒ 从 `--columns` 里去掉它" % c["col"])
if c["col"] in seen:
raise GenError("列 %s 重复" % c["col"])
seen.add(c["col"])
clean.append(c)
head = [PLATFORM_COLUMNS[0]] # f_id
tail = PLATFORM_COLUMNS[1:] # 审计列 + 软删 + 租户
return head + clean + tail
# ---------------------------------------------------------------- 渲染
def spec_columns_block(cols):
out = []
for c in cols:
d = 'Some("%s")' % c["default"] if c["default"] is not None else "None"
out.append(
' ColumnSpec { column: "%s", json_key: "%s", default: %s, numeric: %s },'
% (c["col"], json_key_of(c["col"]), d, "true" if c["numeric"] else "false")
)
return "\n".join(out)
def numeric_columns_literal(cols):
names = ['"%s"' % c["col"] for c in cols if c["numeric"]]
return "&[%s]" % ", ".join(names)
def ddl_block(table, cols):
lines = [" %s," % c["ddl"] for c in cols]
lines.append(" PRIMARY KEY (f_id, f_tenant_id)")
return (
"-- @@TABLE@@ —— 业务表(**业务包自带**,不是平台表)。\n"
"--\n"
"-- 🔴 **DDL 跟着包走**:本文件由 `packs/@@APP@@/src/lib.rs` 的 `include_str!`\n"
"-- 编译进二进制 ⇒ 内核启动时按包顺序幂等执行\n"
"-- ⇒ **不要**再手抄进 `src/backend/db/schema.sql`。\n"
"--\n"
"-- 🔴 **【集成期友好性】列名按官方规范**:`f_` 前缀 / `f_id VARCHAR(50)`(36 位 UUID)\n"
"-- / `f_tenant_id VARCHAR(50) DEFAULT '0' NOT NULL` —— 官方 `base_*` 表全部带它,\n"
"-- **单租户也不许省**(缺这列 ⇒ 集成时导不进官方)。\n"
"--\n"
"-- 🔴 本文件**只许建本包自己的表**,不许建 `base_*`(装载器会拦 `DdlTouchesBaseTable`)。\n"
"\n"
"CREATE TABLE IF NOT EXISTS @@TABLE@@ (\n"
"%s\n"
");\n" % "\n".join(lines)
)
def render(text, tokens):
for k, v in tokens.items():
text = text.replace("@@%s@@" % k, v)
left = re.findall(r"@@[A-Z_]+@@", text)
if left:
raise GenError("模板有未替换的占位符:%s" % ", ".join(sorted(set(left))))
return text
# ---------------------------------------------------------------- 模板
PACK_CARGO_TPL = """[package]
name = "sspf-pack-@@APP@@"
version.workspace = true
edition.workspace = true
rust-version.workspace = true
# 🔴 AR2:业务包只允许依赖 sspf-sdk(+ serde)。
# 出现 axum / tokio / pglite ⇒ `scripts/check-arch.sh` 直接红。
# 这是「整目录可搬走」的技术保证 —— 包的**路由是声明**,注册由内核做。
[dependencies]
sspf-sdk = { path = "../../crates/sspf-sdk" }
"""
PACK_TOML_TPL = """# @@APP@@ 业务包清单 —— 与 `PLAN.md` §5.1 的格式一致。
#
# 🔴 本文件不是给 cargo 读的,是给 `sspf pack export/import` 与内核装载器读的。
# 🔴 **改完要跑**(否则内核里的清单快照不更新 ⇒ `pack-sync --check` 会红):
# python3 scripts/pack-sync.py
[pack]
app_code = "@@APP@@"
name = "@@NAME@@"
version = "1.0.0"
kernel = "@@KERNEL@@" # 内核兼容区间(不匹配则拒载)
migratable = true # 允许导出到基线平台
[pack.compat]
baseline = "v7" # 兼容基线版本
frontend = "vue3" # 前端族(决定表单 JSON 方言)
tenant = false # 本期单租户
# 物理表:name = 本平台表名;baseline_table = 基线平台上的表名(允许不同,导出时映射)
[[pack.tables]]
name = "@@TABLE@@"
ddl = "schema/001_init.sql"
baseline_table = "@@TABLE@@"
[pack.metadata]
# 低代码元数据(与基线平台 visualdev 同构的 JSON)。本包是「手写 spec」形态 ⇒ 留空。
forms = []
models = []
menus = []
flows = []
[pack.build]
# 本包带手写 Rust(`src/lib.rs`)⇒ 链进内核。
# 🔴 kind 不是 "none" 时必须补 `toolchain`,且与 `rust-toolchain.toml` 一致。
kind = "static"
toolchain = "@@TOOLCHAIN@@"
"""
PACK_LIB_TPL = '''//! @@APP@@ —— 业务包:@@ENTITY@@(物理表 `@@TABLE@@`)。
//!
//! 🔴 **本文件是 spec 的单一真源** —— 内核的 `src/backend/src/modules/@@APP@@.rs`
//! 只做 `pub use` 转发(面 A 适配器),不再保留第二份拷贝。
//!
//! 🔴 **路由用官方 JNPF 形状**(RESTful:`GET/POST /api/@@APP@@/@@ENTITY@@`、
//! `DELETE /api/@@APP@@/@@ENTITY@@/{id}`)—— **不是**面 A 的
//! `/api/ssw/{appCode}/{Entity}/{List|Save|Delete}`(那是本仓自造的约定,
//! 集成到官方 JNPF 时**全部作废**)。
//!
//! 🔴 **DDL 跟着包走**:`schema/001_init.sql` 用 `include_str!` 编译进二进制
//! ⇒ 内核启动时幂等执行 ⇒ 不手抄进 `db/schema.sql`。
use sspf_sdk::{
BusinessPack, ColumnSpec, EntitySpec, HttpMethod, Manifest, MenuSpec, PackRoute, RouteAction,
RouteGuard,
};
/// 🔴 **包的统一 DDL 出口**(`表名 → DDL 文本`)—— 内核**只认这一种写法**。
///
/// 内核的 `packs_gen.rs` 是生成的,生成器按 `sspf_pack_<app>::DDLS` 取值
/// ⇒ 每个包都用同一个常量名 ⇒ 加包不用改内核。
/// `include_str!` 把 DDL **编译进二进制** ⇒ 单二进制部署,运行期不需要 `packs/` 目录。
pub const DDLS: &[(&str, &str)] = &[("@@TABLE@@", include_str!("../schema/001_init.sql"))];
/// @@ENTITY@@ 的列清单(**顺序 = 响应 JSON 的键序**)。
///
/// 🔴 前 1 列必须是 `f_id`;末 4 列是平台列(审计 / 软删 / 租户)。
/// 🔴 `f_tenant_id` **不许省** —— 官方 `base_*` 表全部带它,且参与复合主键
/// `(f_id, f_tenant_id)`;单租户也不许省 ⇒ 集成时缺这列就导不进官方。
const @@UPPER@@_COLUMNS: &[ColumnSpec] = &[
@@SPEC_COLUMNS@@
];
/// @@ENTITY@@ 的 spec。
pub const @@UPPER@@_SPEC: EntitySpec = EntitySpec {
app_code: "@@APP@@",
entity: "@@ENTITY@@",
table: "@@TABLE@@",
// 🔴 `module_key` 必须 == 菜单 `url_address` == 前端 Route path(三处一字不差)。
module_key: Some("@@URL@@"),
columns: @@UPPER@@_COLUMNS,
numeric_columns: @@NUMERIC@@,
// 非 demo 表 ⇒ `body.creatorUserId || 'admin'`。
creator_fixed: None,
};
/// 本包的内置菜单。
///
/// 🔴 `url_address` 必须与 [`@@UPPER@@_SPEC`] 的 `module_key` 一字不差 ——
/// 面 A 的菜单守卫靠它命中。
pub const @@UPPER@@_MENU: MenuSpec = MenuSpec {
id: "@@MENU_ID@@",
full_name: "@@NAME@@",
// 🔴 面 B 的点权限判据 `f_en_code`:路由的守卫必须与它**一字不差**
// (不一致 ⇒ 运行时查菜单查不到 ⇒ 走「未映射放行」⇒ 越权且静默)。
en_code: "@@EN_CODE@@",
url_address: "@@URL@@",
parent_id: "0",
menu_type: 2,
icon: Some("app"),
sort_code: @@SORT@@,
// 🔴 字面量而非引用内核常量:业务包不许依赖内核(AR2)。
system_en_code: "mainSystem",
};
/// 包清单(与 `pack.toml` 的 `[pack]` 段一致)。
const MANIFEST: Manifest = Manifest {
app_code: "@@APP@@",
name: "@@NAME@@",
version: "1.0.0",
kernel_req: "@@KERNEL@@",
migratable: true,
};
// ---------------------------------------------------------------- 路由声明
//
// 🔴 **官方 CRUD 的形状是 RESTful**(2026-11-02 实测官方 controller:
// `/xxx/Save` 仅 4 条特例、`/xxx/Delete` **0 条**):
// 列表 `GET /api/{模块}/{资源}`、新建 `POST …`、改 `PUT …/{id}`、删 `DELETE …/{id}`。
/// `GET /api/@@APP@@/@@ENTITY@@` —— 列表。
pub const @@UPPER@@_LIST_ROUTE: PackRoute = PackRoute {
path: "/api/@@APP@@/@@ENTITY@@",
method: HttpMethod::Get,
entity: "@@ENTITY@@",
action: RouteAction::List,
guard: RouteGuard::EnCode("@@EN_CODE@@"),
};
/// `POST /api/@@APP@@/@@ENTITY@@` —— 新建 / 更新(body 里带 `id` 就是更新)。
pub const @@UPPER@@_SAVE_ROUTE: PackRoute = PackRoute {
path: "/api/@@APP@@/@@ENTITY@@",
method: HttpMethod::Post,
entity: "@@ENTITY@@",
action: RouteAction::Save,
guard: RouteGuard::EnCode("@@EN_CODE@@"),
};
/// `DELETE /api/@@APP@@/@@ENTITY@@/{id}` —— 软删。
pub const @@UPPER@@_DELETE_ROUTE: PackRoute = PackRoute {
path: "/api/@@APP@@/@@ENTITY@@/{id}",
method: HttpMethod::Delete,
entity: "@@ENTITY@@",
action: RouteAction::Delete,
guard: RouteGuard::EnCode("@@EN_CODE@@"),
};
/// 本包声明的全部路由。
pub const @@UPPER@@_ROUTES: &[PackRoute] = &[
@@UPPER@@_LIST_ROUTE,
@@UPPER@@_SAVE_ROUTE,
@@UPPER@@_DELETE_ROUTE,
];
/// @@NAME@@ 业务包。
///
/// 🔴 **类型名固定为 `Pack`** —— 内核的 `src/backend/src/packs_gen.rs` 是**生成**的,
/// 生成器按 `sspf_pack_<app>::Pack` 拼路径 ⇒ 每个包都用同一个名字。
pub struct Pack;
impl BusinessPack for Pack {
fn manifest(&self) -> &'static Manifest {
&MANIFEST
}
fn entities(&self) -> &'static [EntitySpec] {
&[@@UPPER@@_SPEC]
}
fn menus(&self) -> &'static [MenuSpec] {
&[@@UPPER@@_MENU]
}
fn routes(&self) -> &'static [PackRoute] {
@@UPPER@@_ROUTES
}
}
#[cfg(test)]
mod tests {
use super::*;
/// 🔴 三处一致:`module_key` == `menu.url_address`(第三处是前端 Route,本包管不到)。
/// 不一致的后果是**静默放行**(菜单未映射 ⇒ 守卫不拦),不会报错。
#[test]
fn module_key_matches_menu_url_address() {
assert_eq!(
@@UPPER@@_SPEC.module_key,
Some(@@UPPER@@_MENU.url_address)
);
}
/// 列名全部 `f_` 前缀,且主键是 `f_id`。
#[test]
fn columns_are_prefixed_and_have_id() {
assert_eq!(@@UPPER@@_COLUMNS[0].column, "f_id");
for c in @@UPPER@@_COLUMNS {
assert!(c.column.starts_with("f_"), "列名必须 f_ 前缀: {}", c.column);
}
}
/// `json_key` 必须是列名去 `f_` 前缀后的 camelCase。
#[test]
fn json_keys_are_camel_case_without_prefix() {
for c in @@UPPER@@_COLUMNS {
let stripped = c.column.trim_start_matches("f_");
let mut expect = String::new();
let mut up = false;
for ch in stripped.chars() {
if ch == '_' {
up = true;
} else if up {
expect.extend(ch.to_uppercase());
up = false;
} else {
expect.push(ch);
}
}
assert_eq!(c.json_key, expect, "json_key 与列名不匹配: {}", c.column);
}
}
/// numeric 标记与 `numeric_columns` 必须一致(否则金额会被当字符串转义)。
#[test]
fn numeric_columns_matches_column_flags() {
let flagged: Vec<&str> = @@UPPER@@_COLUMNS
.iter()
.filter(|c| c.numeric)
.map(|c| c.column)
.collect();
assert_eq!(flagged, @@UPPER@@_SPEC.numeric_columns);
}
/// 包清单与 spec 的 app_code 必须一致(否则内核按 app 路由会找不到)。
#[test]
fn manifest_app_code_matches_spec() {
assert_eq!(Pack.manifest().app_code, @@UPPER@@_SPEC.app_code);
assert_eq!(Pack.entities().len(), 1);
assert_eq!(Pack.menus().len(), 1);
assert_eq!(Pack.routes().len(), 3);
}
/// 🔴 **路由必须是官方形状** —— 面 A 的 `/api/ssw/...` 集成时全部作废。
#[test]
fn routes_use_official_shape_not_face_a() {
for r in Pack.routes() {
assert!(r.path.starts_with("/api/"), "路由必须以 /api/ 开头: {}", r.path);
assert!(
!r.path.starts_with("/api/ssw/"),
"🔴 路由不许用面 A 的 /api/ssw/...(集成时作废): {}",
r.path
);
assert!(!r.path.ends_with("/Save"), "官方没有 /Save 端点: {}", r.path);
assert!(!r.path.ends_with("/Delete"), "官方没有 /Delete 端点: {}", r.path);
}
let del = Pack
.routes()
.iter()
.find(|r| r.action == RouteAction::Delete)
.expect("必须有删除路由");
assert!(del.path.contains("{id}"), "删除路由必须带 {{id}}: {}", del.path);
}
/// 🔴 **路由的 entity 必须指向本包声明的实体** —— 否则装配时拿到空 spec
/// ⇒ 路由注册了但永远查不到表 ⇒ **静默 404**。
#[test]
fn routes_point_at_declared_entities() {
for r in Pack.routes() {
assert!(
Pack.entities().iter().any(|e| e.entity == r.entity),
"路由 {} 指向未声明的实体 {}",
r.path,
r.entity
);
}
}
/// 🔴 动作与方法的对应被钉死(内核的 `crud_router` 按这个分派)。
#[test]
fn route_actions_match_methods() {
for r in Pack.routes() {
match (r.action, r.method) {
(RouteAction::List, HttpMethod::Get) => {}
(RouteAction::Save, HttpMethod::Post) => {}
(RouteAction::Delete, HttpMethod::Delete) => {}
_ => panic!("动作 {:?} 与方法 {:?} 的组合不被支持: {}", r.action, r.method, r.path),
}
}
}
/// 🔴 **守卫必须与菜单的 `f_en_code` 一字不差** —— 不一致 ⇒ 运行时查菜单
/// 查不到 ⇒ 走「未映射放行」⇒ **任何登录用户都能调** ⇒ 静默越权。
#[test]
fn route_guards_match_menu_en_code() {
for r in Pack.routes() {
let RouteGuard::EnCode(code) = r.guard else {
panic!("本包的路由都该有点权限守卫: {}", r.path);
};
assert_eq!(code, @@UPPER@@_MENU.en_code, "路由 {} 的守卫与菜单不一致", r.path);
}
}
/// 🔴 **DDL 必须含 `f_tenant_id` 且复合主键是 `(f_id, f_tenant_id)`**。
#[test]
fn ddl_carries_tenant_id() {
let sql = DDLS[0].1;
assert!(sql.contains("f_tenant_id"), "DDL 必须含 f_tenant_id");
assert!(
sql.contains("PRIMARY KEY (f_id, f_tenant_id)"),
"复合主键必须是 (f_id, f_tenant_id)"
);
}
/// 🔴 **DDL 与 spec 的列必须一致** —— spec 少一列 ⇒ CRUD 投影会漏字段。
#[test]
fn ddl_columns_match_spec_columns() {
let sql = DDLS[0].1;
for col in @@UPPER@@_SPEC.columns {
assert!(sql.contains(col.column), "DDL 缺列 {}", col.column);
}
}
/// 🔴 `DDLS` 的每一对都必须是「表名 → 真的建这张表的 SQL」。
#[test]
fn ddls_pairs_name_the_table_they_create() {
assert!(!DDLS.is_empty(), "本包有实体 ⇒ DDLS 不能为空");
for (table, sql) in DDLS {
assert!(
sql.contains(&format!("CREATE TABLE IF NOT EXISTS {table}")),
"DDLS 里 {table} 的 DDL 没有建这张表"
);
}
}
/// 🔴 `DDLS` 覆盖本包全部实体(漏一张 ⇒ 那张表根本没建)。
#[test]
fn ddls_covers_every_entity_table() {
for spec in Pack.entities() {
assert!(
DDLS.iter().any(|(t, _)| *t == spec.table),
"实体 {} 的表 {} 不在 DDLS 里",
spec.entity,
spec.table
);
}
}
}
'''
MODULE_TPL = '''//! @@APP@@ —— 业务模块:@@ENTITY@@(物理表 `@@TABLE@@`)。
//!
//! 🔴 **本文件是「面 A 适配器」,不是 spec 的家**:
//! spec / 菜单 / 面 B 路由的单一真源在 `packs/@@APP@@/src/lib.rs`(**只依赖 sspf-sdk**),
//! 本文件只做 `pub use` 转发 ⇒ **spec 只有一份**。
//!
//! 🔴 **为什么还要面 A**:MVP 前端(React,`src/frontend`)走的是
//! `/api/ssw/{appCode}/{Entity}/{List|Save|Delete}` ⇒ 没有面 A 页面就是空的。
//! 集成到官方 JNPF 时面 A 作废、面 B 直接搬(两套路径不同,互不影响)。
//!
//! 🔴 本文件由 `scripts/new-pack.sh` 生成;重跑会覆盖(`--force`)。
use axum::body::Bytes;
use axum::extract::{RawQuery, State};
use axum::http::HeaderMap;
use axum::routing::{delete, get, post};
use axum::{Json, Router};
use crate::platform::crud::{handle_delete, handle_list, handle_save};
use crate::platform::envelope::ActionResult;
use crate::platform::state::AppState;
// 🔴 **spec 与菜单的单一真源 = 业务包** —— 这里只转发,不重写。
pub use sspf_pack_@@APP@@::@@UPPER@@_MENU;
pub use sspf_pack_@@APP@@::@@UPPER@@_SPEC;
/// 本模块的 3 条路由(**面 A**:业务层的路由表)—— 钉子测试遍历它。
pub const ROUTES: [&str; 3] = [
"/api/ssw/@@APP@@/@@ENTITY@@/List",
"/api/ssw/@@APP@@/@@ENTITY@@/Save",
"/api/ssw/@@APP@@/@@ENTITY@@/Delete",
];
/// `GET /api/ssw/@@APP@@/@@ENTITY@@/List`。
pub async fn @@SNAKE@@_list(
State(state): State<AppState>,
headers: HeaderMap,
) -> Json<ActionResult> {
handle_list(&state, &headers, &@@UPPER@@_SPEC).await
}
/// `POST /api/ssw/@@APP@@/@@ENTITY@@/Save`。
pub async fn @@SNAKE@@_save(
State(state): State<AppState>,
headers: HeaderMap,
body: Bytes,
) -> Json<ActionResult> {
handle_save(&state, &headers, &@@UPPER@@_SPEC, &body).await
}
/// `DELETE /api/ssw/@@APP@@/@@ENTITY@@/Delete?id=`。
pub async fn @@SNAKE@@_delete(
State(state): State<AppState>,
headers: HeaderMap,
raw: RawQuery,
) -> Json<ActionResult> {
handle_delete(&state, &headers, &@@UPPER@@_SPEC, &raw).await
}
/// 本模块的路由(**面 A**,`Router::merge` 进总路由)。
///
/// 🔴 路径在这里写**字面量**(不用 `ROUTES[0]`)—— 契约扫描器是静态解析,
/// 认不出数组下标 ⇒ 写成下标会让 `check-contract` 判「契约有、代码没有」(假飘移)。
pub fn router() -> Router<AppState> {
Router::new()
.route("/api/ssw/@@APP@@/@@ENTITY@@/List", get(@@SNAKE@@_list))
.route("/api/ssw/@@APP@@/@@ENTITY@@/Save", post(@@SNAKE@@_save))
.route(
"/api/ssw/@@APP@@/@@ENTITY@@/Delete",
delete(@@SNAKE@@_delete),
)
}
'''
# ---------------------------------------------------------------- 前置校验
def check_app(app):
if not re.match(r"^[a-z][a-z0-9_]*$", app):
raise GenError(
"app_code %r 非法:只允许 小写字母/数字/下划线,且以字母开头"
"(它同时是目录名、crate 名的一部分、路由前缀)" % app)
def check_entity(entity):
if not re.match(r"^[A-Z][A-Za-z0-9]*$", entity):
raise GenError(
"实体名 %r 非法:必须大驼峰(如 `DataResource`)"
"—— 它同时是路由段、JSON 的 entity、常量名前缀" % entity)
def check_collisions(app, entity, table, menu_id, url, en_code):
"""🔴 撞名检查 —— 这些撞了**都不报错**,只会静默错。
- 目录 / 模块文件撞 ⇒ 覆盖别人的包;
- 物理表撞 ⇒ `CREATE TABLE IF NOT EXISTS` **静默不生效**,两张表共用一份数据;
- 菜单 id 撞 ⇒ 种子 INSERT 主键冲突(启动 exit 1);
- `url_address` / `en_code` 撞 ⇒ 两套路由共用一条菜单 ⇒ **互相越权**。
"""
if os.path.isdir(os.path.join(PACKS_DIR, app)):
raise GenError("包目录 packs/%s 已存在(要覆盖请加 --force)" % app)
mod = os.path.join(MODULES_DIR, "%s.rs" % app)
if os.path.isfile(mod):
raise GenError("模块文件 src/backend/src/modules/%s.rs 已存在(要覆盖请加 --force)" % app)
# 物理表:平台 schema + 所有包的 DDL
haystacks = [SCHEMA_SQL]
for root, _dirs, files in os.walk(PACKS_DIR):
for f in files:
if f.endswith(".sql"):
haystacks.append(os.path.join(root, f))
for path in haystacks:
if not os.path.isfile(path):
continue
if re.search(r"CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?%s\b" % re.escape(table),
read(path), re.I):
raise GenError("物理表 %s 已存在(在 %s 里)" % (table, os.path.relpath(path, ROOT)))
# 菜单:契约表里查(它登记了全仓的菜单)
contract = read(os.path.join(ROOT, "docs", "contract.md"))
for label, needle in (("菜单 id", menu_id), ("url_address", url), ("f_en_code", en_code)):
if re.search(r"(?m)^%s\t" % re.escape(needle), contract) or re.search(
r"\t%s(\t|$)" % re.escape(needle), contract):
raise GenError("%s %s 已在 docs/contract.md 里登记过" % (label, needle))
def next_sort_code():
"""菜单 `sort_code` = 现有最大 + 1(不猜具体数字,跟着现状走)。"""
contract = read(os.path.join(ROOT, "docs", "contract.md"))
m = re.search(r"(?m)^\[MENU\]\n([\s\S]*?)\n\[", contract)
if not m:
return 10
best = 0
for line in m.group(1).split("\n"):
if not line.strip() or line.lstrip().startswith("#") or line.startswith("<"):
continue
cols = line.split("\t")
if len(cols) >= 8 and cols[7].strip().isdigit():
best = max(best, int(cols[7]))
return best + 1
# ---------------------------------------------------------------- 主流程
def parse_argv(argv):
if len(argv) < 3:
raise GenError("用法:new-pack-gen.py <app> <Entity> --name 中文名 --columns a:TYPE,b:TYPE")
app, entity = argv[1], argv[2]
opts = {
"name": None, "columns": None, "from_ddl": None, "table": None,
"menu_id": None, "en_code": None, "sort": None,
"with_frontend": False, "dry_run": False, "force": False,
}
i = 3
while i < len(argv):
a = argv[i]
if a in ("--name", "--columns", "--from-ddl", "--table", "--menu-id", "--en-code", "--sort"):
if i + 1 >= len(argv):
raise GenError("参数 %s 后面缺值" % a)
key = a[2:].replace("-", "_")
opts[key] = argv[i + 1]
i += 2
continue
if a == "--with-frontend":
opts["with_frontend"] = True
i += 1
continue
if a == "--dry-run":
opts["dry_run"] = True
i += 1
continue
if a == "--force":
opts["force"] = True
i += 1
continue
raise GenError("未知参数 %r" % a)
return app, entity, opts
def plan(app, entity, opts):
"""算清楚要写什么 ⇒ dict(不落盘)。"""
check_app(app)
check_entity(entity)
table = opts["table"] or "%s_%s" % (app, snake(entity))
if not re.match(r"^[a-z][a-z0-9_]*$", table):
raise GenError("表名 %r 非法(小写 + 下划线)" % table)
if opts["from_ddl"]:
table, cols, skipped = parse_ddl(opts["from_ddl"], table)
if skipped:
print(" ⚠️ 以下行没有进包的 DDL(索引 / 约束 / 注释请手工补):")
for s in skipped:
print(" · %s" % s[:100])
elif opts["columns"]:
cols = parse_columns_arg(opts["columns"])
else:
raise GenError(
"没有列清单:给 `--columns \"name:VARCHAR(200),price:DECIMAL(18,2)\"`,\n"
" 或者用 `--from-ddl <某个 .sql>` 从已有建表语句读。\n"
" 🔴 不猜:空表建出来没有意义,而且会掩盖「忘了给列」。")
cols = merge_columns(cols)
menu_id = opts["menu_id"] or "m_%s" % snake(entity)
url = "%s/%s" % (app, entity)
en_code = opts["en_code"] or "permission.%s.%s" % (app, entity.lower())
sort = int(opts["sort"]) if opts["sort"] else next_sort_code()
name = opts["name"] or entity
if not opts["force"]:
check_collisions(app, entity, table, menu_id, url, en_code)
tokens = {
"APP": app,
"ENTITY": entity,
"TABLE": table,
"NAME": name,
"URL": url,
"MENU_ID": menu_id,
"EN_CODE": en_code,
"SORT": str(sort),
"KERNEL": KERNEL_REQ,
"TOOLCHAIN": TOOLCHAIN,
"UPPER": upper_snake(entity),
"SNAKE": snake(entity),
"SPEC_COLUMNS": spec_columns_block(cols),
"NUMERIC": numeric_columns_literal(cols),
}
files = [
(os.path.join(PACKS_DIR, app, "Cargo.toml"), render(PACK_CARGO_TPL, tokens)),
(os.path.join(PACKS_DIR, app, "pack.toml"), render(PACK_TOML_TPL, tokens)),
(os.path.join(PACKS_DIR, app, "schema", "001_init.sql"), render(ddl_block(table, cols), tokens)),
(os.path.join(PACKS_DIR, app, "src", "lib.rs"), render(PACK_LIB_TPL, tokens)),
(os.path.join(MODULES_DIR, "%s.rs" % app), render(MODULE_TPL, tokens)),
]
return {"app": app, "entity": entity, "table": table, "files": files,
"cols": cols, "menu_id": menu_id, "url": url, "en_code": en_code, "sort": sort}
def register_ruler():
"""跑一次 `check-module.sh`,把契约 `[RULER]` 里的断言条数登记成实际值。
🔴 **为什么必须做**:`check-module.sh` 的断言数**随模块数增长**
(每个模块 ~30 条)⇒ 加完模块它会报「尺子被改弱了(少了/多了断言)」。
那条自证的用意是「有人偷偷删断言」,而**加模块导致的变多**是合法的
⇒ 让生成器把数字登记掉,别让人去猜。
🔴 **安全边界**(很重要):
- **只允许变大**:变小说明真有人删了断言 ⇒ 拒绝登记并打印;
- **有别的失败就不登记**:只认「尺子自证」这一条 ❌,
其它 ❌(模块形状不对 / 前端缺文件)必须先修。
"""
sh = os.path.join(HERE, "check-module.sh")
env = dict(os.environ)
env["PATH"] = os.path.dirname(sys.executable) + os.pathsep + env.get("PATH", "")
r = subprocess.run(["/bin/bash", sh], capture_output=True, text=True, env=env)
out = (r.stdout or "") + (r.stderr or "")
m = re.search(r"PASS=(\d+) FAIL=(\d+)", out)
if not m:
print(" ⚠️ 读不出 PASS/FAIL ⇒ 跳过登记")
return False
passed = int(m.group(1))
# 只认「行首是 ❌」的断言失败;汇总行(`有 ❌,请按上面修复…`)不算。
bad = [
ln.strip()
for ln in out.split("\n")
if ln.strip().startswith("❌") and "尺子自证" not in ln
]
if bad:
print(" ⚠️ check-module 有真失败 ⇒ 不登记条数(先修这些):")
for ln in bad[:6]:
print(" " + ln)
return False
path = os.path.join(ROOT, "docs", "contract.md")
text = read(path)
hit = re.search(r"(?m)^check-module\.sh\t(\d+)$", text)
if not hit:
print(" ⚠️ 契约里找不到 `[RULER]` 的 `check-module.sh` 行 ⇒ 跳过登记")
return False
old = int(hit.group(1))
if old == passed:
print(" ✅ 条数已是最新(%d)" % passed)
return True
if old > passed:
print(" ⚠️ 条数从 %d **降到** %d ⇒ 像是有人删了断言 ⇒ 拒绝自动登记" % (old, passed))
return False
write(path, text.replace(hit.group(0), "check-module.sh\t%d" % passed))
print(" ✅ 已登记 %d 条(原 %d,+%d 来自新模块)" % (passed, old, passed - old))
return True
def main(argv):
app, entity, opts = parse_argv(argv)
p = plan(app, entity, opts)
print("业务包:%s / %s(表 %s,%d 列)" % (p["app"], p["entity"], p["table"], len(p["cols"])))
print("菜单:%s url=%s en_code=%s sort=%d" % (p["menu_id"], p["url"], p["en_code"], p["sort"]))
print("要写 %d 个文件:" % len(p["files"]))
for path, text in p["files"]:
print(" · %-58s %3d 行" % (os.path.relpath(path, ROOT), text.count("\n")))
if opts["dry_run"]:
print("\n(--dry-run ⇒ 一个字节都没写)")
return 0
for path, text in p["files"]:
write(path, text)
# 🔴 **接线**:契约表 + packs_gen.rs + modules/mod.rs 五段 + Cargo 依赖段。
# 不跑这一步 ⇒ 包存在但内核不认识它(面 A/B 全 404,且**不报错**)。
print("\n同步派生位置(契约表 / packs_gen.rs / modules/mod.rs / Cargo.toml)…")
rc = subprocess.call([sys.executable, os.path.join(HERE, "pack-sync.py")])
if rc != 0:
sys.stderr.write(
"❌ pack-sync 失败 ⇒ 包文件已写、但**内核还不知道它**。\n"
" 修好上面的报错后跑:python3 scripts/pack-sync.py\n")
return 2
if opts["with_frontend"]:
print("\n生成前端三件套…")
rc = subprocess.call(["/bin/bash", os.path.join(HERE, "new-page.sh"), p["app"], p["entity"]])
if rc != 0:
sys.stderr.write(
"❌ new-page.sh 失败 ⇒ 后端已就位、前端页面还没有。\n"
" 修好后跑:bash scripts/new-page.sh %s %s\n" % (p["app"], p["entity"]))
return 2
# 🔴 **尺子条数**:`check-module.sh` 的断言数 = 模块数 × 每模块条数
# ⇒ 加一个模块必然变多 ⇒ 那条「尺子被改弱了」的自证会红。
# 这里把它登记掉(只允许变大,见 `register_ruler` 的安全边界)。
print("\n登记尺子条数(check-module 的断言数随模块数增加)…")
register_ruler()
print("""
下一步(缺一个都会在运行时才发现问题):
1. bash scripts/verify.sh --fast # 全绿才继续(编译 + 6 把静态闸门)
2. 补列的**中文标签**:src/frontend/src/views/%s.tsx 的 FIELDS(生成器不猜业务语义)
3. 起后端 + 前端,点一遍列表 / 新增 / 删除
""" % p["entity"])
return 0
if __name__ == "__main__":
try:
sys.exit(main(sys.argv))
except GenError as exc:
sys.stderr.write("new-pack: %s\n" % exc)
sys.exit(2)