Files
materials/.sre-s23/gen.js
huanghaosheng 84aa0143a8 refactor: 板块 03 改为「SRE 工程师」专属板块,站点迁至 SRE工程师/sre-learning-path/
- 取消「学习路径 / learning-path」模块,新增 id=sre、目录=SRE工程师 的「SRE 工程师」板块:
  统一归档 SRE 相关资料(学习路径 + 排障速查 / SLO 模板 / 值班与复盘模板 / 面试题 / 书单等)
- 学习路线/sre-learning-path/ -> SRE工程师/sre-learning-path/(git mv,404 个文件保留改名历史),
  搬空的 学习路线/ 目录删除
- 路由改为 #/sre/sre-learning-path,返回入口标签改为「SRE 工程师 › SRE 从零到成熟学习路径」
  (399 个页面由 tools/add-back-links.js 重算)
- docker / linux / nginx 的外链、build-nav.js 生成器与自检白名单,.sre-s23 脚手架,
  以及 README / DEPLOY.md(含 nginx 中文目录的百分号编码示例)全部同步到新路径

自检:check-portal(4 个板块 / 6 份资料)、add-back-links --check(454 页)全绿;
SRE 站点 399 页与 docker、linux、nginx 的 check-pages、.sre-s23 四项体检均通过。
2026-10-15 11:55:58 +08:00

