#!/usr/bin/env node /* ========================================================================== 阶段 2 / 3 内容生成器(临时构建工具,全部生成完成并校验通过后可删除) 用法: node .sre-s23/gen.js --all 生成 content/ 下全部模块 node .sre-s23/gen.js --only 只生成一个模块 node .sre-s23/gen.js --check 只校验不写文件 内容源:.sre-s23/content/.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//index.html SRE工程师/sre-learning-path/modules//NN-.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, "&").replace(//g, ">").replace(/"/g, """); const stripTags = s => s.replace(/<[^>]+>/g, ""); const decode = s => s.replace(/</g, "<").replace(/>/g, ">") .replace(/"/g, '"').replace(/'/g, "'").replace(/ /g, " ") .replace(/—/g, "—").replace(/&/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 应为小写连字符(用于

)`); 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 || ""); /*
 必须有 data-lang,且内部 < 必须转义 */
    const pres = (c.html || "").match(//g) || [];
    pres.forEach((blk, k) => {
      if (!/]*data-lang=/.test(blk)) fail(`${tag}: 第 ${k + 1} 个 
 未标注 data-lang`);
      const body = blk.replace(/^]*>/, "").replace(/<\/pre>$/, "");
      if (/ 内有未转义的 <`);
    });

    /* 标签配对 */
    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("", "g")) || []).length;
      if (o !== cl) fail(`${tag}: <${t}> 开合不匹配 ${o}/${cl}`);
    }

    /* h3 必须带 id */
    const h3all = ((c.html || "").match(/]/g) || []).length;
    const h3id = ((c.html || "").match(/

/g, "") .replace(/[\s\S]*?<\/code>/g, "").replace(/<[^>]+>/g, ""); if (/'/.test(prose)) fail(`${tag}: 中文正文里出现 ASCII 单引号,请改用「」`); /* 危险:正文里出现裸 < 会被浏览器吞掉 */ const bare = (c.html || "").replace(//g, "") .replace(/<[a-zA-Z\/!][^>]*>/g, ""); if (/ ${esc(title)}
`; } let mod = null; function pager(prevHref, prevK, prevV, nextHref, nextK, nextV) { const a = prevHref ? `` : ``; const b = nextHref ? `` : ``; 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(/

([\s\S]*?)<\/h3>/g)] .map(x => `${esc(stripNo(plain(x[2])))}`).join(""); return `
  • ${secs ? `\n
    ${secs}
    ` : ""}
  • `; }).join("\n"); mod.crumbTail = `${esc(m.title)}`; 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} 个小节。`) + `
    阶段 ${m.stage.num} · 模块 ${m.no} / ${m.total}

    ${esc(m.title)}

    ${esc(m.sub)}

    共 ${m.chapters.length} 章 ${secTotal} 个小节 约 ${kilo} 千字

    ${reindent(m.lead, " ")}

    章节目录

      ${chaplist}
    怎么用这一模块

    左侧是章节目录树:先看章标题快速定位,进入某一章后该章的小节会展开并跟随滚动高亮;点其它章标题可直接跳到对应页面。

    每章结尾都有「上一章 / 下一章」可以连续阅读,代码块右上角可以一键复制。

    ` + `

    ${esc(m.title)} · 模块目录
    返回学习路径

    `; 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 = `${esc(m.title)}/第 ${no} 章`; 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(/

    ${esc(m.title)} · 第 ${no} / ${m.chapters.length} 章

    ${no}${esc(c.title)}

    ${reindent(c.html, " ")} ` + `

    ${esc(m.title)} · 第 ${no} 章 ${esc(c.title)}
    模块目录 · 返回学习路径

    `; 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(", "));