Files
materials/knowledge/linux/tools/check-chapter.js
huanghaosheng 3ccd17cad8 refactor: SRE 学习路径抽成独立板块「学习路线」,与知识库同级
- knowledge/sre-learning-path/ -> 学习路线/sre-learning-path/(git mv,404 个文件保留改名历史)
- 导航页新增模块 learning-path(num 03,project 顺延 04),知识库回到 4 份资料
- check-portal.js / add-back-links.js 支持模块目录独立于 id(m.dir || m.id),
  路由仍为 #/learning-path/sre-learning-path,URL 保持 ASCII
- portal.js 快捷键提示按模块数生成、复制板块目录用真实目录名
- docker / linux / nginx 的外链、build-nav.js 生成器与自检白名单改指 ../../学习路线/sre-learning-path/
- 399 个站点页面与全部知识站点的返回入口由 tools/add-back-links.js 重算
  (标签改为「学习路径 › SRE 从零到成熟学习路径」)
- .sre-s23 生成脚手架与根 README、index.html 同步到新路径与新板块数

自检:check-portal / add-back-links --check 全绿;
学习路线站点 399 页与 docker、linux、nginx 的 check-pages 全部通过。
2026-10-14 23:33:29 +08:00

169 lines
9.2 KiB
JavaScript
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 node
/* ==========================================================================
Linux 专题 · 单章自检(写章节时用这个,比全站 check-pages.js 更聚焦)
用法:node tools/check-chapter.js 04-perm.html
node tools/check-chapter.js # 不给参数则检查所有 NN-*.html
只校验「作者需要负责」的东西,不校验侧栏/上下章/页脚(那些由
tools/build-nav.js 在收尾时统一生成,中途为空是正常的):
- 模板结构:title / meta description / meta keywords / article / 四个占位块 /
doc.css / doc.js / 主题按钮 / 不越界链接
- 代码块:data-lang 是否标注且在允许列表内、块内 < 是否转义
- 标签配对:div/section/article/aside/nav/main/details/table/ul/ol/li
- 章节:h2 有 id、h3 全部有 id 且以 sec-章号- 开头、小节数 3–10
- 组件:至少 1 个 .box、至少 1 个表格或卡片组、至少 1 处实战落点
- 体量:至少 3 个代码块、正文不少于 2800 字
- 链接:跨章链接指向的文件若尚未生成会标为提示(可忽略),存在则校验锚点
========================================================================== */
const fs = require("fs");
const path = require("path");
const root = path.resolve(__dirname, "..");
const problems = [];
const hints = [];
const LANGS = ["bash", "shell", "sh", "console", "text", "plain", "yaml", "yml", "json", "toml",
"conf", "config", "ini", "systemd", "unit", "fstab", "crontab", "ssh", "sshconfig", "log",
"diff", "csv", "xml", "http", "nginx", "makefile", "dockerfile", "properties",
"go", "javascript", "js", "typescript", "ts", "python", "java", "c", "cpp", "sql",
"powershell", "promql", "regex", "awk", "sed", "lua"];
const stripTags = s => s.replace(/<[^>]+>/g, "");
const norm = s => s.replace(/\s+/g, "").length;
const args = process.argv.slice(2);
const files = args.length
? args
: fs.readdirSync(root).filter(f => /^\d\d-.*\.html$/.test(f)).sort();
if (!files.length) {
console.error("没有找到章节文件。用法:node tools/check-chapter.js 04-perm.html");
process.exit(1);
}
/* 已存在章节的 id 索引,用于跨章锚点校验 */
const idIndex = new Map();
for (const f of fs.readdirSync(root).filter(f => /^\d\d-.*\.html$/.test(f)).concat(["index.html"])) {
if (!fs.existsSync(path.join(root, f))) continue;
idIndex.set(f, new Set([...fs.readFileSync(path.join(root, f), "utf8")
.matchAll(/\sid="([^"]+)"/g)].map(m => m[1])));
}
for (const f of files) {
const p = path.join(root, f);
if (!fs.existsSync(p)) { problems.push(`${f}: 文件不存在`); continue; }
if (!/^\d\d-.*\.html$/.test(f)) { problems.push(`${f}: 文件名必须是 NN-slug.html`); continue; }
const html = fs.readFileSync(p, "utf8");
const markup = html.replace(/<script[\s\S]*?<\/script>/g, "");
const num = parseInt(f.slice(0, 2), 10);
const own = [];
/* ---------------- 结构 ---------------- */
if (!new RegExp(`<title>[^<]*第 ${num} 章[^<]*</title>`).test(html)) own.push("title 里应含「第 N 章」");
if (!/<article>/.test(html)) own.push("缺少 <article>");
if (!html.includes('id="chapters"')) own.push("缺少侧栏 <nav id=\"chapters\">");
if (!html.includes('class="chapnav"')) own.push("缺少 <p class=\"chapnav\"></p>");
if (!html.includes('class="pager"')) own.push("缺少 <nav class=\"pager\"></nav>");
if (!html.includes('class="foot"')) own.push("缺少 <p class=\"foot\"></p>");
if (!html.includes('href="assets/doc.css"')) own.push("doc.css 路径不对");
if (!html.includes('src="assets/doc.js"')) own.push("doc.js 路径不对");
if (!html.includes('id="themeBtn"')) own.push("缺少主题切换按钮");
if (!html.includes('href="index.html"')) own.push("缺少返回总目录链接");
if (!/class="brand"/.test(html)) own.push("缺少 topbar 品牌区");
if (!/<h2 id="ch\d+"><span class="n">\d+<\/span>/.test(html)) own.push("章标题格式应为 <h2 id=\"chN\"><span class=\"n\">N</span>标题</h2>");
if (!/class="lead"/.test(html)) own.push("缺少 <div class=\"lead\">");
const desc = (html.match(/<meta name="description" content="([^"]*)"/) || [, ""])[1];
if (desc.trim().length < 20) own.push(`meta description 太短或缺失(${desc.length} 字)`);
const keys = (html.match(/<meta name="keywords" content="([^"]*)"/) || [, ""])[1];
if (keys.trim().length < 6) own.push(`meta keywords 太短或缺失(${keys.length} 字)`);
if (/href="\.\.\/(?!docker\/|\.\.\/学习路线\/sre-learning-path\/)/.test(markup)) {
own.push("站内链接不应跑出本资料目录(只允许 ../docker/ 与 ../../学习路线/sre-learning-path/)");
}
/* ---------------- 代码块 ---------------- */
const pres = markup.match(/<pre[\s\S]*?<\/pre>/g) || [];
pres.forEach((blk, i) => {
if (!/data-lang=/.test(blk)) own.push(`第 ${i + 1} 个 <pre> 未标注 data-lang`);
const body = blk.replace(/^<pre[^>]*>/, "").replace(/<\/pre>$/, "");
if (/</.test(body)) own.push(`第 ${i + 1} 个 <pre> 内有未转义的 <(应为 &lt;)`);
});
for (const m of markup.matchAll(/<pre data-lang="([^"]*)"/g)) {
if (!LANGS.includes(m[1])) own.push(`data-lang="${m[1]}" 不在允许列表里(见 SPEC 第 2 节)`);
}
if (pres.length < 3) own.push(`代码块过少(${pres.length}),至少 3 个`);
/* ---------------- 标签配对 ---------------- */
for (const t of ["div", "section", "article", "aside", "nav", "main", "details", "table", "ul", "ol", "li"]) {
const o = (markup.match(new RegExp("<" + t + "(?=[\\s>])", "g")) || []).length;
const c = (markup.match(new RegExp("</" + t + ">", "g")) || []).length;
if (o !== c) own.push(`<${t}> 开合不匹配 ${o}/${c}`);
}
/* ---------------- 组件构成 ---------------- */
if (!/class="box (note|tip|warn|danger|ok|case|lab)"/.test(html)) own.push("没有任何 .box 提示框");
if (!/class="tablewrap"/.test(html) && !/class="cards"/.test(html)) own.push("既没有表格也没有卡片组");
if (!/class="box case"|class="box lab"|实战|实际用法/.test(html)) {
own.push("缺少「开发/运维实际用法」落点(.box case / .box lab / 标题含实战)");
}
/* ---------------- 小节 ---------------- */
const h3 = [...html.matchAll(/<h3 id="([^"]+)">([\s\S]*?)<\/h3>/g)];
const h3any = (html.match(/<h3[ >]/g) || []).length;
if (h3.length !== h3any) own.push(`有 ${h3any - h3.length} 个 h3 未补 id`);
if (h3.length < 3) own.push(`小节过少(${h3.length}),至少 3 个`);
if (h3.length > 10) own.push(`小节过多(${h3.length}),最多 10 个`);
const seen = new Set();
const secOrder = [];
for (const m of h3) {
if (!m[1].startsWith(`sec-${num}-`)) own.push(`小节 id "${m[1]}" 应以 sec-${num}- 开头`);
if (seen.has(m[1])) own.push(`小节 id 重复:${m[1]}`);
seen.add(m[1]);
/* 标题文本必须带「N.M」编号,且与 id 里的序号一致 */
const title = stripTags(m[2]).replace(/&nbsp;/g, " ").trim();
const label = title.match(/^(\d+)\.(\d+)\b/);
const idSeq = m[1].slice(`sec-${num}-`.length);
if (!label) own.push(`小节标题缺少「${num}.M」编号:${title.slice(0, 30)}`);
else {
if (label[1] !== String(num)) own.push(`小节标题编号与章号不符:${title.slice(0, 30)}`);
if (label[2] !== idSeq) own.push(`小节标题编号 ${label[1]}.${label[2]} 与 id ${m[1]} 不一致`);
secOrder.push(parseInt(label[2], 10));
}
}
for (let i = 1; i < secOrder.length; i++) {
if (secOrder[i] !== secOrder[i - 1] + 1) own.push(`小节编号不连续:…${secOrder[i - 1]} → ${secOrder[i]}`);
}
/* ---------------- 体量 ---------------- */
const body = norm(stripTags(markup.replace(/<pre[\s\S]*?<\/pre>/g, " ")));
if (body < 2800) own.push(`正文过短(约 ${body} 字,不含代码),至少要 2800 字`);
/* ---------------- 链接与锚点 ---------------- */
for (const l of new Set([...markup.matchAll(/href="(?!https?:|mailto:|#)([^"]+)"/g)].map(m => m[1]))) {
const [file, hash] = l.split("#");
const target = path.join(root, file || f);
if (file && !fs.existsSync(target)) { hints.push(`${f}: 目标章节尚未生成 → ${l}`); continue; }
const key = path.basename(file || f);
if (hash && idIndex.has(key) && !idIndex.get(key).has(hash)) own.push(`锚点不存在:${l}`);
}
for (const l of new Set([...markup.matchAll(/href="#([^"]+)"/g)].map(m => m[1]))) {
if (idIndex.has(f) && !idIndex.get(f).has(l)) own.push(`页内锚点不存在:#${l}`);
}
if (own.length) problems.push(...own.map(x => `${f}: ${x}`));
console.log(`${f.padEnd(20)} ${String(h3.length).padStart(2)} 小节 · ${String(pres.length).padStart(2)} 段代码 · ${body} 字正文 · ${own.length ? "✗ " + own.length + " 个问题" : "✓ 通过"}`);
}
if (hints.length) {
console.log(`\n提示(并行写作期间正常,可忽略):`);
hints.slice(0, 12).forEach(x => console.log(" - " + x));
}
if (problems.length) {
console.error(`\n发现 ${problems.length} 个问题:`);
problems.forEach(x => console.error(" - " + x));
process.exit(1);
}
console.log(`\nOK ${files.length} 个章节文件全部通过单章自检。`);