Files
materials/测试开发工程师/testdev-learning-path/tools/build-module-index.js

179 lines
7.6 KiB
JavaScript
Raw Normal View History

#!/usr/bin/env node
/* ==========================================================================
模块目录页生成器(阶段 0)
用法:node tools/build-module-index.js [站点根目录,默认本文件的上一级]
作用:读取 tools/modules-plan.json 里的模块级元数据(标题 / 副标题 / 导语 /
建议投入 / 前后模块),再扫描 modules/<dir>/NN-*.html 解析出每章的 h2 标题与
全部 h3 小节,生成模块目录页 modules/<dir>/index.html。
为什么章节标题不写在 plan 里:目录页与正文必须永远一致。从正文解析,
就不会出现「改了正文章节标题、目录页还是旧的」这类问题。
幂等:可重复运行;生成后建议再跑一次 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 stage = plan.stage;
const mods = plan.modules;
/* ---------- 逐模块生成 ---------- */
let written = 0;
const report = [];
mods.forEach((m, mi) => {
const modPath = path.join(MODDIR, m.dir);
if (!fs.existsSync(modPath)) throw new Error(`模块目录不存在:modules/${m.dir}`);
const files = fs.readdirSync(modPath).filter(f => /^\d\d-.*\.html$/.test(f)).sort();
if (!files.length) throw new Error(`modules/${m.dir} 下没有 NN-*.html 章节页`);
const 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 };
});
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 = mi === 0
? { href: `${plan.brand.home}#${stage.id}`, k: "← 上一模块", v: `已经是阶段 0 的第一个模块` }
: { href: `../${mods[mi - 1].dir}/index.html`, k: "← 上一模块", v: mods[mi - 1].title };
const next = mi === mods.length - 1
? { href: `${plan.brand.home}#${stage.id}`, k: "阶段 0 完成 →", v: "回到学习路径,进入阶段 1 · 会测" }
: { href: `../${mods[mi + 1].dir}/index.html`, k: "下一模块 →", v: mods[mi + 1].title };
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)} · ${stage.anchorText} 模块 ${mi + 1} · ${esc(plan.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="${plan.brand.home}"><span class="logo">${esc(plan.brand.logo)}</span><div>从零到成熟<small>测试开发 · 模块详解</small></div></a>
<div class="crumbs">
<a href="${plan.brand.home}">学习路径</a><span class="sep">/</span>
<a href="${plan.brand.home}#${stage.id}">${esc(stage.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="${plan.brand.home}">学习路径</a>
</div>
</aside>
<div class="mask" id="mask"></div>
<main class="main-col">
<article>
<div class="modhero">
<span class="mh-no">${stage.anchorText} · 模块 ${mi + 1} / ${mods.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="${plan.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} 千字`);
});
console.log(report.join("\n"));
console.log(`\n共生成 ${written} 个模块目录页。下一步:node tools/build-nav.js`);