fix(gates): close the BOM gate hole that let new files skip the check

The BOM gate claimed to stop BOMs from being stripped, but it only ever
inspected files that were already tracked AND already had a BOM. A new
file under a BOM-listed directory could be born without one and never
be noticed, because the scan never returned it and, even if it had, the
"no HEAD version" branch skipped it. Editing a listed file and losing
its BOM is a real accident that already happened once; creating one
without a BOM was the same accident with no safety net at all.

Measured before and after on the same untracked file with no BOM:

  before: checked 101 files, no drift, exit 0
  after:  FAIL, names the file, exit 1

The count of 101 was itself the symptom: with one more file present the
honest number is 102. The old code was not "silently passing a clean
tree", it was not looking.

The scan now includes untracked files, and a listed file with no HEAD
version must carry a BOM. Files that are tracked without a BOM keep
their historical pass so this does not flood existing code with
failures; instead the two that were listed but had no BOM were given one
so the list means what it says.

That exposed a conflict nobody had hit yet. The font file is generated,
and the generator rewrites it from scratch on every run, so a hand-added
BOM survived until the next regeneration and then vanished. The BOM gate
and the generated-fresh gate could not both pass. The generator now puts
the BOM back as its last step, idempotently, so the two gates agree and
the whole UI directory keeps its uniform encoding. Font content is
untouched: everything after the first three bytes is byte-identical.

The menu generator gains a real read-only mode. It previously had no
options at all and always rewrote its outputs; the arrows it printed
were accurate. That made it easy to mistake for a checker, since an
unchanged tree produces identical bytes and looks untouched. --check now
reports up to date or stale without writing anything, and the
registration tables are checked the same way. Default behaviour and
output are unchanged.

The telemetry page header no longer restates the board's input hardware
facts. They live in the IOBOARD README, which is where the board's
electrical behaviour belongs; the page keeps only what it alone can say:
that the output rows show the shadow register rather than contact
feedback, why an invalid sample draws -- instead of 分, and that these
twelve rows are not in the point table. One fact, one place.

