feat: 每个资料子页面加回导航页的返回入口;导航页与 Docker/Linux/Nginx/408 站点入库
一、子页面返回入口(本次改动)
- 新增 assets/back.js:在页面顶栏的站点标题之后挂「← 资料库」,点一下回根目录
index.html 并直接落在本资料的详情路由(如 #/knowledge/docker);注册表之外的目录
(408/)回首页;没有顶栏的页面(408 的 404)退化为左下角浮动按钮
- 层级由脚本自己的 src 反推(new URL('../', src)),任何目录深度都不必改 back.js;
样式跟随各站点:描边 / 文字用 currentColor、主色用 var(--brand) / var(--accent)、
圆角跟随 var(--btn-radius),深浅色主题都自适应,打印时自动隐藏;页面里已有
index.html#/ 形式的返回链接时(interview/ 占位页)不再重复挂
- 新增 tools/add-back-links.js:按 assets/portal.data.js 反查路由与名称,给每个子页面
注入 <script src="…assets/back.js" data-portal-back=… data-portal-label=…>。
先删旧标签再按规则插回,位置写错也能自动纠正;--check 只检查(缺一个即退出码 1)、
--dry 只预演、写入失败不会中断整轮
- 共注入 454 个页面,3 个有意跳过:根 index.html(它本身就是导航页)、
interview/index.html(已有「← 返回导航」)、408/ds12-tree/og.html(分享预览图页面)
- 末尾是内联 <script> 的 7 个 index.html:标签插在内联脚本之前,保持
</script>\s*</body> 的既有形态,各站点自检规则不受影响
- .sre-s23/gen.js 的两处模板同步带上该行,重新生成 SRE 模块页不会丢入口
- README 补「子页面怎么回到导航页」一节,并在新增资料流程里加上这一步
二、此前未入库的内容(一并提交)
- 导航页:index.html + assets/portal.css|portal.data.js|portal.js + tools/check-portal.js
- knowledge/docker(14 章)、knowledge/linux(17 章)、knowledge/nginx(17 章)
- 408/ds12-tree 知识卡片(app.js / styles.css / verify.mjs / favicon / og)
- interview 占位页、README.md
校验
- add-back-links --check:454 / 454 已就绪
- check-portal:3 个模块 / 6 份资料全部命中(无死链)
- check-pages:docker 15 页、linux 18 页、nginx 18 页、sre-learning-path 399 页 全部 OK
- 无头 Chrome 实测点击:docker 章节页 / SRE 模块页 / 场景题库 / 项目题库 / 408 卡片页
都落到对应资料详情,404 的浮动按钮回导航首页;按钮颜色浅色 rgb(23,33,46) 深色
rgb(231,237,246) 自适应,408 站点圆角保持 0px
- 受版本管理的 402 个页面每个只 +1 行(gen.js +2 行),没有整文件改写
说明:本机沙箱下 knowledge/sre-learning-path/**、408/、knowledge/scenario、project/、
interview/ 这些文件当时不可写(缺低完整性标记),注入是在一次完全权限授权下完成的。
This commit is contained in:
261
knowledge/linux/tools/SPEC.md
Normal file
261
knowledge/linux/tools/SPEC.md
Normal file
@@ -0,0 +1,261 @@
|
||||
# Linux 专题知识库 · 章节写作规范(SPEC)
|
||||
|
||||
> 本文件是给「写章节正文」用的**唯一契约**。骨架(侧栏目录树、章节定位条、上下章导航、页脚)
|
||||
> 由 `tools/build-nav.js` 统一生成,你只需要写正文,**不要自己写目录树**。
|
||||
> 写完必须能通过 `node tools/check-pages.js`。站点根目录:`knowledge/linux/`。
|
||||
|
||||
## 0. 定位
|
||||
|
||||
- 读者:有 1–3 年经验的开发者 / 运维,每天在 Linux 上写代码、部署服务、排故障。
|
||||
- 立场:**面向实际开发与生产运维**——每个知识点都要回答「我在什么时候会用到它、错了会怎样、怎么验证」。
|
||||
- 语气:直接、具体、讲代价。不写「Linux 很强大」这类空话;给命令、给真实输出、给判断依据。
|
||||
- 篇幅:每章正文 2800–5000 字(不含代码),小节 3–10 个,每个小节 2–6 段或「段落 + 代码 + 提示框」。
|
||||
- 平台基线:默认 **Ubuntu 22.04 / 24.04 LTS(systemd、glibc、apt)**,涉及 RHEL 系时显式说明
|
||||
(RHEL 9 / Rocky 9,`dnf`,`/etc/sysconfig`)。命令的输出示例要写成这份发行版上真实会看到的形状。
|
||||
|
||||
## 1. 文件模板(严格照抄结构,只替换标题与正文)
|
||||
|
||||
```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>第 4 章 用户、权限与提权 · Linux 专题知识库</title>
|
||||
<meta name="description" content="本章 40–90 字的摘要,写清覆盖范围与产出,会显示在目录页卡片上。">
|
||||
<meta name="keywords" content="Linux,权限,chmod,chown,sudo,umask,suid,ACL,关键词4~8个">
|
||||
<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">LNX</span><div>Linux 专题<small>从命令行到生产运维的系统知识库</small></div></a>
|
||||
<div class="crumbs">
|
||||
<a href="index.html">总目录</a><span class="sep">/</span><b>第 4 章</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>
|
||||
</div>
|
||||
</aside>
|
||||
<div class="mask" id="mask"></div>
|
||||
|
||||
<main class="main-col">
|
||||
<article>
|
||||
<p class="chapnav"></p>
|
||||
|
||||
<h2 id="ch4"><span class="n">4</span>用户、权限与提权</h2>
|
||||
|
||||
<div class="lead">
|
||||
<b>这一章解决什么:</b>……(2–4 行,说明学完能做什么、为什么重要)
|
||||
</div>
|
||||
|
||||
<h3 id="sec-4-1">4.1 uid / gid 与三个身份文件</h3>
|
||||
<p>……</p>
|
||||
|
||||
<!-- 更多小节 -->
|
||||
</article>
|
||||
|
||||
<nav class="pager"></nav>
|
||||
|
||||
<p class="foot"></p>
|
||||
</main>
|
||||
</div>
|
||||
|
||||
<button id="toTop" title="回到顶部">↑</button>
|
||||
<script src="assets/doc.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
|
||||
四个空占位块**必须**原样保留(`<nav id="chapters"></nav>`、`<p class="chapnav"></p>`、
|
||||
`<nav class="pager"></nav>`、`<p class="foot"></p>`),内容由生成器填。
|
||||
|
||||
## 2. 可用的排版组件(只能用这些类,不要引入新 CSS)
|
||||
|
||||
| 组件 | 写法 | 用途 |
|
||||
|---|---|---|
|
||||
| 导语 | `<div class="lead">…</div>` | 每章开头一个,说明本章解决什么 |
|
||||
| 提示框 | `<div class="box note\|tip\|warn\|danger\|ok\|case">` + `<span class="bt">标题</span>` | note=补充说明,tip=技巧,warn=注意,danger=踩坑/事故,ok=推荐做法,case=真实案例,lab=动手实验 |
|
||||
| 代码块 | `<pre data-lang="bash" data-name="可选说明">…</pre>` | 语言标签自动显示并可一键复制;**每个 pre 必须带 data-lang** |
|
||||
| 表格 | `<div class="tablewrap"><table><thead>…</thead><tbody>…</tbody></table></div>` | 对比、速查、参数表 |
|
||||
| 步骤 | `<ol class="steps"><li>…</li></ol>` | 操作流程 |
|
||||
| 卡片 | `<div class="cards"><div class="card"><h4>…</h4><ul>…</ul></div></div>` | 并列要点 |
|
||||
| 行内 | `<code>` `<kbd>` `<mark>` `<strong>` | 命令、按键、重点 |
|
||||
| 小节标题 | `<h3 id="sec-4-1">4.1 标题</h3>` | **每个 h3 都必须有 id,格式 sec-章号-序号** |
|
||||
| 章标题 | `<h2 id="ch4"><span class="n">4</span>标题</h2>` | 每章一个,放正文最前面 |
|
||||
|
||||
`data-lang` 允许值:`bash` `shell` `sh` `console` `text` `plain` `yaml` `yml` `json` `toml`
|
||||
`conf` `config` `ini` `systemd` `unit` `fstab` `crontab` `ssh` `sshconfig` `log` `diff` `csv` `xml`
|
||||
`http` `nginx` `makefile` `dockerfile` `properties` `go` `javascript` `js` `typescript` `ts`
|
||||
`python` `java` `c` `cpp` `sql` `powershell` `promql` `regex` `awk` `sed` `lua`。
|
||||
|
||||
## 3. 硬性规则(校验器会逐条检查,违反即失败)
|
||||
|
||||
1. 只创建分配给你的 `NN-*.html` 文件,**不要动** `index.html`、`assets/`、`tools/`、别人的章节。
|
||||
2. `<pre>` 内的 `<` 必须写成 `<`,`&` 写成 `&`;不要放未转义的尖括号。
|
||||
(典型场景:`awk 'NR<10'`、`grep -E '<img'`、`>` 重定向、`2>&1`。)
|
||||
3. 标签必须闭合,`div/section/article/aside/nav/main/table/ul/ol/li/details` 开合数量一致。
|
||||
4. 站内链接只能指向本目录的文件或页内锚点;**不要写跨资料目录的相对路径**(不要 `../`)。
|
||||
指向别的章节的写法固定为 `04-perm.html`、`04-perm.html#sec-4-2`。
|
||||
5. 每个 `<h3>` 都要有 `id`,且以 `sec-<章号>-` 开头;小节编号写进标题文本(如 `4.1`)。
|
||||
6. 小节数量 3–10 个;正文不少于 2800 字;至少 3 个代码块;至少 1 个表格或卡片组。
|
||||
7. 每章至少一处 `.box case`(真实案例)或 `.box lab`(动手实验)或标题含「实战」的小节,
|
||||
用来交代**这在开发和运维里怎么用**。
|
||||
8. 代码必须真实可运行:命令、参数、路径、发行版、内核版本都要真实存在,
|
||||
不要编造命令或参数;不确定的写法宁可不写。
|
||||
9. 术语:第一次出现的英文术语用「中文(English)」;命令、文件名、路径一律 `<code>`。
|
||||
10. 不要写「如下图所示」——本站不放图片;用表格/列表替代。
|
||||
11. `<meta name="keywords">` 必填(逗号分隔 4–8 个关键词,含英文术语,供目录页搜索)。
|
||||
|
||||
## 4. 内容质量要求
|
||||
|
||||
- **先讲为什么**:任何参数/机制先给场景(比如「为什么 `kill -9` 杀不掉 D 状态进程」),再给结论和命令。
|
||||
- **给判断依据**:不要只说「建议用 ext4」,要说清各文件系统的取舍、什么时候不该用。
|
||||
- **给排错路径**:每个易错点写清「现象 → 原因 → 验证命令 → 解决」,优先用表格承载。
|
||||
- **给真实输出**:代码块的输出要写成真实形状(例如 `top` 的 load average 行、`ss -lntp` 的列),
|
||||
让读者能对照自己的终端。可以适当截断并标注 `…`。
|
||||
- **关联开发流程**:能联系到写代码、本地联调、脚本、CI、部署、上线排障的地方就明确写出来。
|
||||
- **交叉引用**:涉及别章内容时用链接,例如「权限模型见 <a href="04-perm.html#sec-4-2">4.2</a>」。
|
||||
第 5 节列出了全部合法小节 id,链接必须指向其中真实存在的一个。
|
||||
|
||||
## 5. 全部 17 章大纲(只写分配给你的章;小节标题可微调,但 id 与编号必须与下表一致)
|
||||
|
||||
### 01-what.html · 第 1 章 Linux 全景:内核、用户态与发行版
|
||||
1.1 一个真实痛点:同一份脚本,三台机器三种行为 · 1.2 内核与用户态:系统调用是唯一的门 ·
|
||||
1.3 从加电到登录:启动链上的每一环 · 1.4 发行版家族与选型依据 ·
|
||||
1.5 FHS 目录层级:每个目录为什么存在 · 1.6 内核版本号、LTS 与发行版内核的关系 ·
|
||||
1.7 什么时候该关心内核,什么时候只关心发行版
|
||||
|
||||
### 02-shell.html · 第 2 章 Shell 与命令行心智模型
|
||||
2.1 一条命令背后的 fork / exec / wait 与退出码 · 2.2 管道、重定向与文件描述符 ·
|
||||
2.3 变量、引号与分词(word splitting) · 2.4 通配符与各类扩展的求值顺序 ·
|
||||
2.5 作业控制:前台、后台与信号 · 2.6 交互效率:history、alias 与快捷键 ·
|
||||
2.7 脚本基本功:set -euo pipefail 与 shellcheck · 2.8 bash / dash / zsh 与 POSIX 可移植性
|
||||
|
||||
### 03-fs.html · 第 3 章 文件系统与路径
|
||||
3.1 「一切皆文件」到底意味着什么 · 3.2 七种文件类型与它们的用途 · 3.3 硬链接与符号链接 ·
|
||||
3.4 挂载、/proc、/sys 与 /dev · 3.5 inode、目录项与「磁盘满却找不到大文件」 ·
|
||||
3.6 定位文件:find / locate 与 glob 的取舍 · 3.7 空间治理实战:du / df / lsof +L1
|
||||
|
||||
### 04-perm.html · 第 4 章 用户、权限与提权
|
||||
4.1 uid / gid 与三个身份文件 · 4.2 rwx 与目录权限的真实语义 ·
|
||||
4.3 umask、默认权限与 setgid 目录 · 4.4 特殊权限位:suid / sgid / sticky ·
|
||||
4.5 sudo 与最小权限设计 · 4.6 ACL、chattr 与不可变文件 ·
|
||||
4.7 Permission denied 的七种原因与排查顺序
|
||||
|
||||
### 05-text.html · 第 5 章 文本处理与日志分析
|
||||
5.1 grep:从日常筛选到排障 · 5.2 sed:流编辑与就地修改 · 5.3 awk:按列处理与统计 ·
|
||||
5.4 组合拳:cut / sort / uniq / tr / wc / xargs · 5.5 jq 与结构化日志 ·
|
||||
5.6 日志分析实战:从 access.log 到 Top N · 5.7 大文件处理:less / split / 并行
|
||||
|
||||
### 06-proc.html · 第 6 章 进程、信号与作业管理
|
||||
6.1 进程模型:pid / ppid / 进程组 / 会话 · 6.2 进程状态与不可杀的 D 状态 ·
|
||||
6.3 信号全表与常用信号 · 6.4 观察进程:ps / top / htop / pgrep / pstree ·
|
||||
6.5 长任务托管:nohup / setsid / disown / tmux · 6.6 僵尸进程与孤儿进程 ·
|
||||
6.7 /proc 里的进程真相 · 6.8 进程杀不掉时的排查顺序
|
||||
|
||||
### 07-systemd.html · 第 7 章 systemd 与服务管理
|
||||
7.1 为什么现代发行版都用 systemd · 7.2 unit 类型与依赖关系 · 7.3 service unit 文件全解 ·
|
||||
7.4 systemctl 日常命令 · 7.5 journalctl 日志查询 · 7.6 timer 替代 cron ·
|
||||
7.7 服务起不来的排障剧本 · 7.8 容器里该不该跑 systemd
|
||||
|
||||
### 08-disk.html · 第 8 章 存储、分区与文件系统管理
|
||||
8.1 块设备与 /dev 命名规则 · 8.2 分区表 MBR / GPT 与 parted · 8.3 LVM:在线扩容为什么是运维刚需 ·
|
||||
8.4 文件系统选型:ext4 / xfs / btrfs · 8.5 挂载与 /etc/fstab 的坑 ·
|
||||
8.6 swap 的取舍与 swappiness · 8.7 磁盘扩容全流程实战 · 8.8 SMART 与磁盘故障预警
|
||||
|
||||
### 09-net.html · 第 9 章 网络配置与排障
|
||||
9.1 协议分层与 Linux 里的对应物 · 9.2 网卡、IP 与路由:ip 取代 ifconfig ·
|
||||
9.3 DNS 解析链路与 resolv.conf · 9.4 端口、socket 与 ss ·
|
||||
9.5 防火墙四件套:iptables / nftables / firewalld / ufw · 9.6 抓包:tcpdump 实战 ·
|
||||
9.7 网络排障剧本 · 9.8 内核网络参数调优
|
||||
|
||||
### 10-ssh.html · 第 10 章 SSH 与远程运维
|
||||
10.1 SSH 原理与首次连接的信任问题 · 10.2 密钥认证与 ssh-agent · 10.3 ssh_config 与跳板机 ·
|
||||
10.4 端口转发三种模式 · 10.5 文件传输:scp / sftp / rsync ·
|
||||
10.6 加固:禁密码、限用户与 fail2ban · 10.7 会话保持:tmux 与断线重连 ·
|
||||
10.8 SSH 连不上的排障顺序
|
||||
|
||||
### 11-pkg.html · 第 11 章 软件包管理与运行环境
|
||||
11.1 包管理器心智模型:仓库、依赖与版本 · 11.2 Debian 系:apt 与 dpkg ·
|
||||
11.3 RHEL 系:dnf 与 rpm · 11.4 仓库配置与内网镜像 ·
|
||||
11.5 源码编译:configure / make 与动态库查找 · 11.6 多语言运行时共存 ·
|
||||
11.7 锁定版本与可复现环境
|
||||
|
||||
### 12-boot.html · 第 12 章 启动流程、内核与内核参数
|
||||
12.1 启动链:固件 → bootloader → kernel → initramfs → systemd · 12.2 GRUB 配置与多内核管理 ·
|
||||
12.3 initramfs 的作用与重建 · 12.4 内核命令行参数与 sysctl 的区别 ·
|
||||
12.5 sysctl 持久化与常见调参 · 12.6 内核模块管理 ·
|
||||
12.7 起不来的救援:单用户模式与救援盘
|
||||
|
||||
### 13-perf.html · 第 13 章 性能分析与可观测性
|
||||
13.1 分析方法论:先定位再优化 · 13.2 CPU 与负载:load / vmstat / mpstat ·
|
||||
13.3 内存:free、page cache 与 PSI · 13.4 磁盘 IO:iostat / iotop / 调度器 ·
|
||||
13.5 网络指标与 sar 历史数据 · 13.6 perf、火焰图与 eBPF 工具链 ·
|
||||
13.7 日志与审计:dmesg / journalctl / auditd · 13.8 「这台机器为什么慢」完整剧本
|
||||
|
||||
### 14-sec.html · 第 14 章 安全加固与应急响应
|
||||
14.1 威胁模型与攻击面 · 14.2 账号与认证加固 · 14.3 最小权限与服务隔离 ·
|
||||
14.4 SELinux 与 AppArmor · 14.5 审计与入侵检测 · 14.6 补丁与漏洞管理 ·
|
||||
14.7 被入侵后的应急响应顺序 · 14.8 上线前 Linux 加固清单
|
||||
|
||||
### 15-dev.html · 第 15 章 开发环境实战:把 Linux 用进日常
|
||||
15.1 开发机上必须会的事 · 15.2 环境变量与 PATH 的正确管理 · 15.3 Makefile 与构建脚本 ·
|
||||
15.4 本地服务与端口管理 · 15.5 容器背后的 Linux:namespace 与 cgroup ·
|
||||
15.6 CI 里的 Linux 脚本 · 15.7 脚本工程化:日志、幂等与错误处理 ·
|
||||
15.8 「本地能跑线上不能跑」的 Linux 原因
|
||||
|
||||
### 16-cheat.html · 第 16 章 速查表与 30 个高频坑
|
||||
16.1 文件、目录与查找速查 · 16.2 文本处理速查 · 16.3 进程与服务速查 · 16.4 网络速查 ·
|
||||
16.5 磁盘与容量速查 · 16.6 权限、用户与 SSH 速查 ·
|
||||
16.7 30 个高频坑(现象 → 原因 → 解决,用一张大表格)
|
||||
|
||||
### 17-checklist.html · 第 17 章 能力自测与面试
|
||||
17.1 能力自测清单(三档) · 17.2 60 道自测题(附答案) · 17.3 面试高频问答与追问 ·
|
||||
17.4 学习路径(1 周 / 1 月 / 3 月) · 17.5 文档、手册与延伸阅读
|
||||
|
||||
## 6. 全部合法锚点(交叉引用只能指向这些)
|
||||
|
||||
```
|
||||
01-what.html#sec-1-1 … sec-1-7
|
||||
02-shell.html#sec-2-1 … sec-2-8
|
||||
03-fs.html#sec-3-1 … sec-3-7
|
||||
04-perm.html#sec-4-1 … sec-4-7
|
||||
05-text.html#sec-5-1 … sec-5-7
|
||||
06-proc.html#sec-6-1 … sec-6-8
|
||||
07-systemd.html#sec-7-1 … sec-7-8
|
||||
08-disk.html#sec-8-1 … sec-8-8
|
||||
09-net.html#sec-9-1 … sec-9-8
|
||||
10-ssh.html#sec-10-1 … sec-10-8
|
||||
11-pkg.html#sec-11-1 … sec-11-7
|
||||
12-boot.html#sec-12-1 … sec-12-7
|
||||
13-perf.html#sec-13-1 … sec-13-8
|
||||
14-sec.html#sec-14-1 … sec-14-8
|
||||
15-dev.html#sec-15-1 … sec-15-8
|
||||
16-cheat.html#sec-16-1 … sec-16-7
|
||||
17-checklist.html#sec-17-1 … sec-17-5
|
||||
```
|
||||
|
||||
引用某一章但不引用具体小节时,写文件名即可,例如 <code><a href="04-perm.html">第 4 章</a></code>。
|
||||
|
||||
## 7. 交付前的自检
|
||||
|
||||
```bash
|
||||
cd knowledge/linux
|
||||
node tools/build-nav.js # 生成侧栏/导航(写完章节后必跑)
|
||||
node tools/check-pages.js # 结构、链接、锚点、转义、小节数、篇幅
|
||||
```
|
||||
|
||||
只写自己那几章时可以只跑 `node tools/check-pages.js`,它会一并检查别人已完成的页面;
|
||||
如果报错指向的不是你的文件,忽略即可。
|
||||
181
knowledge/linux/tools/build-nav.js
Normal file
181
knowledge/linux/tools/build-nav.js
Normal file
@@ -0,0 +1,181 @@
|
||||
#!/usr/bin/env node
|
||||
/* ==========================================================================
|
||||
Linux 专题 · 页面骨架生成器
|
||||
用法:node tools/build-nav.js [站点根目录,默认本文件的上一级]
|
||||
|
||||
作用:扫描站点根目录下的 NN-*.html,采集「章标题(h2)+ 小节(h3)」与
|
||||
每章的 <meta name="description">,然后重写页面里的占位区块:
|
||||
|
||||
章节页:<nav id="chapters"></nav> 侧栏目录树(当前章展开小节)
|
||||
<p class="chapnav"></p> 「第 N / 17 章」定位条
|
||||
<nav class="pager"></nav> 上一章 / 下一章
|
||||
<p class="foot"></p> 页脚
|
||||
目录页:<nav id="chapters"></nav> 全部章节(不展开小节)
|
||||
<!-- AUTO:kpis --> 章节 / 小节 / 代码示例 / 字数 四块指标
|
||||
<!-- AUTO:cards --> 章节卡片(勾选已读 + 展开小节链接)
|
||||
<nav class="pager"></nav> 「开始阅读」
|
||||
<p class="foot"></p>
|
||||
|
||||
写章节时只写正文,骨架由本脚本统一生成;新增/重排章节后重新执行即可,
|
||||
幂等、可重复运行。
|
||||
========================================================================== */
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
|
||||
const root = process.argv[2] || path.resolve(__dirname, "..");
|
||||
const SITE = "Linux 专题";
|
||||
const SITE_SUB = "从命令行到生产运维的系统知识库";
|
||||
|
||||
const esc = s => String(s).replace(/&/g, "&").replace(/</g, "<")
|
||||
.replace(/>/g, ">").replace(/"/g, """);
|
||||
const stripTags = s => s.replace(/<[^>]+>/g, " ").replace(/\s+/g, " ").trim();
|
||||
const decode = s => s.replace(/</g, "<").replace(/>/g, ">").replace(/"/g, '"')
|
||||
.replace(/'/g, "'").replace(/ /g, " ").replace(/&/g, "&");
|
||||
const plain = s => decode(stripTags(s));
|
||||
|
||||
/* ---------------------------- 1. 采集 ---------------------------- */
|
||||
const files = fs.readdirSync(root, { withFileTypes: true })
|
||||
.filter(e => e.isFile() && /^\d\d-.*\.html$/.test(e.name))
|
||||
.map(e => e.name).sort();
|
||||
|
||||
if (!files.length) {
|
||||
console.error("没有找到 NN-*.html 章节页,请检查目录:" + root);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const chapters = files.map(file => {
|
||||
const html = fs.readFileSync(path.join(root, file), "utf8");
|
||||
const num = parseInt(file.slice(0, 2), 10);
|
||||
|
||||
const h2 = html.match(/<h2 id="[^"]*">([\s\S]*?)<\/h2>/);
|
||||
if (!h2) throw new Error(`${file}: 找不到 <h2 id="...">章标题</h2>`);
|
||||
const title = plain(h2[1].replace(/<span class="n">\d+<\/span>/, ""));
|
||||
|
||||
const sections = [...html.matchAll(/<h3 id="([^"]+)">([\s\S]*?)<\/h3>/g)]
|
||||
.map(m => ({ id: m[1], label: plain(m[2]) }));
|
||||
|
||||
const metaDesc = (html.match(/<meta name="description" content="([^"]*)"/) || [, ""])[1];
|
||||
const metaKeys = (html.match(/<meta name="keywords" content="([^"]*)"/) || [, ""])[1];
|
||||
const article = (html.match(/<article>([\s\S]*)<\/article>/) || [, ""])[1];
|
||||
// 正文字数不含代码块(代码块单独统计段数)
|
||||
const bodyText = article.replace(/<pre[\s\S]*?<\/pre>/g, " ");
|
||||
|
||||
return {
|
||||
num, file, title, sections,
|
||||
desc: plain(metaDesc),
|
||||
keywords: plain(metaKeys),
|
||||
pres: (html.match(/<pre[\s\S]*?<\/pre>/g) || []).length,
|
||||
chars: plain(bodyText).replace(/\s+/g, "").length
|
||||
};
|
||||
});
|
||||
|
||||
const totalSecs = chapters.reduce((n, c) => n + c.sections.length, 0);
|
||||
const totalPres = chapters.reduce((n, c) => n + c.pres, 0);
|
||||
const totalChars = chapters.reduce((n, c) => n + c.chars, 0);
|
||||
|
||||
/* ---------------------------- 2. 区块生成 ---------------------------- */
|
||||
function navTree(curNum) {
|
||||
return chapters.map(c => {
|
||||
const isCur = c.num === curNum;
|
||||
const row = isCur
|
||||
? `<span class="toc-a active" aria-current="page"><i class="cn">${c.num}</i>${esc(c.title)}</span>`
|
||||
: `<a class="toc-a" href="${c.file}"><i class="cn">${c.num}</i>${esc(c.title)}</a>`;
|
||||
if (!isCur || !c.sections.length) return row;
|
||||
const sub = c.sections.map(s =>
|
||||
`<a class="toc-a lv3" href="#${s.id}">${esc(s.label)}</a>`).join("");
|
||||
return row + `<div class="subnav current">${sub}</div>`;
|
||||
}).join("");
|
||||
}
|
||||
|
||||
function chapnav(c) {
|
||||
return ` <a href="index.html">${SITE}</a>\n` +
|
||||
` <span>·</span>\n` +
|
||||
` <span>第 <b class="pos">${c.num}</b> / ${chapters.length} 章</span>`;
|
||||
}
|
||||
|
||||
function pager(c) {
|
||||
const i = chapters.indexOf(c);
|
||||
const a = (ch, cls, k) => ch
|
||||
? ` <a class="${cls}" href="${ch.file}"><span class="k">${k}</span><span class="v">第 ${ch.num} 章 · ${esc(ch.title)}</span></a>`
|
||||
: ` <a class="${cls} disabled"><span class="k">${k}</span><span class="v">没有更多了</span></a>`;
|
||||
return a(chapters[i - 1], "prev", "← 上一章") + "\n" + a(chapters[i + 1], "next", "下一章 →");
|
||||
}
|
||||
|
||||
function foot(c) {
|
||||
return ` ${SITE} · 第 ${c.num} 章 ${esc(c.title)}<br>\n` +
|
||||
` <a href="index.html">总目录</a> · <a href="../docker/index.html">Docker 专题</a> · ` +
|
||||
`<a href="../sre-learning-path/index.html">SRE 学习路径</a>`;
|
||||
}
|
||||
|
||||
function kpis() {
|
||||
const wan = (totalChars / 10000).toFixed(1);
|
||||
return [
|
||||
`<div class="kpi"><b>${chapters.length}</b><span>章 · 完整知识体系</span></div>`,
|
||||
`<div class="kpi"><b>${totalSecs}</b><span>个知识点小节</span></div>`,
|
||||
`<div class="kpi"><b>${totalPres}</b><span>段可复制代码</span></div>`,
|
||||
`<div class="kpi"><b>${wan} 万</b><span>字正文</span></div>`
|
||||
].join("\n ");
|
||||
}
|
||||
|
||||
function cards() {
|
||||
return chapters.map(c => {
|
||||
const search = [c.title, c.desc, c.keywords, c.sections.map(s => s.label).join(" ")]
|
||||
.join(" ").toLowerCase();
|
||||
const secs = c.sections.map(s =>
|
||||
`<a href="${c.file}#${s.id}">${esc(s.label)}</a>`).join("");
|
||||
return ` <div class="chapcard" data-search="${esc(search)}">
|
||||
<div class="cc-head">
|
||||
<input type="checkbox" data-ch="${c.num}" aria-label="标记第 ${c.num} 章已读">
|
||||
<span class="cc-no">${c.num}</span>
|
||||
<a class="cc-title" href="${c.file}">${esc(c.title)}</a>
|
||||
<a class="cc-go" href="${c.file}">进入 →</a>
|
||||
</div>
|
||||
<p class="cc-desc">${esc(c.desc)}</p>
|
||||
<details class="cc-secs">
|
||||
<summary>${c.sections.length} 个小节 · 展开看知识点</summary>
|
||||
<div>${secs}</div>
|
||||
</details>
|
||||
</div>`;
|
||||
}).join("\n");
|
||||
}
|
||||
|
||||
/* ---------------------------- 3. 写回 ---------------------------- */
|
||||
const Z = (re, gen, only) => ({ re, gen, only }); // only: "index" | "chapter" | undefined
|
||||
|
||||
const zones = [
|
||||
Z(/<nav id="chapters">[\s\S]*?<\/nav>/, (c, idx) => `<nav id="chapters">${navTree(idx ? 0 : c.num)}</nav>`),
|
||||
Z(/<p class="chapnav">[\s\S]*?<\/p>/, c => `<p class="chapnav">\n${chapnav(c)}\n </p>`, "chapter"),
|
||||
Z(/<!-- AUTO:kpis -->[\s\S]*?<!-- \/AUTO:kpis -->/, () => `<!-- AUTO:kpis -->\n ${kpis()}\n <!-- /AUTO:kpis -->`, "index"),
|
||||
Z(/<!-- AUTO:cards -->[\s\S]*?<!-- \/AUTO:cards -->/, () => `<!-- AUTO:cards -->\n${cards()}\n <!-- /AUTO:cards -->`, "index"),
|
||||
Z(/<nav class="pager">[\s\S]*?<\/nav>/, (c, idx) => idx
|
||||
? `<nav class="pager">\n <a class="next" href="${chapters[0].file}"><span class="k">开始阅读 →</span><span class="v">第 1 章 · ${esc(chapters[0].title)}</span></a>\n </nav>`
|
||||
: `<nav class="pager">\n${pager(c)}\n </nav>`),
|
||||
Z(/<p class="foot">[\s\S]*?<\/p>/, (c, idx) => idx
|
||||
? `<p class="foot">\n ${SITE}知识库 · 共 ${chapters.length} 章 ${totalSecs} 个小节 · ${totalPres} 段代码<br>\n <a href="index.html">总目录</a> · <a href="../docker/index.html">Docker 专题</a> · <a href="../sre-learning-path/index.html">SRE 学习路径</a>\n </p>`
|
||||
: `<p class="foot">\n${foot(c)}\n </p>`)
|
||||
];
|
||||
|
||||
let pages = 0;
|
||||
const targets = chapters.map(c => ({ c, file: c.file, idx: false }));
|
||||
if (fs.existsSync(path.join(root, "index.html"))) {
|
||||
targets.push({ c: chapters[0], file: "index.html", idx: true });
|
||||
}
|
||||
|
||||
for (const t of targets) {
|
||||
const p = path.join(root, t.file);
|
||||
let html = fs.readFileSync(p, "utf8");
|
||||
for (const z of zones) {
|
||||
if (z.only === "index" && !t.idx) continue;
|
||||
if (z.only === "chapter" && t.idx) continue;
|
||||
if (!z.re.test(html)) throw new Error(`${t.file}: 缺少占位区块 ${z.re}`);
|
||||
html = html.replace(z.re, z.gen(t.c, t.idx));
|
||||
}
|
||||
fs.writeFileSync(p, html, "utf8");
|
||||
pages++;
|
||||
}
|
||||
|
||||
chapters.forEach(c => console.log(
|
||||
`${c.file.padEnd(20)} 第 ${String(c.num).padStart(2)} 章 · ${String(c.sections.length).padStart(2)} 小节 · ` +
|
||||
`${String(c.pres).padStart(2)} 段代码 · ${String(c.chars).padStart(6)} 字 · ${c.title}`));
|
||||
console.log(`\n共 ${chapters.length} 章 / ${totalSecs} 小节 / ${totalPres} 段代码 / ${(totalChars / 10000).toFixed(1)} 万字,已同步 ${pages} 个页面。`);
|
||||
console.log(`站点副标题:${SITE_SUB}`);
|
||||
168
knowledge/linux/tools/check-chapter.js
Normal file
168
knowledge/linux/tools/check-chapter.js
Normal file
@@ -0,0 +1,168 @@
|
||||
#!/usr/bin/env node
|
||||
/* ==========================================================================
|
||||
Linux 专题 · 单章自检(写章节时用这个,比全站 check-pages.js 更聚焦)
|
||||
用法:node tools/check-chapter.js 04-perm.html
|
||||
node tools/check-chapter.js # 不给参数则检查所有 NN-*.html
|
||||
|
||||
只校验「作者需要负责」的东西,不校验侧栏/上下章/页脚(那些由
|
||||
tools/build-nav.js 在收尾时统一生成,中途为空是正常的):
|
||||
- 模板结构:title / meta description / meta keywords / article / 四个占位块 /
|
||||
doc.css / doc.js / 主题按钮 / 不越界链接
|
||||
- 代码块:data-lang 是否标注且在允许列表内、块内 < 是否转义
|
||||
- 标签配对:div/section/article/aside/nav/main/details/table/ul/ol/li
|
||||
- 章节:h2 有 id、h3 全部有 id 且以 sec-章号- 开头、小节数 3–10
|
||||
- 组件:至少 1 个 .box、至少 1 个表格或卡片组、至少 1 处实战落点
|
||||
- 体量:至少 3 个代码块、正文不少于 2800 字
|
||||
- 链接:跨章链接指向的文件若尚未生成会标为提示(可忽略),存在则校验锚点
|
||||
========================================================================== */
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
|
||||
const root = path.resolve(__dirname, "..");
|
||||
const problems = [];
|
||||
const hints = [];
|
||||
|
||||
const LANGS = ["bash", "shell", "sh", "console", "text", "plain", "yaml", "yml", "json", "toml",
|
||||
"conf", "config", "ini", "systemd", "unit", "fstab", "crontab", "ssh", "sshconfig", "log",
|
||||
"diff", "csv", "xml", "http", "nginx", "makefile", "dockerfile", "properties",
|
||||
"go", "javascript", "js", "typescript", "ts", "python", "java", "c", "cpp", "sql",
|
||||
"powershell", "promql", "regex", "awk", "sed", "lua"];
|
||||
|
||||
const stripTags = s => s.replace(/<[^>]+>/g, "");
|
||||
const norm = s => s.replace(/\s+/g, "").length;
|
||||
|
||||
const args = process.argv.slice(2);
|
||||
const files = args.length
|
||||
? args
|
||||
: fs.readdirSync(root).filter(f => /^\d\d-.*\.html$/.test(f)).sort();
|
||||
|
||||
if (!files.length) {
|
||||
console.error("没有找到章节文件。用法:node tools/check-chapter.js 04-perm.html");
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
/* 已存在章节的 id 索引,用于跨章锚点校验 */
|
||||
const idIndex = new Map();
|
||||
for (const f of fs.readdirSync(root).filter(f => /^\d\d-.*\.html$/.test(f)).concat(["index.html"])) {
|
||||
if (!fs.existsSync(path.join(root, f))) continue;
|
||||
idIndex.set(f, new Set([...fs.readFileSync(path.join(root, f), "utf8")
|
||||
.matchAll(/\sid="([^"]+)"/g)].map(m => m[1])));
|
||||
}
|
||||
|
||||
for (const f of files) {
|
||||
const p = path.join(root, f);
|
||||
if (!fs.existsSync(p)) { problems.push(`${f}: 文件不存在`); continue; }
|
||||
if (!/^\d\d-.*\.html$/.test(f)) { problems.push(`${f}: 文件名必须是 NN-slug.html`); continue; }
|
||||
|
||||
const html = fs.readFileSync(p, "utf8");
|
||||
const markup = html.replace(/<script[\s\S]*?<\/script>/g, "");
|
||||
const num = parseInt(f.slice(0, 2), 10);
|
||||
const own = [];
|
||||
|
||||
/* ---------------- 结构 ---------------- */
|
||||
if (!new RegExp(`<title>[^<]*第 ${num} 章[^<]*</title>`).test(html)) own.push("title 里应含「第 N 章」");
|
||||
if (!/<article>/.test(html)) own.push("缺少 <article>");
|
||||
if (!html.includes('id="chapters"')) own.push("缺少侧栏 <nav id=\"chapters\">");
|
||||
if (!html.includes('class="chapnav"')) own.push("缺少 <p class=\"chapnav\"></p>");
|
||||
if (!html.includes('class="pager"')) own.push("缺少 <nav class=\"pager\"></nav>");
|
||||
if (!html.includes('class="foot"')) own.push("缺少 <p class=\"foot\"></p>");
|
||||
if (!html.includes('href="assets/doc.css"')) own.push("doc.css 路径不对");
|
||||
if (!html.includes('src="assets/doc.js"')) own.push("doc.js 路径不对");
|
||||
if (!html.includes('id="themeBtn"')) own.push("缺少主题切换按钮");
|
||||
if (!html.includes('href="index.html"')) own.push("缺少返回总目录链接");
|
||||
if (!/class="brand"/.test(html)) own.push("缺少 topbar 品牌区");
|
||||
if (!/<h2 id="ch\d+"><span class="n">\d+<\/span>/.test(html)) own.push("章标题格式应为 <h2 id=\"chN\"><span class=\"n\">N</span>标题</h2>");
|
||||
if (!/class="lead"/.test(html)) own.push("缺少 <div class=\"lead\">");
|
||||
|
||||
const desc = (html.match(/<meta name="description" content="([^"]*)"/) || [, ""])[1];
|
||||
if (desc.trim().length < 20) own.push(`meta description 太短或缺失(${desc.length} 字)`);
|
||||
const keys = (html.match(/<meta name="keywords" content="([^"]*)"/) || [, ""])[1];
|
||||
if (keys.trim().length < 6) own.push(`meta keywords 太短或缺失(${keys.length} 字)`);
|
||||
|
||||
if (/href="\.\.\/(?!docker\/|sre-learning-path\/)/.test(markup)) {
|
||||
own.push("站内链接不应跑出本资料目录(只允许 ../docker/ 与 ../sre-learning-path/)");
|
||||
}
|
||||
|
||||
/* ---------------- 代码块 ---------------- */
|
||||
const pres = markup.match(/<pre[\s\S]*?<\/pre>/g) || [];
|
||||
pres.forEach((blk, i) => {
|
||||
if (!/data-lang=/.test(blk)) own.push(`第 ${i + 1} 个 <pre> 未标注 data-lang`);
|
||||
const body = blk.replace(/^<pre[^>]*>/, "").replace(/<\/pre>$/, "");
|
||||
if (/</.test(body)) own.push(`第 ${i + 1} 个 <pre> 内有未转义的 <(应为 <)`);
|
||||
});
|
||||
for (const m of markup.matchAll(/<pre data-lang="([^"]*)"/g)) {
|
||||
if (!LANGS.includes(m[1])) own.push(`data-lang="${m[1]}" 不在允许列表里(见 SPEC 第 2 节)`);
|
||||
}
|
||||
if (pres.length < 3) own.push(`代码块过少(${pres.length}),至少 3 个`);
|
||||
|
||||
/* ---------------- 标签配对 ---------------- */
|
||||
for (const t of ["div", "section", "article", "aside", "nav", "main", "details", "table", "ul", "ol", "li"]) {
|
||||
const o = (markup.match(new RegExp("<" + t + "(?=[\\s>])", "g")) || []).length;
|
||||
const c = (markup.match(new RegExp("</" + t + ">", "g")) || []).length;
|
||||
if (o !== c) own.push(`<${t}> 开合不匹配 ${o}/${c}`);
|
||||
}
|
||||
|
||||
/* ---------------- 组件构成 ---------------- */
|
||||
if (!/class="box (note|tip|warn|danger|ok|case|lab)"/.test(html)) own.push("没有任何 .box 提示框");
|
||||
if (!/class="tablewrap"/.test(html) && !/class="cards"/.test(html)) own.push("既没有表格也没有卡片组");
|
||||
if (!/class="box case"|class="box lab"|实战|实际用法/.test(html)) {
|
||||
own.push("缺少「开发/运维实际用法」落点(.box case / .box lab / 标题含实战)");
|
||||
}
|
||||
|
||||
/* ---------------- 小节 ---------------- */
|
||||
const h3 = [...html.matchAll(/<h3 id="([^"]+)">([\s\S]*?)<\/h3>/g)];
|
||||
const h3any = (html.match(/<h3[ >]/g) || []).length;
|
||||
if (h3.length !== h3any) own.push(`有 ${h3any - h3.length} 个 h3 未补 id`);
|
||||
if (h3.length < 3) own.push(`小节过少(${h3.length}),至少 3 个`);
|
||||
if (h3.length > 10) own.push(`小节过多(${h3.length}),最多 10 个`);
|
||||
const seen = new Set();
|
||||
const secOrder = [];
|
||||
for (const m of h3) {
|
||||
if (!m[1].startsWith(`sec-${num}-`)) own.push(`小节 id "${m[1]}" 应以 sec-${num}- 开头`);
|
||||
if (seen.has(m[1])) own.push(`小节 id 重复:${m[1]}`);
|
||||
seen.add(m[1]);
|
||||
/* 标题文本必须带「N.M」编号,且与 id 里的序号一致 */
|
||||
const title = stripTags(m[2]).replace(/ /g, " ").trim();
|
||||
const label = title.match(/^(\d+)\.(\d+)\b/);
|
||||
const idSeq = m[1].slice(`sec-${num}-`.length);
|
||||
if (!label) own.push(`小节标题缺少「${num}.M」编号:${title.slice(0, 30)}`);
|
||||
else {
|
||||
if (label[1] !== String(num)) own.push(`小节标题编号与章号不符:${title.slice(0, 30)}`);
|
||||
if (label[2] !== idSeq) own.push(`小节标题编号 ${label[1]}.${label[2]} 与 id ${m[1]} 不一致`);
|
||||
secOrder.push(parseInt(label[2], 10));
|
||||
}
|
||||
}
|
||||
for (let i = 1; i < secOrder.length; i++) {
|
||||
if (secOrder[i] !== secOrder[i - 1] + 1) own.push(`小节编号不连续:…${secOrder[i - 1]} → ${secOrder[i]}`);
|
||||
}
|
||||
|
||||
/* ---------------- 体量 ---------------- */
|
||||
const body = norm(stripTags(markup.replace(/<pre[\s\S]*?<\/pre>/g, " ")));
|
||||
if (body < 2800) own.push(`正文过短(约 ${body} 字,不含代码),至少要 2800 字`);
|
||||
|
||||
/* ---------------- 链接与锚点 ---------------- */
|
||||
for (const l of new Set([...markup.matchAll(/href="(?!https?:|mailto:|#)([^"]+)"/g)].map(m => m[1]))) {
|
||||
const [file, hash] = l.split("#");
|
||||
const target = path.join(root, file || f);
|
||||
if (file && !fs.existsSync(target)) { hints.push(`${f}: 目标章节尚未生成 → ${l}`); continue; }
|
||||
const key = path.basename(file || f);
|
||||
if (hash && idIndex.has(key) && !idIndex.get(key).has(hash)) own.push(`锚点不存在:${l}`);
|
||||
}
|
||||
for (const l of new Set([...markup.matchAll(/href="#([^"]+)"/g)].map(m => m[1]))) {
|
||||
if (idIndex.has(f) && !idIndex.get(f).has(l)) own.push(`页内锚点不存在:#${l}`);
|
||||
}
|
||||
|
||||
if (own.length) problems.push(...own.map(x => `${f}: ${x}`));
|
||||
console.log(`${f.padEnd(20)} ${String(h3.length).padStart(2)} 小节 · ${String(pres.length).padStart(2)} 段代码 · ${body} 字正文 · ${own.length ? "✗ " + own.length + " 个问题" : "✓ 通过"}`);
|
||||
}
|
||||
|
||||
if (hints.length) {
|
||||
console.log(`\n提示(并行写作期间正常,可忽略):`);
|
||||
hints.slice(0, 12).forEach(x => console.log(" - " + x));
|
||||
}
|
||||
if (problems.length) {
|
||||
console.error(`\n发现 ${problems.length} 个问题:`);
|
||||
problems.forEach(x => console.error(" - " + x));
|
||||
process.exit(1);
|
||||
}
|
||||
console.log(`\nOK ${files.length} 个章节文件全部通过单章自检。`);
|
||||
176
knowledge/linux/tools/check-pages.js
Normal file
176
knowledge/linux/tools/check-pages.js
Normal file
@@ -0,0 +1,176 @@
|
||||
#!/usr/bin/env node
|
||||
/* ==========================================================================
|
||||
Linux 专题 · 页面自检
|
||||
用法:node tools/check-pages.js [站点根目录,默认本文件的上一级]
|
||||
|
||||
检查项:
|
||||
- 结构:title / keywords / description / article / #chapters / doc.css / doc.js /
|
||||
chapnav / pager / foot / 主题按钮
|
||||
- 代码块:是否标注 data-lang(且在允许列表内)、块内 < 是否转义
|
||||
- 标签配对:div/section/article/aside/nav/main/details/table/ul/ol/li
|
||||
- 链接:站内文件是否存在、锚点是否真实可达
|
||||
- 章节:h2 有 id、h3 全部有 id、小节 id 前缀与章号一致、小节数 3–10
|
||||
- 目录树:每个页面都列出全部章节,当前章展开小节且数量与正文一致
|
||||
- 体量:正文过短会报错(防止只写了标题)
|
||||
========================================================================== */
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
|
||||
const root = process.argv[2] || path.resolve(__dirname, "..");
|
||||
const problems = [];
|
||||
const info = [];
|
||||
|
||||
const must = (c, m) => { if (!c) problems.push(m); };
|
||||
const read = p => fs.readFileSync(p, "utf8");
|
||||
const stripTags = s => s.replace(/<[^>]+>/g, "");
|
||||
const norm = s => s.replace(/\s+/g, "").length;
|
||||
|
||||
const LANGS = ["bash", "shell", "sh", "console", "text", "plain", "yaml", "yml", "json", "toml",
|
||||
"conf", "config", "ini", "systemd", "unit", "fstab", "crontab", "ssh", "sshconfig", "log",
|
||||
"diff", "csv", "xml", "http", "nginx", "makefile", "dockerfile", "properties",
|
||||
"go", "javascript", "js", "typescript", "ts", "python", "java", "c", "cpp", "sql",
|
||||
"powershell", "promql", "regex", "awk", "sed", "lua"];
|
||||
|
||||
const chapterFiles = fs.readdirSync(root).filter(f => /^\d\d-.*\.html$/.test(f)).sort();
|
||||
must(chapterFiles.length >= 5, "章节页数量异常:" + chapterFiles.length);
|
||||
const pages = chapterFiles.concat(fs.existsSync(path.join(root, "index.html")) ? ["index.html"] : []);
|
||||
const totalChapters = chapterFiles.length;
|
||||
|
||||
/* id 索引,供锚点校验 */
|
||||
const idIndex = new Map();
|
||||
for (const f of pages) {
|
||||
const html = read(path.join(root, f));
|
||||
idIndex.set(f, new Set([...html.matchAll(/\sid="([^"]+)"/g)].map(m => m[1])));
|
||||
}
|
||||
|
||||
for (const f of pages) {
|
||||
const html = read(path.join(root, f));
|
||||
const markup = html.replace(/<script[\s\S]*?<\/script>/g, "");
|
||||
const isIndex = f === "index.html";
|
||||
|
||||
must(/<title>[^<]+<\/title>/.test(html), `${f}: 缺少 title`);
|
||||
must(html.includes("<article>"), `${f}: 缺少 <article>`);
|
||||
must(html.includes('id="chapters"'), `${f}: 缺少侧栏 #chapters`);
|
||||
must(html.includes('href="assets/doc.css"'), `${f}: doc.css 路径不对`);
|
||||
must(html.includes('src="assets/doc.js"'), `${f}: doc.js 路径不对`);
|
||||
must(html.includes('id="themeBtn"'), `${f}: 缺少主题切换按钮`);
|
||||
must(!/href="\.\.\/(?!docker\/|sre-learning-path\/)/.test(markup),
|
||||
`${f}: 站内链接不应跑出本资料目录(只允许 ../docker/ 与 ../sre-learning-path/)`);
|
||||
|
||||
/* 代码块 */
|
||||
const pres = markup.match(/<pre[\s\S]*?<\/pre>/g) || [];
|
||||
pres.forEach((blk, i) => {
|
||||
if (!/data-lang=/.test(blk)) problems.push(`${f}: 第 ${i + 1} 个 <pre> 未标注 data-lang`);
|
||||
const body = blk.replace(/^<pre[^>]*>/, "").replace(/<\/pre>$/, "");
|
||||
if (/</.test(body)) problems.push(`${f}: 第 ${i + 1} 个 <pre> 内有未转义的 <`);
|
||||
});
|
||||
for (const m of markup.matchAll(/<pre data-lang="([^"]*)"/g)) {
|
||||
if (!LANGS.includes(m[1])) problems.push(`${f}: data-lang="${m[1]}" 不在允许列表里`);
|
||||
}
|
||||
|
||||
/* 标签配对 */
|
||||
for (const t of ["div", "section", "article", "aside", "nav", "main", "details", "table", "ul", "ol", "li"]) {
|
||||
const o = (markup.match(new RegExp("<" + t + "(?=[\\s>])", "g")) || []).length;
|
||||
const c = (markup.match(new RegExp("</" + t + ">", "g")) || []).length;
|
||||
if (o !== c) problems.push(`${f}: <${t}> 开合不匹配 ${o}/${c}`);
|
||||
}
|
||||
|
||||
/* 链接与锚点 */
|
||||
for (const l of new Set([...markup.matchAll(/href="(?!https?:|mailto:|#)([^"]+)"/g)].map(m => m[1]))) {
|
||||
const [file, hash] = l.split("#");
|
||||
const target = path.resolve(root, file || f);
|
||||
if (file && !fs.existsSync(target)) { problems.push(`${f}: 死链 ${l}`); continue; }
|
||||
const key = file ? path.basename(file) : f;
|
||||
if (hash && idIndex.has(key) && !idIndex.get(key).has(hash)) problems.push(`${f}: 锚点不存在 ${l}`);
|
||||
}
|
||||
for (const l of new Set([...markup.matchAll(/href="#([^"]+)"/g)].map(m => m[1]))) {
|
||||
if (!idIndex.get(f).has(l)) problems.push(`${f}: 页内锚点不存在 #${l}`);
|
||||
}
|
||||
|
||||
if (!isIndex) {
|
||||
const num = parseInt(f.slice(0, 2), 10);
|
||||
const h2 = html.match(/<h2 id="([^"]+)">([\s\S]*?)<\/h2>/);
|
||||
|
||||
/* 元信息与组件构成 */
|
||||
const desc = (html.match(/<meta name="description" content="([^"]*)"/) || [, ""])[1];
|
||||
const keys = (html.match(/<meta name="keywords" content="([^"]*)"/) || [, ""])[1];
|
||||
if (desc.trim().length < 20) problems.push(`${f}: meta description 太短或缺失(${desc.length} 字)`);
|
||||
if (keys.trim().length < 6) problems.push(`${f}: meta keywords 太短或缺失(${keys.length} 字)`);
|
||||
if (!/class="box (note|tip|warn|danger|ok|case|lab)"/.test(html)) problems.push(`${f}: 没有任何 .box 提示框`);
|
||||
if (!/class="tablewrap"/.test(html) && !/class="cards"/.test(html)) {
|
||||
problems.push(`${f}: 既没有表格也没有卡片组`);
|
||||
}
|
||||
must(/class="box case"|class="box lab"|实战|实际用法/.test(html),
|
||||
`${f}: 缺少「开发/运维实际用法」的落点(.box case / .box lab / 实战小节)`);
|
||||
if (pres.length < 3) problems.push(`${f}: 代码块过少(${pres.length}),至少 3 个`);
|
||||
must(!!h2, `${f}: 缺少 h2 章节标题`);
|
||||
must(html.includes('class="chapnav"'), `${f}: 缺少章节定位条 .chapnav`);
|
||||
must(html.includes('class="pager"'), `${f}: 缺少上一/下一章 .pager`);
|
||||
must(html.includes('class="foot"'), `${f}: 缺少页脚 .foot`);
|
||||
must(html.includes('href="index.html"'), `${f}: 缺少返回总目录链接`);
|
||||
must(/class="toc-a active"[^>]*aria-current="page"/.test(html), `${f}: 当前章未标记 active`);
|
||||
|
||||
const h3 = [...html.matchAll(/<h3 id="([^"]+)">([\s\S]*?)<\/h3>/g)];
|
||||
const h3any = (html.match(/<h3[ >]/g) || []).length;
|
||||
must(h3.length === h3any, `${f}: 有 h3 未补 id(${h3.length}/${h3any})`);
|
||||
must(h3.length >= 3, `${f}: 小节过少(${h3.length}),至少 3 个`);
|
||||
if (h3.length > 10) problems.push(`${f}: 小节过多(${h3.length}),最多 10 个`);
|
||||
for (const m of h3) {
|
||||
if (!m[1].startsWith(`sec-${num}-`)) problems.push(`${f}: 小节 id "${m[1]}" 应以 sec-${num}- 开头`);
|
||||
const title = stripTags(m[2]).replace(/ /g, " ").trim();
|
||||
const label = title.match(/^(\d+)\.(\d+)\b/);
|
||||
const idSeq = m[1].slice(`sec-${num}-`.length);
|
||||
if (!label) problems.push(`${f}: 小节标题缺少「${num}.M」编号:${title.slice(0, 30)}`);
|
||||
else {
|
||||
if (label[1] !== String(num)) problems.push(`${f}: 小节标题编号与章号不符:${title.slice(0, 30)}`);
|
||||
if (label[2] !== idSeq) problems.push(`${f}: 小节标题编号 ${label[1]}.${label[2]} 与 id ${m[1]} 不一致`);
|
||||
}
|
||||
}
|
||||
/* 上下章导航必须是「上一章 / 下一章」,页脚必须是本章标题 */
|
||||
const pager = html.match(/<nav class="pager">([\s\S]*?)<\/nav>/);
|
||||
must(!!pager && /上一章|下一章/.test(pager[1]), `${f}: .pager 不是章节页的上一/下一章导航`);
|
||||
must(!!pager && !/开始阅读/.test(pager[1]), `${f}: .pager 误用了目录页的「开始阅读」`);
|
||||
must(/class="foot">\s*Linux 专题 · 第 \d+ 章/.test(html.replace(/\n/g, "")),
|
||||
`${f}: 页脚不是本章标题(可能是目录页页脚)`);
|
||||
|
||||
/* 目录树里当前章的小节数量要与正文一致 */
|
||||
const sub = html.match(/<div class="subnav current">([\s\S]*?)<\/div>/);
|
||||
must(!!sub, `${f}: 侧栏缺少当前章小节`);
|
||||
if (sub) {
|
||||
const n = (sub[1].match(/class="toc-a lv3"/g) || []).length;
|
||||
must(n === h3.length, `${f}: 侧栏小节数 ${n} ≠ 正文 h3 数 ${h3.length}`);
|
||||
}
|
||||
const body = norm(stripTags(markup));
|
||||
if (body < 2200) problems.push(`${f}: 正文过短(约 ${body} 字),内容需要补充`);
|
||||
}
|
||||
|
||||
/* 目录树必须列出全部章节 */
|
||||
const nav = html.match(/<nav id="chapters">([\s\S]*?)<\/nav>/);
|
||||
must(!!nav, `${f}: 缺少 #chapters 目录树`);
|
||||
if (isIndex) {
|
||||
const pg = html.match(/<nav class="pager">([\s\S]*?)<\/nav>/);
|
||||
must(!!pg && /开始阅读/.test(pg[1]), "index.html: .pager 缺少「开始阅读」入口");
|
||||
must(!!pg && !/上一章|下一章/.test(pg[1]), "index.html: .pager 误用了章节页的上一/下一章");
|
||||
must(/class="foot">\s*Linux 专题知识库/.test(html.replace(/\n/g, "")), "index.html: 页脚不是目录页页脚");
|
||||
}
|
||||
if (nav) {
|
||||
const rows = (nav[1].match(/class="toc-a( active)?"/g) || []).length;
|
||||
must(rows === totalChapters, `${f}: 目录树章节数 ${rows} ≠ ${totalChapters}`);
|
||||
for (const cf of chapterFiles) {
|
||||
if (cf === f) continue;
|
||||
must(nav[1].includes(`href="${cf}"`), `${f}: 目录树缺少章节 ${cf}`);
|
||||
}
|
||||
if (isIndex) must(!/class="subnav/.test(nav[1]), "index.html: 目录页不应展开任何章的小节");
|
||||
}
|
||||
|
||||
info.push(`${f.padEnd(24)} ~${norm(stripTags(markup))} 字 · 代码块 ${pres.length}`);
|
||||
}
|
||||
|
||||
info.sort();
|
||||
console.log(info.join("\n"));
|
||||
if (problems.length) {
|
||||
console.error(`\n发现 ${problems.length} 个问题:`);
|
||||
problems.slice(0, 80).forEach(x => console.error(" - " + x));
|
||||
process.exit(1);
|
||||
}
|
||||
console.log(`\nOK 全部校验通过(${chapterFiles.length} 章 + 目录页,共 ${pages.length} 个页面)`);
|
||||
Reference in New Issue
Block a user