Files
materials/测试开发工程师/testdev-learning-path/tools/build-module-index.js
huanghaosheng bd678373b1 feat: 测试开发学习路径上线阶段 1 前两个模块(26 章 / 117 小节),工具链支持多阶段
- 新增 modules/s1-01-case-design/(测试理论与用例设计,13 章 / 59 小节)
- 新增 modules/s1-02-http-api/(HTTP 接口与接口测试基础,13 章 / 58 小节)
- tools/modules-plan.json 改为按阶段组织,阶段 1 的 4 个模块全部登记(未开工的两个标「筹备中」跳过)
- tools/build-module-index.js 支持多阶段,上一/下一模块按全书顺序跨阶段衔接(数据库 → 测试理论与用例设计)
- 新增 tools/check-chapter.js:单章自检(结构 / 章号 / 代码块 / 表格 / 锚点),支持 --strict 校验侧栏同步
- assets/doc.css 补 .box.pit 样式;index.html 登记 s1-0 / s1-1 路由;README 更新进度与工具说明
2026-10-16 10:39:46 +08:00

221 lines
9.2 KiB
JavaScript
Raw Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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
/* ==========================================================================
模块目录页生成器(全部阶段)
用法:node tools/build-module-index.js [站点根目录,默认本文件的上一级]
作用:读取 tools/modules-plan.json 里的模块级元数据(标题 / 副标题 / 导语 /
建议投入),再扫描 modules/<dir>/NN-*.html 解析出每章的 h2 标题与全部 h3 小节,
生成模块目录页 modules/<dir>/index.html。
为什么章节标题不写在 plan 里:目录页与正文必须永远一致。从正文解析,
就不会出现「改了正文章节标题、目录页还是旧的」这类问题。
跳过规则:plan 里列了、但目录不存在或没有 NN-*.html 的模块视为「筹备中」,
照样参与编号与前后模块关系(上一/下一模块会指向它,并标注「筹备中」)。
这样阶段与模块的编号永远和 index.html 的 STAGES 对齐,不会因为先写哪个模块而错位。
上一 / 下一模块按「全书展平顺序」计算,跨阶段也连续:
阶段 0 最后一个模块 → 阶段 1 第一个模块。
幂等:可重复运行;生成后建议再跑一次 tools/build-nav.js 同步侧栏目录树。
========================================================================== */
const fs = require("fs");
const path = require("path");
const root = process.argv[2] || path.resolve(__dirname, "..");
const MODDIR = path.join(root, "modules");
const PLAN = path.join(__dirname, "modules-plan.json");
/* ---------- 读取 JSONC(允许 /* *​/ 注释) ---------- */
function readPlan(p) {
const raw = fs.readFileSync(p, "utf8")
.replace(/\/\*[\s\S]*?\*\//g, "")
.replace(/^\s*\/\/.*$/gm, "");
return JSON.parse(raw);
}
const esc = s => String(s).replace(/&/g, "&amp;").replace(/</g, "&lt;")
.replace(/>/g, "&gt;").replace(/"/g, "&quot;");
const stripTags = s => s.replace(/<[^>]+>/g, "").replace(/\s+/g, " ").trim();
const decode = s => s.replace(/&lt;/g, "<").replace(/&gt;/g, ">")
.replace(/&quot;/g, '"').replace(/&#39;/g, "'").replace(/&nbsp;/g, " ").replace(/&amp;/g, "&");
const plain = s => decode(stripTags(s));
const stripNo = s => s.replace(/^\s*\d+(?:\.\d+)*\s*[\.、]?\s*/, "").trim();
const plan = readPlan(PLAN);
const stages = plan.stages;
const brand = plan.brand;
/* ---------- 1. 扫描:每个模块能否生成 ---------- */
const slots = []; // 全展平,顺序 = 阶段顺序 + 模块下标顺序
stages.forEach((st, si) => {
if (!st.modules) st.modules = [];
st.modules.forEach((m, mi) => {
const modPath = path.join(MODDIR, m.dir);
const files = fs.existsSync(modPath)
? fs.readdirSync(modPath).filter(f => /^\d\d-.*\.html$/.test(f)).sort()
: [];
let chapters = null;
if (files.length) {
chapters = files.map(file => {
const html = fs.readFileSync(path.join(modPath, file), "utf8");
const h2 = html.match(/<h2 id="[^"]*">([\s\S]*?)<\/h2>/);
if (!h2) throw new Error(`modules/${m.dir}/${file}: 找不到 h2 章节标题`);
const title = plain(h2[1].replace(/<span class="n">\d+<\/span>/, ""));
const sections = [...html.matchAll(/<h3 id="([^"]+)">([\s\S]*?)<\/h3>/g)]
.map(x => ({ id: x[1], label: stripNo(plain(x[2])) }));
// 字数口径:只统计中文汉字(代码与英文命令不计入「千字」,否则会被严重高估)
const chars = (stripTags(html).match(/[\u4e00-\u9fff]/g) || []).length;
return { file, title, sections, chars };
});
}
slots.push({ st, si, m, mi, modPath, chapters, files });
});
});
const built = slots.filter(s => s.chapters);
const report = [];
let written = 0;
/* ---------- 2. 逐模块生成 ---------- */
built.forEach((slot, gi) => {
const { st, m, mi, modPath, chapters } = slot;
const prevSlot = gi > 0 ? built[gi - 1] : null;
const nextSlot = gi < built.length - 1 ? built[gi + 1] : null;
// 本阶段的下一个模块(可能还没写)
const nextInStage = nextSlot && nextSlot.st === st
? nextSlot
: slots.find(s => s.st === st && s.mi === mi + 1) || null;
const chapItems = chapters.map((c, i) => {
const secs = c.sections.length
? `\n <div class="ci-secs">${c.sections.map(s => `<a href="${c.file}#${s.id}">${esc(s.label)}</a>`).join("")}</div>`
: "";
return ` <li class="chap-item">
<div class="ci-head">
<span class="ci-no">${i + 1}</span>
<a class="ci-title" href="${c.file}">${esc(c.title)}</a>
<a class="ci-go" href="${c.file}">进入 →</a>
</div>${secs}
</li>`;
}).join("\n");
const totalSecs = chapters.reduce((n, c) => n + c.sections.length, 0);
const totalK = Math.round(chapters.reduce((n, c) => n + c.chars, 0) / 1000);
const prev = prevSlot
? { href: `../${prevSlot.m.dir}/index.html`, k: "← 上一模块", v: prevSlot.m.title }
: { href: `${brand.home}#${st.id}`, k: "← 上一模块", v: `本阶段(${st.anchorText})的第一个模块` };
let next;
if (nextSlot) {
next = {
href: `../${nextSlot.m.dir}/index.html`,
k: nextSlot.st === st ? "下一模块 →" : `${nextSlot.st.anchorText} →`,
v: nextSlot.m.title
};
} else if (nextInStage) {
next = { href: `${brand.home}#${st.id}`, k: "下一模块 →", v: `筹备中:${nextInStage.m.title}` };
} else if (stages[slot.si + 1]) {
const nx = stages[slot.si + 1];
next = { href: `${brand.home}#${nx.id}`, k: `${nx.anchorText} →`, v: `回到学习路径,进入${nx.anchorText}` };
} else {
next = { href: `${brand.home}#${st.id}`, k: "学习路径 →", v: "回到学习路径" };
}
const html = `<!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(m.title)} · ${st.anchorText} 模块 ${mi + 1} · ${esc(brand.siteName)}</title>
<meta name="description" content="${esc(m.title)} 模块目录:共 ${chapters.length} 章、${totalSecs} 个小节。">
<link rel="stylesheet" href="../../assets/doc.css">
</head>
<body>
<header class="topbar">
<div class="tb-in">
<a class="brand" href="${brand.home}"><span class="logo">${esc(brand.logo)}</span><div>从零到成熟<small>测试开发 · 模块详解</small></div></a>
<div class="crumbs">
<a href="${brand.home}">学习路径</a><span class="sep">/</span>
<a href="${brand.home}#${st.id}">${esc(st.anchorText)}</a><span class="sep">/</span>
<b>${esc(m.title)}</b>
</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="${brand.home}">学习路径</a>
</div>
</aside>
<div class="mask" id="mask"></div>
<main class="main-col">
<article>
<div class="modhero">
<span class="mh-no">${esc(st.anchorText)} · 模块 ${mi + 1} / ${st.modules.length}</span>
<h1>${esc(m.title)}</h1>
<p class="mh-sub">${esc(m.sub)}</p>
<div class="mh-meta">
<span>共 <b>${chapters.length}</b> 章</span>
<span><b>${totalSecs}</b> 个小节</span>
<span>约 <b>${totalK}</b> 千字</span>
<span>${esc(m.hours)}</span>
</div>
</div>
<p class="lead">
${m.lead}
</p>
<h2 id="chapters-list">章节目录</h2>
<ol class="chaplist">
${chapItems}
</ol>
<div class="box tip">
<span class="bt">怎么用这一模块</span>
<p>左侧第一栏是<b>章节</b>,可以在整章之间跳转;第二栏是<b>本章小节</b>,进入某章后会显示该章的内容大纲并跟随滚动高亮。</p>
<p>每章结尾都可以用底部的「上一章 / 下一章」连续阅读。每章内部的代码块右上角可以直接复制,点顶栏的「深色 / 浅色」可以切换主题。</p>
</div>
</article>
<nav class="pager">
<a class="prev" href="${prev.href}"><span class="k">${prev.k}</span><span class="v">${esc(prev.v)}</span></a>
<a class="next" href="${next.href}"><span class="k">${next.k}</span><span class="v">${esc(next.v)}</span></a>
</nav>
<p class="foot">
${esc(m.title)} · 模块目录<br>
<a href="${brand.home}">返回学习路径</a>
</p>
</main>
</div>
<button id="toTop" title="回到顶部">↑</button>
<script src="../../assets/doc.js"></script>
<script src="../../../../assets/back.js"></script>
</body>
</html>
`;
fs.writeFileSync(path.join(modPath, "index.html"), html, "utf8");
written++;
report.push(`modules/${m.dir}/index.html:${chapters.length} 章 / ${totalSecs} 小节 / 约 ${totalK} 千字`);
});
const pending = slots.filter(s => !s.chapters);
pending.forEach(s => report.push(`modules/${s.m.dir}/(筹备中,跳过):${s.st.anchorText} 模块 ${s.mi + 1} ${s.m.title}`));
console.log(report.join("\n"));
console.log(`\n共生成 ${written} 个模块目录页(筹备中跳过 ${pending.length} 个)。下一步:node tools/build-nav.js`);