The team rule for experiments now requires the file hash, the located
line number, and both runs. A report once cited a line number that did
not exist in the final file, which left no way to confirm which version
had actually been tested.
This commit is contained in:
2026-11-16 23:59:49 +08:00
parent 515db819ab
commit 12e0617909
14 changed files with 283 additions and 60 deletions
+10
View File
@@ -97,6 +97,16 @@ onToolCallBudget: wrap-up
- **采集必须留原文**。转述"构建成功"无法被复跑推翻,也无法被复跑证实。
- **判定标准必须来自发起方**。执行人可以报告"第 N 行是 X",不能报告"所以通过了"——除非发起方事先把这条写进判据。
**采集层对"实验类证据"的追加要求(变异测试与对照组)**:凡是靠**故意改一个变量**来证明某个东西的证言(变异测试、反向断言自证、对照组/实验组),报告必须同时给出三项,缺一项即按「证据链不完整」处理,不按"已证明"处理:
1. **被测文件的 md5**(证明你测的是哪个版本)
2. **`grep -n` 从最终文件里定位到的那一行**(证明你报告的行号就是最终文件的,不是中间态的)
3. **对照组与实验组的两次输出**(证明两组只差一个变量,而不是各跑了不同版本)
为什么单独提这条:真实失效过一次。执行人报"变异后 120/121,红的行号是 257",验收人独立重跑得到的是行号 322——差 65 行,正好约等于它新增的代码量,说明它引用的是改编号之前的中间态输出。结论没错(失败文案唯一标识了断言),但**那份证据链无法证明它测的是最终文件**,验收人只能靠失败文案去猜。这不是判断题,是采集题:行号对不上,就没人能确认你测的是哪一版。
同一条对 Lead 自己同样适用——Lead 亲自做的实验,也要按这三项交证据,不许因为"我是发起方"就免检。
台架类角色(`bench-runner`)把这条写成了身份约束:它的工具列表里没有 `edit`/`write`,也没有 gate 的 submit/accept 权限,**既不改代码也不给结论**。这是刻意的双锁。
## 五、验收人 ≠ 执行人
+1 -1
View File
@@ -1,4 +1,4 @@
/*
/*
* 模块名称:cfg_file
* 模块功能:通用配置文件引擎(双端共享核心)——INI 段/键表解析校验、外科手术式
* 保存(保留注释/未知内容,缺失段/键写回)、出厂模板生成、沉降去抖轮询
+1 -1
View File
@@ -247,7 +247,7 @@ ioboard_bits.c ← 纯逻辑:位序组装。只依赖 <stdint.h>,主机侧
2026-11-16 已在 **C 通道**上实测确认(信号接入 C 路 → 屏上只有 `DI_C` 显示「合」,
其余 7 路不动),即 A 在 LSB、H 在 MSB 的位序与通道隔离都正确。
其余 7 路尚未逐路验证;若某一路接反,症状是「该路动作时屏上亮的是另一路」。
UI 侧的遥信页 `Drivers/BSP/UI/ui_page_yx.c`(板级开入开出 12 行已并入该页)在文件头注释里做了同样的声明。
UI 侧的遥信页 `Drivers/BSP/UI/ui_page_yx.c` 文件头已改为引用本节(引第 3、6~7 条),不再复述。
7. **开入是电平检测,不是通断检测**(用户口径,2026-11-16):
本板开入测量的是**输入信号有没有 24V 高电平**,「导通」本身是测不出来的——
外部信号必须提供 24V,仅仅把回路接通而没有电平,开入不会动作。
+1 -1
View File
@@ -1,4 +1,4 @@
# Drivers/BSP/UI/ — LVGL UI 组件
# Drivers/BSP/UI/ — LVGL UI 组件
> 基于 LVGL 的界面实现:菜单树、内容页、通用组件、中文字库、待机页。
> **与 PC 模拟器共用同一套 UI 源码**(`simulator/` 只提供平台层)。
+1 -1
View File
@@ -1,4 +1,4 @@
/*
/*
* 模块名称:UI 中文位图字体(ui_font_cn_12,自动生成)
* 模块功能:中文子集 12px 位图字体(宋体;含 ▶ 箭头与全角逗号补回字形)
* 适用平台:STM32F407ZGTx / PC 模拟器(共用源码)
+1 -1
View File
@@ -1,4 +1,4 @@
/*
/*
* 模块名称:UI Network Sink Backend (平台后端接口)
* 模块功能:抽象 RemoDispBus 服务端的平台相关操作(LCDMEM 数据源 / 远端按键注入),
* 使 MCU 端与 PC 模拟器共用同一份 ui_net_sink.c 协议实现
+1 -1
View File
@@ -1,4 +1,4 @@
/*
/*
* 模块名称:UI Network Sink Backend (MCU 实现)
* 模块功能:RemoDispBus 服务端在 MCU 端的平台相关操作——
* 读取 LVGL 帧缓冲(LCDMEM 数据源)与经 ui_port 注入远端按键
+1 -1
View File
@@ -1,4 +1,4 @@
/*
/*
* 模块名称:UI Page RunLog (运行记录内容页)
* 模块功能:运行记录叶子节点(node 40)的内容页数据——动态列表,每条记录 2 行
* (偶数行 = 时间戳、奇数行 = 描述),可移选分页;数据源 = sys_log API
+1 -1
View File
@@ -1,4 +1,4 @@
/*
/*
* 模块名称:UI Page SelfTest (自检记录内容页)
* 模块功能:自检记录叶子节点(node 39)的内容页数据——动态列表,每条记录 2 行
* (偶数行 = 时间戳、奇数行 = 故障描述),可移选分页;数据源 = sys_log API
+13 -15
View File
@@ -75,27 +75,25 @@ typedef char yx_name_count_check[(sizeof(s_yx_name) / sizeof(s_yx_name[0]) == UI
* 措辞沿用原开入开出页:开入「合/分」(外部 24V 有/无),开出「吸合/释放」
* (继电器线圈被驱动/未驱动,见 ioboard.h 的开出极性宏注释)。
*
* 硬件层面的事实(反相链路、电平检测非通断检测、极性宏在驱动层的转换、位序与开出极性
* 的验证状态)详见 Drivers/BSP/IOBOARD/README.md 第 6 节第 3、6~7 条。
* 本文件不复述,避免两处详述漂移后互相矛盾。
*
* 这 12 行能看到什么、看不到什么(与 33 行点表遥信同等对待,别把板级状态当点表事实):
* 1. 开出这 4 行显示的是**软件影子寄存器**(ODR 镜像)——"我们让这一路吸合了",
* 不是继电器机械触点真闭合的实测反馈,本平台没有辅助触点回读通路。
* 2. 驱动里的 ioboard_do_read_level() 读的同样是 ODR,故它读回与本页恒等;
* 它只用来发现"有人在驱动之外写了这 4 根引脚的 ODR",不证明光耦导通。
* 3. 开出极性宏 IOBOARD_DO_LEVEL_ACTIVE 尚未按原理图核对;即便如此本页显示仍按
* 软件 mask 语义(极性在驱动层转换),只是结论只能算"按软件意图显示"。
* 4. 开入位序**已部分验证**:2026-11-16 在 C 通道实测——信号接入 C 路时只有 DI_C
* 显示「合」、其余 7 路不动,即"A 在 LSB、H 在 MSB"的位序与通道隔离成立。
* 其余 7 路尚未逐路验证;某一路接反的症状是该路动作时亮的是另一路。
* 逐路验证方法见 docs/硬件平台/开入开出实施说明.md §5.1。
* 4b. 开入测的是**电平不是通断**(用户口径 2026-11-16):要的是输入有没有 24V 高电平,
* 仅仅把回路导通测不出来。板上是反相链路(有 24V → 光耦导通 → 74HC165 引脚被拉低),
* 这个反相在驱动层由 ioboard.h 的 IOBOARD_DI_LEVEL_ACTIVE 转换,所以本页拿到的 mask
* 里 1 恒表示"有信号",本页不必也不应再判极性。
* 5. 这 12 行与上面 33 行**没有任何映射关系**:上面是 104 点表(协议事实、经 iec104 上送),
* 3. 这 12 行与上面 33 行**没有任何映射关系**:上面是 104 点表(协议事实、经 iec104 上送),
* 这里是板级 GPIO/74HC165 物理状态(未进点表、不上送)。同屏只是"一屏看全"。
* 6. valid 为 0 时显示「--」而不是「分/释放」:此时 mask 里可能还留着上一次的值,画成
* 4. valid 为 0 时显示「--」而不是「分/释放」:此时 mask 里可能还留着上一次的值,画成
* "分"等于把"没数据"伪装成"已复归"。真板子上开出四行会正常显示「吸合/释放」
* (板端 feed 走 ioboard_do_get() 取得到影子,dio_do_valid=1);只有 PC 模拟器构建
* 没有 ioboard 硬件时才恒为 0 显示「--」。上板看到「--」先查 feed 侧,不要改本页判定。
* 5. 拼接边界与页数:行 0~32 = 33 点遥信(下标即 104 点表 IOA-1),行 33~44 = 板级
* 开入开出(DI_A..DI_H + KO6/TRIP/ERT/CLZ,名表见下方 s_dio_name);合计
* 33 + 12 = 45 行,45 / 8 行每页 = 5 满页 + 1 余页 = 6 页。拼接是**纯行号偏移**:
* 没有第二套取数分支边界要维护,pg_refresh 里 `a_row >= UI_DATA_YX_N` 即转板级段。
*/
#define DIO_ROW_N ((uint16_t)(UI_DATA_DI_N + UI_DATA_DO_N))
#define DIO_DI_ON "合"
@@ -188,7 +186,7 @@ static void pg_sync(void) {
}
/*
* 函数功能:总行数(固定 33 点,不随有效性增减)
* 函数功能:总行数(固定 45 行 = 33 点遥信 + 12 行板级开入开出,不随有效性增减)
* 入口参数:无
* 返回值:行数 uint16_t
* 限定条件:框架绘制/翻页链内
@@ -201,7 +199,7 @@ static uint16_t pg_count(void) {
/*
* 函数功能:逐行取数(名 = 固定名表,值 = 三个位图映射出的词)
* 入口参数:a_row - 行下标(0..32) uint16_t
* 入口参数:a_row - 行下标(0..32 = 点表遥信,33..44 = 板级开入开出) uint16_t
* a_name - 名输出缓冲(UI_BUF_STRLEN) char *
* a_value - 值输出缓冲 char *
* 返回值:无
@@ -264,7 +262,7 @@ static void pg_refresh(uint16_t a_row, char *a_name, char *a_value) {
/*
* 页面描述符(外部链接:生成物 ui_page_registry.c 按菜单树 #page=yx 绑定引用):
* 固定 33 行的动态页(rows=NULL + count_cb/refresh),8 行/页 = 5 页;band_h 必须 >0
* 固定 45 行的动态页(rows=NULL + count_cb/refresh),8 行/页 = 5 满页 + 1 余页 = 6 页;band_h 必须 >0
* (selectable 页选中行是黑字,无白带即不可见,同记录页约定)
*/
const content_page_def_t ui_page_yx_desc = {
+63 -14
View File
@@ -21,8 +21,8 @@
这正是目的:名单散在三处而无人同步,等于没有名单。
用法: .venv/Scripts/python.exe scripts/check_bom_drift.py [文件名...] [--all] [--selftest]
不带文件名也不带 --all 时(pre-commit 的常规形态)只核传进来的文件;--all 核全仓
跟踪文件(人工审计/排查用,比 HEAD 全量比一遍慢,但不依赖"改没改过");--selftest
在临时 git 仓库里自证四条判定(含票面要求的两条边界)。
跟踪**及未跟踪**文件(人工审计/排查用,比 HEAD 全量比一遍慢,但不依赖"改没改过");--selftest
在临时 git 仓库里自证六条判定(含新增文件必须带 BOM、名单外不越权、存量两方向)。
退出码: 0 = 通过;1 = 有 BOM 漂移或名单不一致;2 = 用法或环境错误(不在 git 仓库内等)
创建日期:2026-10-25(道E task-20)
"""
@@ -36,6 +36,11 @@ import tempfile
BOM = bytes((0xEF, 0xBB, 0xBF))
# 名单项:(路径, 匹配方式),prefix = 目录内全部文件,eq = 恰好这一个文件
# 名单的语义是"这些文件**必须**带 BOM",不是"这些文件曾经带过 BOM":新增文件按此判
# (见 check_paths 的 hp is None 分支),存量文件若在 HEAD 里就没有 BOM 仍按历史状态放行,
# 但那属于名单登记不实,应逐个补齐后让名实相符——2026-11-16 补的是 App/cfg/cfg_file.c
# (ARMCC 编译的手写源文件、含数百行中文注释,正是 BOM 铁律要保护的对象,HEAD 无 BOM 纯属
# 历史疏漏)。补完后本名单内不再存在"登记了却没 BOM"的存量文件,故此处不设豁免名单。
BOM_LIST = [
("Drivers/BSP/UI/", "prefix"),
("App/task/ui_task.c", "eq"),
@@ -104,7 +109,17 @@ def check_paths(paths):
continue
hp = head_prefix(p)
if hp is None:
continue # 新增文件:HEAD 无 BOM 可谈,不误报(票面边界①)
# 新增文件(HEAD 里没有):名单内的就该有 BOM。这一支原先直接 continue,
# 于是"新建文件忘 BOM"永远拦不住——Scripts 自查实测:在 Drivers/BSP/UI/
# 造一个无 BOM 的未跟踪文件,--all 照样报"无漂移"。那正是本门禁最贵的一类
# 漏检:新建时没人改到它,等下一次有人编辑才炸,且炸在 ARMCC 的假语法错上。
n += 1
wp = work_prefix(p)
if wp is None:
continue # 已在工作区删除:不是本门禁的事
if wp != BOM:
bad.append(p)
continue
n += 1
if hp != BOM:
continue # HEAD 本来就没 BOM:不报(票面边界②)
@@ -117,10 +132,21 @@ def check_paths(paths):
def tracked_files():
data = git_run(["ls-files", "-z"])
"""扫描全集 = 已跟踪 + 未跟踪(不含 gitignore)。
只用 ls-files 会漏掉"新建还没 add"的文件,而那恰恰是 BOM 门禁最该看住的时刻:
新建时忘 BOM 没人会被绊到,等下一次有人编辑该文件才炸,且炸在 ARMCC 的假语法错上
(错的位置和内容都不指向真因)。--others --exclude-standard 把未跟踪但非 gitignore
的文件一并纳入,使 --all 与"提交后会被跟踪的集合"一致。
"""
data = git_run(["ls-files", "-z", "--cached", "--others", "--exclude-standard"])
if data is None:
return []
return [x for x in data.decode("utf-8", "replace").split(chr(0)) if x]
seen = []
for x in data.decode("utf-8", "replace").split(chr(0)):
if x and x not in seen:
seen.append(x)
return seen
def list_crosscheck():
@@ -170,9 +196,11 @@ def list_crosscheck():
def report(bad):
print("[FAIL] 以下文件的 BOM 被剥掉了(HEAD 有 EF BB BF,工作区没有):")
print("[FAIL] 以下名单内文件的 BOM 缺失或被剥掉(工程约定要求 EF BB BF 开头):")
for p in bad:
print(" " + p)
print(" 两种情况都算:① 已入库带 BOM 的文件被编辑工具剥掉了;② 名单内**新建**文件")
print(" 压根没带 BOM(HEAD 里没有它,但进了名单目录就必须带)。")
print(" 补救:只把 3 个字节 EF BB BF 补回文件最前面;**不要**整文件重写——")
print(" 用 PowerShell/Set-Content 之类整文件重写会按系统默认编码重打中文,")
print(" 那会把可修的丢 BOM 变成不可修的 U+FFFD(AGENTS 铁律第 1/2 条)。")
@@ -181,7 +209,7 @@ def report(bad):
def selftest():
"""在临时 git 仓库里跑四条判定(含票面要求的两条边界),任一不符返回 1。"""
"""在临时 git 仓库里跑六条判定(含新增文件、名单外、存量两方向边界),任一不符返回 1。"""
ok = True
tmp = tempfile.mkdtemp(prefix="bomdrift_")
old = os.getcwd()
@@ -222,12 +250,19 @@ def selftest():
with open(bomf, "wb") as f:
f.write(body)
# 边界①:HEAD 里根本没有的新文件(哪怕在名单目录内)不得误报
# 边界①:HEAD 里根本没有的新文件**在名单内**就必须带 BOM(票面边界①,2026-11-16 收紧)
# 旧行为是直接放行,正是"新建文件忘 BOM 永远拦不住"的那层漏报。
with open("Drivers/BSP/UI/new.c", "wb") as f:
f.write(b"/* brand new, no BOM */")
bad, n = check_paths(["Drivers/BSP/UI/new.c"])
if bad or n != 0:
print("[SELFTEST FAIL] 新增无 BOM 文件被误报")
if bad != ["Drivers/BSP/UI/new.c"] or n != 1:
print("[SELFTEST FAIL] 名单内新增无 BOM 文件没被拦住(本次修复的主用例失守)")
ok = False
with open("Drivers/BSP/UI/new.c", "wb") as f:
f.write(BOM + b"/* brand new, with BOM */")
bad, n = check_paths(["Drivers/BSP/UI/new.c"])
if bad or n != 1:
print("[SELFTEST FAIL] 名单内新增文件**带** BOM 被误报")
ok = False
os.remove("Drivers/BSP/UI/new.c")
@@ -241,24 +276,38 @@ def selftest():
# 名单外文件即使 BOM 丢了也不报(门禁不越权管名单外)
with open("Lib/lv_conf.h", "wb") as f:
f.write(b"x")
with open("App/cfg/cfg_file.c", "wb") as f:
f.write(b"/* listed but never committed, no BOM */")
bad, n = check_paths(["App/cfg/cfg_file.c"])
if bad or n != 0:
print("[SELFTEST FAIL] 名单内但不在 HEAD 的文件被误报")
if bad != ["App/cfg/cfg_file.c"] or n != 1:
print("[SELFTEST FAIL] 名单内新增无 BOM 文件(eq 项)没被拦住")
ok = False
bad, n = check_paths(["README.md"])
if n != 0:
print("[SELFTEST FAIL] 名单外文件参与了检查")
ok = False
with open("Lib/lv_conf.h", "wb") as f:
f.write(BOM + b"/* lv_conf, already has BOM in HEAD */")
git_run(["add", "Lib/lv_conf.h"])
git_run(["commit", "-q", "-m", "lv_conf"])
with open("Lib/lv_conf.h", "wb") as f:
f.write(b"/* BOM stripped by an editor */")
bad, n = check_paths(["Lib/lv_conf.h"])
if bad != ["Lib/lv_conf.h"] or n != 1:
print("[SELFTEST FAIL] 已入库带 BOM 的文件被剥掉后没报(原有主用例失守)")
ok = False
finally:
os.chdir(old)
print("[SELFTEST] " + ("4 条判定全过(含两条票面要求的边界)" if ok else "有判定未过"))
print("[SELFTEST] " + ("6 条判定全过(含新增文件必须带 BOM、名单外不越权等边界)"
if ok else "有判定未过"))
return 0 if ok else 1
def main():
ap = argparse.ArgumentParser(description="BOM 漂移检查(bom-guard 钩子实现)")
ap.add_argument("files", nargs="*", help="待核文件(仓库根相对路径)")
ap.add_argument("--all", action="store_true", help="核 git 跟踪的全部文件")
ap.add_argument("--all", action="store_true",
help="核 git 跟踪的与未跟踪(不含 gitignore)的全部文件")
ap.add_argument("--selftest", action="store_true", help="临时仓库自证判定")
args = ap.parse_args()
+26
View File
@@ -549,8 +549,34 @@ def main():
verify_coverage(OUT) # 生成后校验:字符集全部码位必须进字体(防静默丢字)
fix_trailing_newline(OUT) # 规范化末尾换行(pre-commit end-of-file-fixer)
normalize_project_conventions(OUT, args.size, args.bpp) # 对齐工程约定(文件头/包含路径/版本守卫压平)
if ensure_bom(OUT): # 必须最后一步:前面的中间步骤会整文件重写,BOM 补早了会被冲掉
print('已补 UTF-8 BOM(Drivers/BSP/UI/ 整目录带 BOM 的工程约定,幂等)')
print('OK %d bytes -> %s' % (os.path.getsize(OUT), OUT))
def ensure_bom(path):
"""保证生成物带头 BOM(EF BB BF),且幂等。
为什么要这一步:`Drivers/BSP/UI/` 整目录是工程约定的带 BOM 名单(AGENTS 铁律第 2 条),
目录里其它生成物(如菜单生成器产物)都是带头的,字体是这个目录里唯一会掉队的生成物——
因为本脚本每次都在 :544 调 lv_font_conv **整文件重写**输出,产物天然无 BOM;后面几步虽然
各自读 has_bom 再原样回写,但那是"读到的已经是没有 BOM 的那份",于是 `has_bom` 恒为 False,
"保留原样"压根无从发生(手动补的 BOM 下一轮就被覆盖掉)。
为什么不改成"让每步都保留":真正决定这里要不要 BOM 的是**工程约定**,不是上游产物,所以
收敛在末尾一步显式补,比在 6 个中间步骤里各自维持一个 has_bom 便宜得多,也不依赖调用顺序
(本次踩的坑正是"装配顺序把事实冲掉了")。
幂等:已有 BOM 直接返回,不重复加。只碰最前面 3 字节,字体字节/字形数/glyph_id 全不受影响。
"""
with open(path, 'rb') as fp:
raw = fp.read()
if raw.startswith(b'\xef\xbb\xbf'):
return False
with open(path, 'wb') as fp:
fp.write(b'\xef\xbb\xbf' + raw)
return True
if __name__ == '__main__':
main()
+39
View File
@@ -10,10 +10,49 @@
## 使用方式
两种模式,**写不写盘是唯一区别**;两者的生成/注册逻辑共用同一段代码(`plan_prune` +
`plan_sync` 只算不写,写盘模式再落盘),所以"检查说的"与"写入做的"不可能漂移。
### 写入模式(默认,不带参数)
```bash
& '.venv\Scripts\python.exe' tools/menu_gen/gen_menu.py
```
重写 4 个生成物(`ui_menu_tab.c/.h`、`ui_page_registry.c/.h`)+ 同步双端注册
(`MDK-ARM/STM32F407-Demo.uvprojx`、`simulator/CMakeLists.txt`)。
输出里的箭头行(`-> Drivers/BSP/UI/ui_menu_tab.h` 等)**表示文件确实被重写了**——
注意重写不代表内容变了:内容相同时字节不变、`git status` 也就没有 diff。
**什么时候用**:改了 `ui_menu_tree.txt` 或增删页面实例后,这是唯一会刷新生成物的途径。
### 只读模式(`--check`)
```bash
& '.venv\Scripts\python.exe' tools/menu_gen/gen_menu.py --check
```
只报告"工作区生成物是否已与 `ui_menu_tree.txt` 同步",**一次写操作都不发生**,
也不建临时文件;双端注册同样只比对不写入。退出码即结论:
| 情形 | 输出 | 退出码 |
|---|---|---|
| 已同步 | `[OK] up-to-date: 4 个生成物与双端注册均与 ui_menu_tree.txt 一致` | 0 |
| 有漂移 | 每个待刷新文件一行 `[STALE] would rewrite <路径> (原因)`,末行给总数 | 1 |
`[STALE]` 行**刻意不使用箭头符号**——那个符号在只读场景里会被误读成"已经写过了"。
差异摘要会给出首个不同的行号,或"需删 N 条死引用 / 需补 N 条注册",便于直接定位。
**什么时候用**:改完菜单树、提交前想确认"我这笔改动是否已经重跑过生成器",
或 review 别人的菜单改动时。它不替代强制门禁——见下节。
## 与 `check_generated_fresh.py` 的分工
`scripts/check_generated_fresh.py`(pre-commit 钩子「生成器幂等性」)把生成器拷到临时目录
重跑再逐字节比对,是**强制的红绿门禁**,保证"生成物比生成器旧"必 FAIL。
`--check` 是**给人看差异的**:门禁只说红或绿,`--check` 说差在哪个文件、第几行、缺哪条注册。
日常改菜单用 `--check` 自查,提交时由门禁兜底,两者都要在。
菜单树输入的权威副本:仓库根 `ui_menu_tree.txt`。
## ⚠️ 注意
+124 -23
View File
@@ -19,7 +19,9 @@
改菜单/加页面只需编辑 ui_menu_tree.txt + 写页面实例文件,然后重跑本脚本。
用法(仓库根目录或任意目录均可,脚本自动定位仓库根):
python tools/menu_gen/gen_menu.py
python tools/menu_gen/gen_menu.py 写入模式:重写生成物 + 双端注册(默认,行为不变)
python tools/menu_gen/gen_menu.py --check 只读模式:只报告工作区是否已是最新,绝不写文件
一致 exit 0([OK]);不一致 exit 1([STALE] + 差异摘要)
"""
import os
import re
@@ -559,12 +561,15 @@ def _write_text(path, text):
fp.write(text)
def prune_registration():
"""删掉两份注册表里指向**已不存在的 ui_page_*.c** 的死条目,返回被删项。
def plan_prune():
"""算出"删掉两份注册表里指向**已不存在的 ui_page_*.c** 的死条目"后的文本。
与 sync_registration 对称:删页/改名后残留的条目会让 Keil 直接报
与 plan_sync 对称:删页/改名后残留的条目会让 Keil 直接报
"cannot open source input file"(模拟器同理报源文件缺失),属必须清掉的死引用;
只匹配 ui_page_*.c 这一类(生成器自己负责的范围),不碰其它组/其它模块的条目。
**本函数只算不写**(返回 (新文本, 被删项列表)),由调用方决定写盘还是只比对——
--check 模式必须能拿到同样的结果却不碰磁盘,这是把"算"与"写"拆开的唯一理由。
"""
pruned = []
@@ -581,8 +586,6 @@ def prune_registration():
return ''
new_uv = blk_re.sub(_drop, uv)
if new_uv != uv:
_write_text(UVPROJX, new_uv)
cm = _read_text(CMAKELISTS)
line_re = re.compile(r'^[ \t]*\$\{UI_DIR\}/(ui_page_[a-z0-9_]*\.c)[ \t]*\r?\n', re.M)
@@ -595,22 +598,23 @@ def prune_registration():
return ''
new_cm = line_re.sub(_drop_cm, cm)
if new_cm != cm:
_write_text(CMAKELISTS, new_cm)
return pruned
return (new_uv, new_cm), pruned
def sync_registration(filenames):
"""把 UI 目录下的 .c 文件名补进 uvprojx 与 CMakeLists 的显式列表,返回实际插入项。
def plan_sync(filenames, uv, cm):
"""算出"把 filenames 补进 uvprojx 与 CMakeLists 显式列表"后的文本。
只做定点插入、不重排不改写其余内容:uvprojx 由 UV4 维护,任何无关改动都会污染
diff("UV4 抖动不入库"铁律);已存在则不动(幂等,重复跑不产生 diff)。
**本函数只算不写**:uv / cm 由调用方传入(可来自磁盘,也可来自 plan_prune 的产物),
返回 (新 uv, 新 cm, 插入项列表)。--check 与写盘模式走同一条计算路径,
这样"检查说的"与"写入做的"不可能漂移。
"""
inserted = []
# ① uvprojx:Drivers/BSP/UI 组的 <Files> 末尾补 <File> 块
uv = _read_text(UVPROJX)
gi = uv.find('<GroupName>%s</GroupName>' % UI_GROUP)
if gi < 0:
sys.exit('ERROR: uvprojx 找不到组 %r,无法自动注册(请检查工程结构)' % UI_GROUP)
@@ -630,10 +634,8 @@ def sync_registration(filenames):
inserted.append(('uvprojx', fn))
if add:
uv = uv[:line_start] + add + uv[line_start:]
_write_text(UVPROJX, uv)
# ② CMakeLists:set(UI_SOURCES ...) 列表末尾补 ${UI_DIR}/xxx.c
cm = _read_text(CMAKELISTS)
si = cm.find('set(UI_SOURCES')
if si < 0:
sys.exit('ERROR: CMakeLists.txt 找不到 set(UI_SOURCES ...),无法自动注册')
@@ -649,12 +651,70 @@ def sync_registration(filenames):
inserted.append(('CMakeLists', fn))
if add:
cm = cm[:line_start] + add + cm[line_start:]
return uv, cm, inserted
def apply_registration(needed):
"""写盘模式:先清死引用再补缺目(改名场景两头都覆盖),返回 (pruned, inserted)。"""
(new_uv, new_cm), pruned = plan_prune()
if new_uv != _read_text(UVPROJX):
_write_text(UVPROJX, new_uv)
if new_cm != _read_text(CMAKELISTS):
_write_text(CMAKELISTS, new_cm)
# 补缺目要基于"刚清完死引用"的文本继续算,再落盘
uv, cm, inserted = plan_sync(needed, new_uv, new_cm)
if uv != new_uv:
_write_text(UVPROJX, uv)
if cm != new_cm:
_write_text(CMAKELISTS, cm)
return inserted
return pruned, inserted
def main():
def check_registration(needed):
"""只读模式:算出双端注册应有的最终文本,与磁盘逐字符比对。
返回 (差异列表, 待删项, 待补项);差异列表为 [(标签, 相对路径, 摘要)]。
**不写任何文件、不建临时文件**——只在内存里跑与写盘模式相同的两个 plan 函数,
因此"检查说的"与"写入做的"不可能漂移。
比较基准是**最终态**(清死引用 + 补缺目之后)对磁盘原文本,不是拿中间态比中间态:
否则同一处差异会被算两次,且 diff 摘要会误导。
"""
diffs = []
(pruned_uv, pruned_cm), pruned = plan_prune()
cur_uv = _read_text(UVPROJX)
cur_cm = _read_text(CMAKELISTS)
final_uv, final_cm, inserted = plan_sync(needed, pruned_uv, pruned_cm)
for label, path, cur, final in (
('uvprojx', UVPROJX, cur_uv, final_uv),
('CMakeLists', CMAKELISTS, cur_cm, final_cm)):
if cur == final:
continue
n_prune = len([1 for t, _ in pruned if t == label])
n_add = len([1 for t, _ in inserted if t == label])
parts = []
if n_prune:
parts.append('需删 %d 条死引用' % n_prune)
if n_add:
parts.append('需补 %d 条注册' % n_add)
if not parts:
parts.append('内容有差异(行数 %d 到 %d)' % (cur.count('\n'), final.count('\n')))
diffs.append((label, os.path.relpath(path, ROOT), ','.join(parts)))
return diffs, pruned, inserted
def main(argv=None):
argv = list(sys.argv[1:] if argv is None else argv)
if argv and argv not in (['--check'], ['-h'], ['--help']):
sys.exit('ERROR: 未知参数 %s\n用法: gen_menu.py [--check]' % ' '.join(argv))
readonly = argv == ['--check']
if not os.path.exists(SRC):
sys.exit('ERROR: 未找到 ui_menu_tree.txt(应在仓库根目录)')
text = open(SRC, encoding='utf-8-sig').read()
@@ -670,17 +730,47 @@ def main():
header, body, menus, max_depth = emit(nodes)
reg_h, reg_c = emit_registry(bound, password_stem)
# 双端注册:注册表本身 + 每个绑定页实例(密码页也必须是已绑定或 @password 声明的)
needed = ['ui_page_registry.c'] + sorted({'ui_page_%s.c' % p for _, _, p in bound})
generated = ((OUT_H, header), (OUT_C, body),
(OUT_REG_H, reg_h), (OUT_REG_C, reg_c))
if readonly:
# --check:全程只读。四个生成物按"写盘会产出的同一段字节"对比磁盘,
# 双端注册走 plan_prune + plan_sync 的纯计算,一次 open(...,'w') 都不发生。
stale = []
for path, content in generated:
try:
with open(path, 'r', encoding='utf-8-sig', newline='') as fp:
disk = fp.read()
except OSError:
stale.append((os.path.relpath(path, ROOT), '文件不存在'))
continue
if disk != content:
stale.append((os.path.relpath(path, ROOT), _diff_summary(disk, content)))
reg_diffs, _pruned, _inserted = check_registration(needed)
if stale or reg_diffs:
for rel, summary in stale:
print('[STALE] would rewrite %s (%s)' % (rel, summary))
for _label, rel, summary in reg_diffs:
print('[STALE] would rewrite %s (%s)' % (rel, summary))
print('[STALE] %d 个生成物与 ui_menu_tree.txt 不一致;'
'本次未写任何文件,执行不带参数的 gen_menu.py 即可刷新'
% (len(stale) + len(reg_diffs)))
return 1
print('[OK] up-to-date: %d 个生成物与双端注册均与 ui_menu_tree.txt 一致'
% len(generated))
return 0
# Drivers/BSP/UI/* 约定为 UTF-8 带 BOM(同 ui_menu.c);字符串字面量含中文,
# 无 BOM 时 cl.exe(代码页 936) 会按 GBK 误读 UTF-8 字节导致字符串解析错乱。
for path, content in ((OUT_H, header), (OUT_C, body),
(OUT_REG_H, reg_h), (OUT_REG_C, reg_c)):
for path, content in generated:
with open(path, 'w', encoding='utf-8-sig', newline='') as fp:
fp.write(content)
# 双端注册:注册表本身 + 每个绑定页实例(密码页也必须是已绑定或 @password 声明的)
needed = ['ui_page_registry.c'] + sorted({'ui_page_%s.c' % p for _, _, p in bound})
pruned = prune_registration() # 先清死引用,再补缺目(改名场景两头都覆盖)
inserted = sync_registration(needed)
pruned, inserted = apply_registration(needed)
protected = sum(1 for _, _, _, p, _ in nodes if p)
print('nodes=%d menu=%d leaf=%d protected=%d max_depth=%d'
@@ -696,7 +786,18 @@ def main():
print(' registered %-12s %s' % (target, fn))
if not pruned and not inserted:
print(' registration up-to-date (uvprojx + CMakeLists unchanged)')
return 0
def _diff_summary(disk, content):
"""给 --check 的 STALE 行找第一处差异,帮人直接跳到出错的地方。"""
disk_lines = disk.split('\n')
new_lines = content.split('\n')
for i in range(min(len(disk_lines), len(new_lines))):
if disk_lines[i] != new_lines[i]:
return '首个差异在第 %d 行' % (i + 1)
return '行数 %d 到 %d' % (len(disk_lines), len(new_lines))
if __name__ == '__main__':
main()
sys.exit(main())