Files
materials/tools/add-back-links.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

256 lines
10 KiB
JavaScript
Raw Permalink 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
/* ============================================================================
* 资料库导航 · 给每个资料子页面注入「返回资料库」入口
* ----------------------------------------------------------------------------
* 在页面 </body> 之前插入一行(样式与行为都在 assets/back.js 里):
*
* <script src="../../assets/back.js"
* data-portal-back="knowledge/docker"
* data-portal-label="知识库 › Docker 专题知识库"></script>
*
* 返回目标从 assets/portal.data.js 反查:注册过的资料 → 该资料在导航页里的详情
* (index.html#/knowledge/docker);注册表之外的目录(如 408/)→ 导航页首页
* (index.html#/)。script src 按页面的目录深度自动补 ../。
*
* node tools/add-back-links.js # 注入 / 更新(幂等,可重复运行)
* node tools/add-back-links.js --check # 只检查:有页面没挂就退出码 1
* node tools/add-back-links.js --dry # 只报告将改动的文件,不写盘
*
* 有意不动的页面(会打印在「跳过」里):
* - 仓库根 index.html 它本身就是资料库导航
* - 已有 index.html#/ 返回链接的页面 如 interview/ 占位页,避免出现两个返回入口
* - 408/ds12-tree/og.html 社交分享预览图页面,多一个按钮会污染出图
*
* 末尾是内联 <script> 的页面(各站点 index.html),新标签插在内联脚本之前,
* 这样 `</script>\s*</body>` 这类既有自检规则不受影响。
* ==========================================================================*/
'use strict';
const fs = require('fs');
const path = require('path');
const vm = require('vm');
const ROOT = path.resolve(__dirname, '..');
const CHECK = process.argv.includes('--check');
const DRY = process.argv.includes('--dry');
/* 根目录 index.html、以及预览图页面 */
const SKIP_FILES = new Set(['index.html', '408/ds12-tree/og.html']);
const BACK_JS = path.join(ROOT, 'assets', 'back.js');
const DATA_FILE = path.join(ROOT, 'assets', 'portal.data.js');
/* 匹配本工具注入的那一行(用于幂等 / 更新) */
const TAG_RE = /[ \t]*<script\b[^>]*\bsrc="[^"]*assets\/back\.js"[^>]*><\/script>/;
/* 连同行尾一起删,删完再按规则插回去,位置就唯一了 */
const STRIP_RE = /[ \t]*<script\b[^>]*\bsrc="[^"]*assets\/back\.js"[^>]*><\/script>\r?\n?/;
const SRC_RE = /\bsrc="([^"]*assets\/back\.js)"/;
const problems = [];
const fail = (m) => problems.push(m);
/* ------------------------------------------------------------ 读取注册表 */
function loadPortalData() {
if (!fs.existsSync(DATA_FILE)) {
console.error('✗ 找不到 ' + path.relative(ROOT, DATA_FILE));
process.exit(1);
}
const sandbox = { window: {} };
try {
vm.createContext(sandbox);
vm.runInContext(fs.readFileSync(DATA_FILE, 'utf8'), sandbox, { filename: 'portal.data.js' });
} catch (e) {
console.error('✗ portal.data.js 解析失败:' + e.message);
process.exit(1);
}
const d = sandbox.window.PORTAL_DATA;
if (!d || !Array.isArray(d.modules)) {
console.error('✗ portal.data.js 里没有 window.PORTAL_DATA.modules');
process.exit(1);
}
return d;
}
const DATA = loadPortalData();
/* 路由表:资料目录 → 路由 + 说明文字;目录越长越优先
* 磁盘目录用 m.dir || m.id(模块 id 是英文时,目录可以是中文),
* 路由永远用模块 id(URL hash 里保持 ASCII 可读)。 */
const routes = [];
for (const m of DATA.modules) {
const modDir = ((m.dir || m.id) || '').replace(/\/+$/, '');
if (!modDir) continue;
for (const e of m.entries || []) {
const dir = (e.dir || (e.path ? e.path.replace(/\/[^/]*$/, '') : '')).replace(/\/+$/, '');
if (!dir) continue;
routes.push({ dir, route: m.id + '/' + e.id, label: `${m.name} › ${e.name}` });
}
}
routes.sort((a, b) => b.dir.length - a.dir.length);
const modules = DATA.modules
.filter((m) => m && m.id)
.map((m) => ({ dir: (m.dir || m.id).replace(/\/+$/, ''), route: m.id.replace(/\/+$/, ''), label: m.name }));
/* 页面相对路径 → 导航页 hash 路由;未登记的目录返回首页 */
function resolveRoute(rel) {
for (const r of routes) {
if (rel.startsWith(r.dir + '/')) return r;
}
for (const r of modules) {
if (rel.startsWith(r.dir + '/')) return { route: r.route, label: r.label };
}
return { route: '', label: '' };
}
/* ------------------------------------------------------------ 扫描页面 */
const pages = [];
function walk(dir) {
for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
if (e.isDirectory()) {
if (e.name.startsWith('.')) continue; // .git / .sre-s23 / .acl-report
if (e.name === 'node_modules') continue;
walk(path.join(dir, e.name));
} else if (/\.html?$/i.test(e.name)) {
pages.push(path.join(dir, e.name));
}
}
}
walk(ROOT);
pages.sort();
/* ------------------------------------------------------------ 注入位置 */
/* 返回插入了多少个字符的偏移(在 html 里插新标签的位置) */
function insertion(html) {
const bodyIdx = html.lastIndexOf('</body>');
if (bodyIdx < 0) return null;
const before = html.slice(0, bodyIdx);
// 末尾是内联 <script>(各站点 index.html):插到它前面,让「内联脚本紧贴
// </body>」这个既有形态保持不变,各站点自检里 </script>\s*</body> 才不会失配
const close = before.lastIndexOf('</script>');
if (close >= 0 && /^\s*$/.test(before.slice(close + 9))) {
const start = before.lastIndexOf('<script>', close);
if (start >= 0) {
const indent = (before.slice(0, start).match(/[ \t]*$/) || [''])[0];
return { at: start, before: '', after: indent };
}
}
const ws = (before.match(/[ \t]*$/) || [''])[0];
return { at: bodyIdx - ws.length, before: ws, after: '' };
}
function esc(s) {
return String(s).replace(/&/g, '&amp;').replace(/</g, '&lt;')
.replace(/>/g, '&gt;').replace(/"/g, '&quot;');
}
function tagLine(rel, info) {
const depth = rel.split('/').length - 1;
const prefix = new Array(depth + 1).join('../');
const attrs = info.route
? ` data-portal-back="${esc(info.route)}" data-portal-label="${esc(info.label)}"`
: '';
return `<script src="${prefix}assets/back.js"${attrs}></script>`;
}
/* ------------------------------------------------------------ 主流程 */
const stats = new Map();
const changed = [];
const missing = [];
let ok = 0, skipped = 0;
function note(rel, status) {
const group = rel.includes('/') ? rel.split('/').slice(0, 2).join('/') : '(根目录)';
if (!stats.has(group)) stats.set(group, { total: 0, ok: 0, skip: 0, todo: 0 });
const s = stats.get(group);
s.total++;
if (status === 'ok') { s.ok++; ok++; }
else if (status === 'skip') { s.skip++; skipped++; }
else s.todo++;
}
for (const file of pages) {
const rel = path.relative(ROOT, file).split(path.sep).join('/');
if (SKIP_FILES.has(rel)) { note(rel, 'skip'); continue; }
const html = fs.readFileSync(file, 'utf8');
// 已有 index.html#/ 形式的返回链接(且不是我们注入的)→ 保持原样
if (!TAG_RE.test(html) && /index\.html#\//.test(html)) { note(rel, 'skip'); continue; }
const info = resolveRoute(rel);
const line = tagLine(rel, info);
const hadTag = TAG_RE.test(html);
// src 指向的 assets/back.js 必须真的能从这一页走到
const srcRel = path.join(path.dirname(rel), line.match(SRC_RE)[1]);
if (!fs.existsSync(path.join(ROOT, srcRel))) {
note(rel, 'todo');
fail(`${rel}: back.js 相对路径不对(${line.match(SRC_RE)[1]})`);
continue;
}
// 先删掉旧标签再按规则插回去:位置不对(例如早先插在内联脚本后面)也能自动纠正,
// 位置本来就对时删插之后字节完全一致,于是天然幂等
const stripped = html.replace(STRIP_RE, '');
const pos = insertion(stripped);
if (!pos) { note(rel, 'todo'); fail(`${rel}: 找不到 </body>,无法注入`); continue; }
const nl = stripped.includes('\r\n') ? '\r\n' : '\n';
const next = stripped.slice(0, pos.at) + pos.before + line + nl + pos.after + stripped.slice(pos.at);
if (next === html) { note(rel, 'ok'); continue; }
if (CHECK || DRY) {
note(rel, 'todo');
if (CHECK) missing.push(`${rel}(${hadTag ? '位置或属性与预期不一致' : '缺少返回入口'})`);
else changed.push(rel);
continue;
}
try {
fs.writeFileSync(file, next, 'utf8');
} catch (e) {
note(rel, 'todo');
fail(`${rel}: 写入失败(${e.code || e.message})—— 若为 EPERM/EACCES,说明该文件不在本次沙箱的写入范围内`);
continue;
}
note(rel, 'todo');
changed.push(rel);
}
/* ------------------------------------------------------------ 输出 */
const line = '─'.repeat(66);
console.log(line);
console.log(CHECK ? '资料库导航 · 返回入口检查' : DRY ? '资料库导航 · 返回入口注入(预演)' : '资料库导航 · 返回入口注入');
console.log(line);
for (const [group, s] of [...stats.entries()].sort()) {
const state = s.todo ? `待处理 ${s.todo}` : '已就绪';
console.log(` ${group.padEnd(28)} ${String(s.total).padStart(3)} 页 已挂 ${s.ok} 跳过 ${s.skip} ${state}`);
}
console.log(line);
console.log(` 页面 ${pages.length - skipped} 个(另跳过 ${skipped} 个)· 已挂 ${ok} · 本次处理 ${changed.length}`);
if (!fs.existsSync(BACK_JS)) fail('assets/back.js 不存在');
if (problems.length) {
console.log('\n✗ 问题:');
problems.forEach((p) => console.log(' - ' + p));
process.exit(1);
}
if (CHECK && missing.length) {
console.log('\n✗ 以下页面还没有返回入口(跑 node tools/add-back-links.js 注入):');
missing.slice(0, 30).forEach((p) => console.log(' - ' + p));
if (missing.length > 30) console.log(` … 另有 ${missing.length - 30} 个`);
process.exit(1);
}
if (CHECK) console.log('\n✓ 全部页面都能返回资料库导航。');
else if (DRY) {
console.log('\n(预演,未写盘)将改动:');
changed.forEach((p) => console.log(' ~ ' + p));
} else if (changed.length) {
console.log(`\n✓ 已写入 ${changed.length} 个页面。`);
} else {
console.log('\n✓ 无需改动:所有页面都已挂好返回入口。');
}