392 lines
17 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
/* ==========================================================================
阶段 2 / 3 内容生成器(临时构建工具,全部生成完成并校验通过后可删除)
用法:
node .sre-s23/gen.js --all 生成 content/ 下全部模块
node .sre-s23/gen.js --only <dir> 只生成一个模块
node .sre-s23/gen.js --check <dir> 只校验不写文件
内容源:.sre-s23/content/<dir>.js
module.exports = {
dir, title, sub, no, total,
stage: { num: 2, title: "看得见" },
lead: `...HTML...`,
chapters: [ { file:"01-why", id:"why", title:"...", html:`...` } ]
}
生成物:
SRE工程师/sre-learning-path/modules/<dir>/index.html
SRE工程师/sre-learning-path/modules/<dir>/NN-<slug>.html
侧栏目录树留空,由 tools/build-nav.js 统一填充。
========================================================================== */
const fs = require("fs");
const path = require("path");
const SITE = path.resolve(__dirname, "..", "SRE工程师", "sre-learning-path");
const CONTENT = path.join(__dirname, "content");
/* 完整模块链条:用于生成「上一模块 / 下一模块」 */
const CHAIN = [
["s0-01-linux", "Linux 系统与命令行", "s0"],
["s0-02-network", "计算机网络", "s0"],
["s0-03-programming", "编程与自动化基础", "s0"],
["s1-01-nginx", "Nginx 与流量入口", "s1"],
["s1-02-deploy", "应用部署与发布", "s1"],
["s1-03-container", "容器与镜像", "s1"],
["s1-04-cicd", "CI/CD 流水线", "s1"],
["s2-01-metrics", "指标与 Prometheus", "s2"],
["s2-02-logs", "日志采集与检索", "s2"],
["s2-03-trace", "链路追踪", "s2"],
["s2-04-dashboard", "看板与可视化", "s2"],
["s3-01-slo", "SLI / SLO / 错误预算", "s3"],
["s3-02-ha", "高可用与容灾", "s3"],
["s3-03-capacity", "容量规划与成本", "s3"],
["s3-04-chaos", "混沌工程与演练", "s3"],
["s4-01-k8s", "Kubernetes 核心", "s4"],
["s4-02-gitops", "GitOps 与声明式交付", "s4"],
["s4-03-iac", "基础设施即代码", "s4"],
["s4-04-mesh", "服务网格与网关", "s4"],
["s4-05-platform", "平台工程与自助化", "s4"],
["s5-01-oncall", "On-call 与应急响应", "s5"],
["s5-02-postmortem", "复盘与根因分析", "s5"],
["s5-03-perf", "性能分析与内核调优", "s5"],
["s5-04-security", "安全与合规运维", "s5"],
["s5-05-toil", "效率与 Toil 消除", "s5"],
["s6-01-review", "架构评审与可运维性设计", "s6"],
["s6-02-governance", "数据驱动的可靠性治理", "s6"],
["s6-03-influence", "影响力与带人", "s6"],
["s6-04-career", "职业路径与个人品牌", "s6"]
];
const STAGE_TITLE = {
s0: "打地基", s1: "服务上线", s2: "看得见",
s3: "稳得住", s4: "上规模", s5: "扛得住", s6: "成熟"
};
/* ---------------------------------------------------------------- 工具 */
const esc = s => String(s).replace(/&/g, "&amp;").replace(/</g, "&lt;")
.replace(/>/g, "&gt;").replace(/"/g, "&quot;");
const stripTags = s => s.replace(/<[^>]+>/g, "");
const decode = s => s.replace(/&lt;/g, "<").replace(/&gt;/g, ">")
.replace(/&quot;/g, '"').replace(/&#39;/g, "'").replace(/&nbsp;/g, " ")
.replace(/&mdash;/g, "—").replace(/&amp;/g, "&");
const plain = s => decode(stripTags(s)).replace(/\s+/g, " ").trim();
const stripNo = s => s.replace(/^\s*\d+(?:\.\d+)*\s*[\.、]?\s*/, "").trim();
const textLen = s => stripTags(s).replace(/\s+/g, "").length;
/* 统一缩进:去掉公共前导空白,再按 pad 重排 */
function reindent(html, pad) {
const lines = String(html).replace(/\r\n/g, "\n").replace(/^\n+|\n+$/g, "").split("\n");
const indents = lines.filter(l => l.trim()).map(l => (l.match(/^[ \t]*/) || [""])[0].length);
const min = indents.length ? Math.min(...indents) : 0;
return lines.map(l => (l.trim() ? pad + l.slice(min) : "")).join("\n");
}
/* ---------------------------------------------------------------- 校验 */
const LENIENT = process.argv.includes("--lenient"); // 冒烟测试用:跳过字数下限
const problems = [];
const fail = m => problems.push(m);
function validate(mod, srcName) {
const need = ["dir", "title", "sub", "no", "total", "stage", "lead", "chapters"];
for (const k of need) if (!mod[k]) fail(`${srcName}: 缺少字段 ${k}`);
if (!mod.stage || !mod.stage.num || !mod.stage.title) fail(`${srcName}: stage 需要 {num,title}`);
if (!/^s\d-\d\d-[a-z0-9-]+$/.test(mod.dir || "")) fail(`${srcName}: dir 命名应为 sN-NN-slug`);
if (!Array.isArray(mod.chapters) || !mod.chapters.length) { fail(`${srcName}: chapters 为空`); return; }
const files = new Set();
const ids = new Set();
let total = 0;
(mod.chapters || []).forEach((c, i) => {
const tag = `${srcName} 第 ${i + 1} 章`;
if (!/^\d\d-[a-z0-9-]+$/.test(c.file || "")) fail(`${tag}: file 应为 NN-slug(小写连字符)`);
if (c.file && parseInt(c.file.slice(0, 2), 10) !== i + 1) fail(`${tag}: file 序号应为 ${String(i + 1).padStart(2, "0")}`);
if (files.has(c.file)) fail(`${tag}: file 重复 ${c.file}`);
files.add(c.file);
if (!c.title || !c.title.trim()) fail(`${tag}: 缺少 title`);
if (!/^[a-z][a-z0-9-]*$/.test(c.id || "")) fail(`${tag}: id 应为小写连字符(用于 <h2 id>)`);
if (ids.has(c.id)) fail(`${tag}: id 重复 ${c.id}`);
ids.add(c.id);
if (!c.html || (!LENIENT && textLen(c.html) < 600)) fail(`${tag}: 正文过短(${textLen(c.html || "")} 字,至少 600)`);
total += textLen(c.html || "");
/* <pre> 必须有 data-lang,且内部 < 必须转义 */
const pres = (c.html || "").match(/<pre[\s\S]*?<\/pre>/g) || [];
pres.forEach((blk, k) => {
if (!/<pre[^>]*data-lang=/.test(blk)) fail(`${tag}: 第 ${k + 1} 个 <pre> 未标注 data-lang`);
const body = blk.replace(/^<pre[^>]*>/, "").replace(/<\/pre>$/, "");
if (/</.test(body)) fail(`${tag}: 第 ${k + 1} 个 <pre> 内有未转义的 <`);
});
/* 标签配对 */
for (const t of ["div", "section", "details", "table", "ul", "ol", "li", "p", "span"]) {
const o = ((c.html || "").match(new RegExp("<" + t + "(?=[\\s>])", "g")) || []).length;
const cl = ((c.html || "").match(new RegExp("</" + t + ">", "g")) || []).length;
if (o !== cl) fail(`${tag}: <${t}> 开合不匹配 ${o}/${cl}`);
}
/* h3 必须带 id */
const h3all = ((c.html || "").match(/<h3[ >]/g) || []).length;
const h3id = ((c.html || "").match(/<h3 id="/g) || []).length;
if (h3all !== h3id) fail(`${tag}: 有 h3 未补 id(${h3id}/${h3all})`);
/* 中文正文里不出现 ASCII 单引号 */
const prose = (c.html || "").replace(/<pre[\s\S]*?<\/pre>/g, "")
.replace(/<code>[\s\S]*?<\/code>/g, "").replace(/<[^>]+>/g, "");
if (/'/.test(prose)) fail(`${tag}: 中文正文里出现 ASCII 单引号,请改用「」`);
/* 危险:正文里出现裸 < 会被浏览器吞掉 */
const bare = (c.html || "").replace(/<pre[\s\S]*?<\/pre>/g, "")
.replace(/<[a-zA-Z\/!][^>]*>/g, "");
if (/</.test(bare)) fail(`${tag}: 正文里有未转义的 <`);
});
if (!LENIENT && total < 11000) fail(`${srcName}: 全模块正文合计 ${total} 字,偏少(建议 ≥ 14000)`);
mod._total = total;
/* 必须有收尾的自测章 */
const last = (mod.chapters || [])[mod.chapters.length - 1];
if (last && !/自测|checklist/.test(last.file + last.title)) {
fail(`${srcName}: 最后一章应是「完成标准与自测」(当前 ${last.file})`);
}
return problems.length === 0;
}
/* ---------------------------------------------------------------- 模板 */
function head(title, desc) {
return `<!DOCTYPE html>
<html lang="zh-CN" data-theme="light">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>${esc(title)}</title>
<meta name="description" content="${esc(desc)}">
<link rel="stylesheet" href="../../assets/doc.css">
</head>
<body>
<header class="topbar">
<div class="tb-in">
<a class="brand" href="../../index.html"><span class="logo">SRE</span><div>从零到成熟<small>模块详解</small></div></a>
<div class="crumbs">
<a href="../../index.html">学习路径</a><span class="sep">/</span>
<a href="../../index.html#${mod.stageAnchor}">阶段 ${mod.stage.num} · ${esc(mod.stage.title)}</a><span class="sep">/</span>
${mod.crumbTail}
</div>
<div class="spacer"></div>
<button class="btn" id="tocToggle">☰ 导航</button>
<button class="btn" id="themeBtn" title="切换到深色主题">深色</button>
</div>
</header>
<div class="layout" id="layout">
<aside class="sidebar">
<h2>章节目录</h2>
<nav id="chapters"></nav>
<div class="side-foot">
<a class="btn" href="index.html">← 模块目录</a>
<a class="btn" href="../../index.html">学习路径</a>
</div>
</aside>
<div class="mask" id="mask"></div>
<main class="main-col">
<article>
`;
}
let mod = null;
function pager(prevHref, prevK, prevV, nextHref, nextK, nextV) {
const a = prevHref
? `<a class="prev" href="${prevHref}"><span class="k">${prevK}</span><span class="v">${esc(prevV)}</span></a>`
: `<a class="prev disabled"><span class="k">${prevK}</span><span class="v">${esc(prevV)}</span></a>`;
const b = nextHref
? `<a class="next" href="${nextHref}"><span class="k">${nextK}</span><span class="v">${esc(nextV)}</span></a>`
: `<a class="next disabled"><span class="k">${nextK}</span><span class="v">${esc(nextV)}</span></a>`;
return a + "\n " + b;
}
/* ---------------------------------------------------------------- 生成 */
function generate(m) {
mod = m;
mod.stageAnchor = m.stage.anchor || ("s" + m.stage.num);
const outDir = path.join(SITE, "modules", m.dir);
fs.mkdirSync(outDir, { recursive: true });
const idx = CHAIN.findIndex(x => x[0] === m.dir);
const prevMod = idx > 0 ? CHAIN[idx - 1] : null;
const nextMod = idx >= 0 && idx < CHAIN.length - 1 ? CHAIN[idx + 1] : null;
const nextStage = "s" + (Number(m.stage.num) + 1);
const hasNextStage = Object.prototype.hasOwnProperty.call(STAGE_TITLE, nextStage);
/* ---- 模块目录页 ---- */
const secTotal = m.chapters.reduce((n, c) =>
n + ((c.html.match(/<h3 id="/g) || []).length), 0);
const kilo = Math.round(m._total / 1000);
const chaplist = m.chapters.map((c, i) => {
const no = i + 1;
const secs = [...c.html.matchAll(/<h3 id="([^"]+)">([\s\S]*?)<\/h3>/g)]
.map(x => `<a href="${c.file}.html#${x[1]}">${esc(stripNo(plain(x[2])))}</a>`).join("");
return ` <li class="chap-item">
<div class="ci-head">
<span class="ci-no">${no}</span>
<a class="ci-title" href="${c.file}.html">${esc(c.title)}</a>
<a class="ci-go" href="${c.file}.html">进入 →</a>
</div>${secs ? `\n <div class="ci-secs">${secs}</div>` : ""}
</li>`;
}).join("\n");
mod.crumbTail = `<b>${esc(m.title)}</b>`;
mod.footTail = "模块目录";
const idxPrev = prevMod
? [`../${prevMod[0]}/index.html`, "← 上一模块", prevMod[1]]
: [null, "← 上一模块", "已经是第一个模块"];
const idxNext = nextMod
? [`../${nextMod[0]}/index.html`, "下一模块 →", nextMod[1]]
: hasNextStage
? [`../../index.html#${nextStage}`, "下一模块 →", `阶段 ${nextStage.slice(1)} · ${STAGE_TITLE[nextStage]}`]
: [`../../index.html`, "全部读完 →", "返回学习路径目录"];
const idxBody = head(`${m.title} · 阶段 ${m.stage.num} 模块 ${m.no} · SRE 从零到成熟`,
`${m.title} 模块目录:共 ${m.chapters.length} 章、${secTotal} 个小节。`) +
` <div class="modhero">
<span class="mh-no">阶段 ${m.stage.num} · 模块 ${m.no} / ${m.total}</span>
<h1>${esc(m.title)}</h1>
<p class="mh-sub">${esc(m.sub)}</p>
<div class="mh-meta">
<span>共 <b>${m.chapters.length}</b> 章</span>
<span><b>${secTotal}</b> 个小节</span>
<span>约 <b>${kilo}</b> 千字</span>
</div>
</div>
<p class="lead">
${reindent(m.lead, " ")}
</p>
<h2 id="chapters-list">章节目录</h2>
<ol class="chaplist">
${chaplist}
</ol>
<div class="box tip">
<span class="bt">怎么用这一模块</span>
<p>左侧是<b>章节目录树</b>:先看章标题快速定位,进入某一章后该章的小节会展开并跟随滚动高亮;点其它章标题可直接跳到对应页面。</p>
<p>每章结尾都有「上一章 / 下一章」可以连续阅读,代码块右上角可以一键复制。</p>
</div>
` +
`
</article>
<nav class="pager">
${pager(...idxPrev, ...idxNext)}
</nav>
<p class="foot">
${esc(m.title)} · 模块目录<br>
<a href="../../index.html">返回学习路径</a>
</p>
</main>
</div>
<button id="toTop" title="回到顶部">↑</button>
<script src="../../assets/doc.js"></script>
<script src="../../../../assets/back.js" data-portal-back="sre/sre-learning-path" data-portal-label="SRE 工程师 › SRE 从零到成熟学习路径"></script>
</body>
</html>
`;
fs.writeFileSync(path.join(outDir, "index.html"), idxBody, "utf8");
/* ---- 章节页 ---- */
m.chapters.forEach((c, i) => {
const no = i + 1;
const nc = m.chapters[i + 1];
const pc = m.chapters[i - 1];
mod.crumbTail = `<a href="index.html">${esc(m.title)}</a><span class="sep">/</span><b>第 ${no} 章</b>`;
mod.footTail = `第 ${no} 章 ${c.title}`;
const pv = pc
? [`${pc.file}.html`, "← 上一章", `第 ${no - 1} 章 · ${pc.title}`]
: ["index.html", "← 模块目录", m.title];
const nx = nc
? [`${nc.file}.html`, "下一章 →", `第 ${no + 1} 章 · ${nc.title}`]
: ["index.html", "回到 →", `${m.title} 章节目录`];
const html = head(`${c.title} · ${m.title} · SRE 从零到成熟`,
`${m.title} 第 ${no} 章:${c.title}。本章 ${(c.html.match(/<h3 id="/g) || []).length} 个小节。`) +
` <p class="chapnav">
<a href="index.html">${esc(m.title)}</a>
<span>·</span>
<span>第 <b class="pos">${no}</b> / ${m.chapters.length} 章</span>
</p>
<h2 id="${c.id}"><span class="n">${no}</span>${esc(c.title)}</h2>
${reindent(c.html, " ")}
` +
`
</article>
<nav class="pager">
${pager(...pv, ...nx)}
</nav>
<p class="foot">
${esc(m.title)} · 第 ${no} 章 ${esc(c.title)}<br>
<a href="index.html">模块目录</a> · <a href="../../index.html">返回学习路径</a>
</p>
</main>
</div>
<button id="toTop" title="回到顶部">↑</button>
<script src="../../assets/doc.js"></script>
<script src="../../../../assets/back.js" data-portal-back="sre/sre-learning-path" data-portal-label="SRE 工程师 › SRE 从零到成熟学习路径"></script>
</body>
</html>
`;
fs.writeFileSync(path.join(outDir, c.file + ".html"), html, "utf8");
});
return { dir: m.dir, chapters: m.chapters.length, secs: secTotal, chars: m._total };
}
/* ---------------------------------------------------------------- 入口 */
const argv = process.argv.slice(2);
const only = argv.includes("--only") ? argv[argv.indexOf("--only") + 1] : null;
const checkOnly = argv.includes("--check") ? argv[argv.indexOf("--check") + 1] : null;
const targets = fs.existsSync(CONTENT)
? fs.readdirSync(CONTENT).filter(f => f.endsWith(".js")).map(f => f.replace(/\.js$/, "")).sort()
: [];
if (!targets.length) { console.error("content/ 下没有内容文件"); process.exit(1); }
const results = [];
for (const name of targets) {
if (only && name !== only) continue;
if (checkOnly && name !== checkOnly) continue;
let m;
try { m = require(path.join(CONTENT, name + ".js")); }
catch (e) { console.error(`✗ ${name}.js 加载失败:${e.message}`); process.exitCode = 1; continue; }
const before = problems.length;
const ok = validate(m, name);
if (!ok) {
console.error(`✗ ${name}(${problems.length - before} 个问题)`);
problems.slice(before).forEach(x => console.error(" - " + x));
process.exitCode = 1;
continue;
}
if (checkOnly) { results.push({ dir: m.dir, chapters: m.chapters.length, chars: m._total, dry: true }); continue; }
results.push(generate(m));
console.log(`✓ modules/${m.dir}:${m.chapters.length} 章 / ${m._total} 字`);
}
if (results.length && !checkOnly) {
console.log("\n小计:" + results.map(r => `${r.dir}=${r.chars}`).join(" "));
console.log("合计 " + results.reduce((n, r) => n + r.chars, 0) + " 字");
}
if (problems.length) { console.error(`\n共 ${problems.length} 个问题`); process.exit(1); }
if (checkOnly && results.length) console.log("OK 校验通过:" + results.map(r => r.dir).join(", "));