Files
FreeCADWasmDev/tools/build-tools-manual.mjs
wangdequan 5b61c77c2c docs(tools): generate full tool usage manual (HTML)
Static scan of tools/ and web/tools/ (1691 files, no tool execution):
purpose/usage/env extraction with provenance badges, family folding
(67 families covering 953 files), 16 directory records, 42 hand-written
chapters plus 4 environment contracts, and a 1996-entry search index.

- tools/tools-manual/{config,scan,extract,chapters,render,verify}.mjs
- tools/build-tools-manual.mjs (--check/--verify/--stats)
- tools/check-tools-manual.mjs (Playwright, desktop + mobile)
- docs/current/tools-manual/index.html (1.08 MB, self-contained)
- web/package.json: manual:tools, check:tools-manual

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-25 03:22:36 +08:00

196 lines
7.6 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
/**
* Purpose: 生成项目工具使用手册(docs/current/tools-manual/index.html)。
*
* 静态扫描 tools/ 与 web/tools/ 下的全部脚本,提取用途/用法/环境变量,
* 归并同族脚本,叠加手写核心章节,输出单文件自包含 HTML。
* 全程不执行任何工具(emcc 垫片等脚本带副作用)。
*
* Usage:
* node tools/build-tools-manual.mjs # 生成
* node tools/build-tools-manual.mjs --check # 校验磁盘文件是否为最新(不一致 exit 1)
* node tools/build-tools-manual.mjs --verify # 生成后做语义断言
* node tools/build-tools-manual.mjs --stats # 只打印统计
* node tools/build-tools-manual.mjs --root <dir> --out <file.html>
*
* Exit: 0 成功 / 1 --check 不一致或校验失败 / 2 参数或读取错误
*/
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { REPO_ROOT, CATEGORIES } from "./tools-manual/config.mjs";
import { scan } from "./tools-manual/scan.mjs";
import { extract } from "./tools-manual/extract.mjs";
import { CHAPTERS, CONTRACT_CHAPTERS } from "./tools-manual/chapters.mjs";
import { render } from "./tools-manual/render.mjs";
import { verify } from "./tools-manual/verify.mjs";
const HERE = path.dirname(fileURLToPath(import.meta.url));
const DEFAULT_ROOT = path.resolve(HERE, "..");
const DEFAULT_OUT = path.join(DEFAULT_ROOT, "docs/current/tools-manual/index.html");
function parseArgs(argv) {
const options = { check: false, verify: false, stats: false, root: DEFAULT_ROOT, out: DEFAULT_OUT };
for (let index = 0; index < argv.length; index += 1) {
const arg = argv[index];
if (arg === "--check") options.check = true;
else if (arg === "--verify") options.verify = true;
else if (arg === "--stats") options.stats = true;
else if (arg === "--help" || arg === "-h") {
console.log("node tools/build-tools-manual.mjs [--check] [--verify] [--stats] [--root <dir>] [--out <file>]");
process.exit(0);
} else if (arg === "--root") options.root = path.resolve(argv[++index] ?? ".");
else if (arg === "--out") options.out = path.resolve(argv[++index] ?? DEFAULT_OUT);
else {
console.error(`未知参数:${arg}`);
process.exit(2);
}
}
return options;
}
function slug(value) {
return String(value).toLowerCase().replace(/[^a-z0-9一-龥]+/g, "-").replace(/^-|-$/g, "");
}
/** Anchors must be unique across the whole document. */
function makeAnchorFactory() {
const used = new Set();
return {
/** Hand-authored ids (chapters already carry a `tool-` prefix) are taken as-is. */
reserve(anchor) {
used.add(anchor);
return anchor;
},
unique(prefix, key) {
const base = prefix ? `${prefix}-${slug(key) || "x"}` : slug(key) || "x";
let anchor = base;
let counter = 1;
while (used.has(anchor)) anchor = `${base}-${(counter += 1)}`;
used.add(anchor);
return anchor;
},
};
}
function readNpmCatalog(root) {
const catalog = [];
for (const [rel, cwd] of [["package.json", ""], ["web/package.json", "web"]]) {
let pkg;
try {
pkg = JSON.parse(fs.readFileSync(path.join(root, rel), "utf8"));
} catch {
continue;
}
for (const [name, command] of Object.entries(pkg.scripts ?? {})) catalog.push({ name, command, cwd });
}
return catalog;
}
function buildModel(root) {
const scanned = scan(root);
const extracted = extract(scanned);
const anchors = makeAnchorFactory();
const chapters = CHAPTERS.map((chapter) => ({
...chapter,
anchor: anchors.reserve(chapter.id),
shortTitle: chapter.title.split(" — ")[0],
}));
// Reserved first so generated anchors can never shadow a hand-written id.
for (const contract of CONTRACT_CHAPTERS) anchors.reserve(contract.id);
for (const section of ["overview", "quickstart", "contracts", "topology", "core", "inventory", "npm", "env", "troubleshooting", "maintenance", "appendix"]) anchors.reserve(section);
const families = extracted.families.map((family) => ({ ...family, anchor: anchors.unique("fam", family.id) }));
const records = extracted.records.map((record) => ({ ...record, anchor: anchors.unique("file", record.relPath) }));
const directories = extracted.directories.map((directory) => ({ ...directory, anchor: anchors.unique("dir", directory.relPath) }));
const byCategory = {};
for (const entry of [...families, ...records.filter((record) => !record.familyId), ...directories]) {
byCategory[entry.categoryId] = (byCategory[entry.categoryId] ?? 0) + 1;
}
const stats = {
...extracted.stats,
byCategory,
npmScripts: readNpmCatalog(root).length,
envVars: extracted.envUsage.size,
};
return {
root,
chapters,
contracts: CONTRACT_CHAPTERS,
families,
records,
directories,
envUsage: extracted.envUsage,
npmCatalog: readNpmCatalog(root),
stats,
badges: extracted.badges,
categories: CATEGORIES,
};
}
function main() {
const options = parseArgs(process.argv.slice(2));
if (!fs.existsSync(options.root)) {
console.error(`根目录不存在:${options.root}`);
process.exit(2);
}
const model = buildModel(options.root);
const html = render(model);
if (options.stats) {
const rows = model.stats.rows;
console.log(`文件 ${model.stats.files}`);
console.log(`族 ${model.stats.families}(覆盖 ${model.families.reduce((sum, family) => sum + family.count, 0)} 个文件)`);
console.log(`单列 ${model.stats.singles}`);
console.log(`目录记录 ${model.stats.directories}`);
console.log(`索引行 ${rows}`);
console.log(`手写章节 ${model.chapters.length} + 契约 ${model.contracts.length}`);
console.log(`环境变量 ${model.stats.envVars}`);
console.log(`npm 脚本 ${model.stats.npmScripts}`);
console.log(`分类 ${Object.entries(model.stats.byCategory).map(([id, count]) => `${id}:${count}`).join(" ")}`);
console.log(`页面体积 ${(Buffer.byteLength(html) / 1024).toFixed(0)} KB`);
}
if (options.verify) {
const result = verify({ root: options.root, html, model });
for (const warning of result.warnings) console.warn(`WARN ${warning}`);
for (const error of result.errors) console.error(`FAIL ${error}`);
console.log(`verify: ${result.ok ? "OK" : "FAILED"}(${result.rows} 行,${result.searchEntries} 条搜索项,${(result.bytes / 1024).toFixed(0)} KB)`);
if (!result.ok) process.exit(1);
}
if (options.check) {
let existing = null;
try {
existing = fs.readFileSync(options.out, "utf8");
} catch {
console.error(`FAIL --check:目标文件不存在 ${options.out}`);
process.exit(1);
}
if (existing === html) {
console.log(`check: OK(${options.out} 已是最新)`);
return;
}
let offset = 0;
while (offset < existing.length && offset < html.length && existing[offset] === html[offset]) offset += 1;
console.error(`FAIL --check:磁盘文件与生成结果不一致,首个差异在偏移 ${offset}(磁盘 ${existing.length} 字节 / 生成 ${html.length} 字节)`);
console.error(` 磁盘:${JSON.stringify(existing.slice(offset, offset + 60))}`);
console.error(` 生成:${JSON.stringify(html.slice(offset, offset + 60))}`);
process.exit(1);
}
if (options.stats || options.verify) return;
fs.mkdirSync(path.dirname(options.out), { recursive: true });
fs.writeFileSync(options.out, html);
console.log(`written ${path.relative(options.root, options.out)} (${(Buffer.byteLength(html) / 1024).toFixed(0)} KB)`);
}
main();