#!/usr/bin/env node /* ========================================================================== 术语表自检:扫描所有模块章节页,检查示例命名是否统一 用法:node tools/check-glossary.js [站点根目录,默认本文件的上一级] 规则写在 tools/glossary.json 里(canonical 是正确写法,forbidden 是正则 + 提示)。 为什么要单独一个脚本:check-pages.js 管结构与链接,这个脚本管「一个概念一个名字」, 两者失败原因不同,分开跑更容易定位;也可以单独挂到 CI 的 lint 阶段。 退出码:0 全部通过;1 有命中(列出文件、行号、片段与修改建议)。 ========================================================================== */ const fs = require("fs"); const path = require("path"); const root = process.argv[2] || path.resolve(__dirname, ".."); const MODDIR = path.join(root, "modules"); const glossary = JSON.parse( fs.readFileSync(path.join(__dirname, "glossary.json"), "utf8") .replace(/\/\*[\s\S]*?\*\//g, "") .replace(/^\s*\/\/.*$/gm, "") ); const rules = glossary.forbidden.map(r => ({ re: new RegExp(r.re, "g"), hint: r.hint, src: r.re })); function walk(dir, out = []) { for (const e of fs.readdirSync(dir, { withFileTypes: true })) { const p = path.join(dir, e.name); if (e.isDirectory()) walk(p, out); else if (e.name.endsWith(".html")) out.push(p); } return out; } const files = fs.existsSync(MODDIR) ? walk(MODDIR) : []; const hits = []; for (const file of files) { const rel = path.relative(root, file).replace(/\\/g, "/"); const lines = fs.readFileSync(file, "utf8").split(/\r?\n/); lines.forEach((line, i) => { for (const rule of rules) { rule.re.lastIndex = 0; const m = rule.re.exec(line); if (!m) continue; // 允许在行尾写 // glossary-ok 明确豁免(例如引用第三方系统的真实表名) if (/glossary-ok/.test(line)) continue; hits.push({ rel, line: i + 1, text: m[0], hint: rule.hint, snippet: line.trim().slice(0, 110) }); } }); } if (!hits.length) { console.log(`OK 术语统一:扫描 ${files.length} 个页面,未发现命名漂移。`); process.exit(0); } console.error(`发现 ${hits.length} 处命名漂移(共 ${files.length} 个页面):\n`); const byFile = new Map(); for (const h of hits) { if (!byFile.has(h.rel)) byFile.set(h.rel, []); byFile.get(h.rel).push(h); } for (const [rel, list] of byFile) { console.error(`${rel}(${list.length} 处)`); for (const h of list.slice(0, 12)) { console.error(` :${h.line} 「${h.text}」→ ${h.hint}`); console.error(` ${h.snippet}`); } if (list.length > 12) console.error(` …… 其余 ${list.length - 12} 处省略`); } console.error("\n改完重跑本脚本;确认某处是刻意保留的,可在该行加注释 // glossary-ok 豁免。"); process.exit(1);