Files
FreeCADWasmDev/tools/tools-manual/extract.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

418 lines
17 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.
/**
* Record extraction for tools/build-tools-manual.mjs.
*
* Turns scanned file heads into inventory records: category, role (CLI /
* library / data), Chinese purpose, usage, environment variables, and the
* family a generated sibling belongs to.
*
* Every extracted text keeps its provenance so the page can show a badge and
* nobody mistakes an inference for a declaration.
*/
import path from "node:path";
import { CATEGORIES, CATEGORY_BY_ID, ENV_DOCS, VARIANT_TOKENS } from "./config.mjs";
const BADGE = {
header: "源码注释",
docstring: "源码注释",
npm: "npm 脚本",
family: "族模板(推断)",
filename: "命名推断",
};
export function escapeText(value) {
return String(value ?? "")
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")
.replace(/"/g, "&quot;");
}
function collapse(text) {
return String(text ?? "").replace(/\s+/g, " ").trim();
}
function firstSentences(text, limit) {
const clean = collapse(text);
if (clean.length <= limit) return clean;
const cut = clean.slice(0, limit);
const stop = Math.max(cut.lastIndexOf("。"), cut.lastIndexOf(". "), cut.lastIndexOf(";"), cut.lastIndexOf(";"));
return stop > limit * 0.4 ? `${cut.slice(0, stop + 1)}` : `${cut}…`;
}
function stripCommentDecor(line) {
return line.replace(/^\s*(?:\/\/+|#+|\*+|\/\*+)\s?/, "").replace(/\*\/\s*$/, "").trim();
}
/* --- purpose ------------------------------------------------------------ */
function pythonDocstring(head) {
const start = head.search(/"""/);
if (start < 0 || start > 4000) return null;
const body = head.slice(start + 3);
const end = body.indexOf('"""');
return end < 0 ? null : body.slice(0, end);
}
function jsHeaderComment(head) {
const block = head.match(/^\s*(?:#![^\n]*\n)?\s*\/\*\*?([\s\S]*?)\*\//);
if (block) {
const lines = block[1].split("\n").map(stripCommentDecor).filter(Boolean);
if (lines.length) return lines.join(" ");
}
const lineComments = [];
for (const line of head.split("\n").slice(0, 20)) {
if (/^\s*#!/.test(line)) continue;
if (/^\s*\/\//.test(line)) { lineComments.push(stripCommentDecor(line)); continue; }
if (/^\s*$/.test(line) && lineComments.length === 0) continue;
if (/^\s*$/.test(line) && lineComments.length) break;
if (lineComments.length) break;
}
return lineComments.length ? lineComments.join(" ") : null;
}
function shellHeaderComment(head) {
const lines = [];
for (const line of head.split("\n").slice(0, 15)) {
if (/^\s*#!/.test(line)) continue;
if (/^\s*#/.test(line)) { lines.push(stripCommentDecor(line)); continue; }
if (/^\s*$/.test(line) && lines.length === 0) continue;
break;
}
return lines.length ? lines.join(" ") : null;
}
function extractPurpose(file) {
const explicit = file.head.match(/^\s*(?:\/\/|#|\*)?\s*(?:Purpose|用途)\s*[::]\s*(.+)$/m);
if (explicit) return { text: firstSentences(explicit[1], 320), source: BADGE.header };
const text = file.ext === ".py"
? pythonDocstring(file.head)
: file.ext === ".sh" || file.ext === ".ps1" ? shellHeaderComment(file.head) : jsHeaderComment(file.head);
if (!text) return null;
const cleaned = firstSentences(text, 320);
if (!cleaned || /^copyright|^license|^spdx/i.test(cleaned)) return null;
return { text: cleaned, source: BADGE.docstring };
}
/* --- usage -------------------------------------------------------------- */
const COMMAND_LINE = /^\s*(?:(?:\/\/|#|\*)\s*)?((?:node|npx|python3?|npm|bash|sh|pwsh)\s+[^\n]*)$/gm;
function extractUsage(file) {
const commands = [];
const push = (cmd) => {
const clean = collapse(cmd).replace(/^["']|["']$/g, "");
if (clean && !commands.some((existing) => existing === clean)) commands.push(clean);
};
for (const match of file.head.matchAll(COMMAND_LINE)) push(match[1]);
const usageLine = file.head.match(/^\s*(?:\/\/|#|\*)\s*(?:Usage|用法)\s*[::]\s*(.+)$/m);
if (usageLine) push(usageLine[1]);
const blockUsage = file.head.match(/(?:Usage|用法)\s*[::]\s*\n((?:\s*(?:\/\/|#|\*)\s*\S[^\n]*\n){1,6})/);
if (blockUsage) {
for (const line of blockUsage[1].split("\n")) {
const clean = stripCommentDecor(line);
if (/^(node|npx|python3?|npm|bash|sh|\.\/)/.test(clean)) push(clean);
}
}
return commands.slice(0, 4);
}
/* --- environment -------------------------------------------------------- */
function extractEnv(head) {
const names = new Set();
for (const match of head.matchAll(/process\.env\.([A-Z0-9_]+)/g)) names.add(match[1]);
for (const match of head.matchAll(/process\.env\[\s*["']([A-Z0-9_]+)["']\s*\]/g)) names.add(match[1]);
for (const match of head.matchAll(/os\.environ\[\s*["']([A-Z0-9_]+)["']\s*\]/g)) names.add(match[1]);
for (const match of head.matchAll(/os\.environ\.get\(\s*["']([A-Z0-9_]+)["']/g)) names.add(match[1]);
for (const match of head.matchAll(/os\.getenv\(\s*["']([A-Z0-9_]+)["']/g)) names.add(match[1]);
return [...names].sort();
}
/* --- role --------------------------------------------------------------- */
function detectRole(file, importedBy) {
if (file.ext === ".json" || file.relPath.startsWith("tools/generated-contracts/")) return "data";
const shebang = /^#!/.test(file.head);
const argv = /process\.argv/.test(file.head);
const mainGuard = /__name__\s*==\s*["']__main__["']/.test(file.head);
const argparse = /ArgparseError|ArgumentParser|add_argument\(/.test(file.head);
const hasCliMarkers = shebang || argv || mainGuard || argparse;
const importers = importedBy.get(file.relPath) ?? 0;
if (hasCliMarkers && importers > 0) return "cli-module";
if (hasCliMarkers) return "cli";
if (importers > 0) return "module";
if (/^\s*export\s/m.test(file.head)) return "module";
return "unknown";
}
export const ROLE_LABEL = {
cli: "CLI",
"cli-module": "CLI + 库",
module: "库",
data: "数据",
unknown: "未验证",
};
/* --- classification ----------------------------------------------------- */
export function classify(relPath, name) {
for (const category of CATEGORIES) {
if (category.test(relPath, name)) return category.id;
}
return "other";
}
/* --- families ----------------------------------------------------------- */
function baseName(name) {
return name.replace(/\.(mjs|js|ts|tsx|py|sh|ps1|json|cmake)$/, "");
}
function stripVariantTokens(stem) {
let current = stem;
for (let guard = 0; guard < 5; guard += 1) {
const match = current.match(/^(.*)[-_]([a-z0-9]+)$/);
if (!match || !VARIANT_TOKENS.has(match[2])) break;
current = match[1];
}
return current;
}
const VARIANT_PURPOSE = {
smoke: "冒烟验证:加载 Web 构建并断言核心路径可用。",
gate: "验收门禁:汇总同族结果,非零退出表示不达标。",
chrome: "Chrome 端到端用例:真实浏览器里跑完整交互。",
probe: "探测脚本:采集运行时/界面数据并输出报告。",
worker: "后台 worker 用例:在 worker 环境里校验 Python/原生路由。",
summary: "汇总脚本:把分散的结果聚合成一份摘要。",
receipt: "回执生成:记录一次运行的可核对凭据。",
recovery: "恢复用例:验证失败后的回滚与重试路径。",
persistence: "持久化用例:验证 OPFS/文档存取。",
kernel: "内核用例:直接对 WASM 内核调用断言。",
native: "原生路由用例:校验 C++/Python 原生实现路径。",
boundary: "边界用例:几何与接口的边界条件。",
runtime: "运行时检查:校验生成产物与运行期一致。",
parity: "桌面端与 Web 端一致性检查。",
batch: "批量运行器:按清单跑多个用例。",
cases: "业务场景表:导出用例供 smoke/gate 调用。",
};
function familyOf(relPath, name, stemCounts) {
const base = baseName(name);
const dir = path.posix.dirname(relPath);
let match;
if ((match = base.match(/^run_p6_([a-z0-9]+)_(.+)$/))) {
const [, moduleName, rest] = match;
const variant = rest.replace(/^action\d+_/, "");
return { id: `run_p6.${moduleName}`, title: `run_p6_${moduleName}_*`, variant, module: moduleName, pattern: `run_p6_${moduleName}_<action>_<kind>.mjs` };
}
if (base.includes("-business-cases")) {
const token = base.split("-business-cases")[0];
return { id: `cases.${token}`, title: `${token}-business-cases*`, variant: "cases", module: token, pattern: `${token}-business-cases.mjs` };
}
if ((match = base.match(/^ui-([a-z0-9]+)-(.+)$/))) {
return { id: `ui.${match[1]}`, title: `ui-${match[1]}-*`, variant: "parity", module: match[1], pattern: `ui-${match[1]}-<surface>.mjs` };
}
if (/^build_cam_.*_profile$/.test(base)) {
return { id: "build.cam-profiles", title: "build_cam_*_profile", variant: "build", module: "CAM", pattern: "build_cam_<op>_profile.mjs" };
}
if ((match = base.match(/^build_([a-z0-9]+)_(.+)$/))) {
return { id: `build.${match[1]}`, title: `build_${match[1]}_*`, variant: "build", module: match[1], pattern: `build_${match[1]}_<target>.mjs` };
}
if (/^generate_.*runtime_index$/.test(base)) {
return { id: "codegen.runtime-index", title: "generate_*_runtime_index", variant: "runtime", module: "runtime", pattern: "generate_<family>_runtime_index.py" };
}
if (/^generate_.*adapter_manifest/.test(base)) {
return { id: "codegen.adapter-manifest", title: "generate_*adapter_manifest*", variant: "runtime", module: "adapter", pattern: "generate_<family>_adapter_manifest.py" };
}
// Generic: only group when at least three siblings share the stripped stem.
const stem = stripVariantTokens(base);
if (stem !== base && stem.length >= 4 && (stemCounts.get(stem) ?? 0) >= 3) {
return { id: `stem.${dir}.${stem}`, title: `${stem}_*`, variant: base.slice(stem.length).replace(/^[-_]/, ""), module: stem, pattern: `${stem}_<variant>.mjs` };
}
return null;
}
function pickRepresentative(members) {
const scored = members.map((member) => {
let score = 0;
if (member.purpose && member.purpose.source === BADGE.docstring) score += 10;
if (member.usage.length) score += 5;
if (member.role === "cli") score += 3;
return { member, score };
});
scored.sort((a, b) => b.score - a.score || a.member.name.length - b.member.name.length || (a.member.relPath < b.member.relPath ? -1 : 1));
return scored[0].member;
}
/* --- main --------------------------------------------------------------- */
export function extract({ files, directories, npmScripts, importedBy }) {
const stemCounts = new Map();
for (const file of files) {
const stem = stripVariantTokens(baseName(file.name));
if (stem !== baseName(file.name)) stemCounts.set(stem, (stemCounts.get(stem) ?? 0) + 1);
}
const records = files.map((file) => {
const categoryId = classify(file.relPath, file.name);
const role = detectRole(file, importedBy);
const purpose = extractPurpose(file);
const usage = extractUsage(file);
const env = extractEnv(file.head);
const npm = npmScripts.get(file.relPath) ?? [];
const family = familyOf(file.relPath, file.name, stemCounts);
return {
relPath: file.relPath,
name: file.name,
ext: file.ext,
bytes: file.bytes,
categoryId,
role,
purpose,
usage,
env,
npm,
family,
importedBy: importedBy.get(file.relPath) ?? 0,
};
});
// Purpose fallback chain: npm script > family template > filename.
for (const record of records) {
if (record.purpose) continue;
if (record.npm.length) {
record.purpose = { text: `npm 脚本 \`${record.npm[0]}\` 的入口;具体行为见源码。`, source: BADGE.npm };
continue;
}
if (record.family && VARIANT_PURPOSE[record.family.variant]) {
const moduleName = record.family.module ?? "";
record.purpose = { text: `${moduleName ? `\`${moduleName}\` 的` : ""}${VARIANT_PURPOSE[record.family.variant]}(由文件名推断,未在头部声明用途)`, source: BADGE.family };
continue;
}
if (record.role === "module" || record.role === "cli-module") {
record.purpose = { text: `库模块:被 ${record.importedBy} 个脚本导入,无独立命令行入口。`, source: BADGE.filename };
} else if (record.role === "data") {
record.purpose = { text: "数据文件:由其他脚本读取,不直接执行。", source: BADGE.filename };
} else {
const category = CATEGORY_BY_ID.get(record.categoryId);
record.purpose = { text: `未检测到头部说明;按命名归入「${category?.label ?? "其他"}」。请阅读源码确认。`, source: BADGE.filename };
}
}
// Usage fallback chain.
for (const record of records) {
if (record.usage.length) continue;
const p = record.relPath;
if (record.npm.length) {
record.usage = [`cd web && npm run ${record.npm[0]}`, `${record.ext === ".py" ? "python3" : "node"} ${p}`];
continue;
}
if (record.family && ["smoke", "gate", "chrome", "probe", "worker", "batch"].includes(record.family.variant)) {
const runner = record.ext === ".py" ? "python3" : "node";
record.usage = [`${runner} ${record.family.pattern}`.replace("<action>_<kind>", "<action>_<kind>").replace("<kind>", record.family.variant).replace("<surface>", "<surface>").replace("<target>", "<target>").replace("<op>", "<op>").replace("<family>", "<family>").replace("<variant>", record.family.variant)];
record.usageNote = "将占位符替换为展开列表中的成员名;参数未在头部声明。";
continue;
}
if (record.role === "module" || record.role === "cli-module") {
record.usage = [`import { … } from "${p.replace(/\.(mjs|js|ts)$/, ".mjs")}"`];
record.usageNote = "库用法:导入后调用其导出函数,无独立 CLI 入口。";
continue;
}
if (record.role === "data") {
record.usage = [];
record.usageNote = record.importedBy ? `数据文件:由 ${record.importedBy} 个脚本读取。` : "数据文件:不直接执行。";
continue;
}
const runner = record.ext === ".py" ? "python3" : record.ext === ".sh" ? "bash" : record.ext === ".json" ? null : "node";
record.usage = runner && record.role !== "unknown" ? [`${runner} ${p}`] : runner ? [`${runner} ${p}`] : [];
if (runner) record.usageNote = "参数未在源码头部声明;运行前请阅读文件头部或尝试 --help。";
else record.usageNote = "未在源码中声明用法。";
if (record.role === "unknown") record.usageNote = "未检测到 CLI 标记,也无导入者;可能是一次性脚本或被外部调用。";
}
// Family aggregation.
const groups = new Map();
for (const record of records) {
if (!record.family) continue;
if (!groups.has(record.family.id)) groups.set(record.family.id, []);
groups.get(record.family.id).push(record);
}
const families = [];
for (const [id, members] of groups) {
if (members.length < 2) {
for (const member of members) member.family = null;
continue;
}
const representative = pickRepresentative(members);
const env = new Set();
for (const member of members) for (const name of member.env) env.add(name);
families.push({
id,
title: members[0].family.title,
pattern: members[0].family.pattern,
variant: members[0].family.variant,
module: members[0].family.module,
count: members.length,
representative,
members: members.map((member) => member.relPath).sort(),
categoryId: representative.categoryId,
purpose: representative.purpose,
usage: representative.usage,
usageNote: representative.usageNote,
env: [...env].sort(),
npm: [...new Set(members.flatMap((member) => member.npm))],
role: members.every((member) => member.role === "data") ? "data" : "family",
});
}
families.sort((a, b) => (a.id < b.id ? -1 : 1));
const familyIds = new Set(families.map((family) => family.id));
for (const record of records) {
if (record.family && !familyIds.has(record.family.id)) record.family = null;
if (record.family) record.familyId = record.family.id;
delete record.family;
}
// Per-family bookkeeping is enough for the page: a member row links to its family.
const directoryRecords = directories.map((entry) => ({
relPath: entry.relPath,
name: entry.label,
categoryId: entry.category,
role: "directory",
purpose: { text: entry.note, source: BADGE.header },
usage: [],
usageNote: `目录型记录:共 ${entry.count} 个文件,逐项见展开列表。`,
env: [],
npm: [],
familyId: null,
members: entry.members,
count: entry.count,
importedBy: 0,
}));
const envUsage = new Map();
for (const record of [...records, ...families]) {
for (const name of record.env ?? []) {
if (!envUsage.has(name)) envUsage.set(name, { count: 0, samples: [] });
const entry = envUsage.get(name);
entry.count += record === undefined ? 0 : (record.count ?? 1);
if (entry.samples.length < 4) entry.samples.push(record.relPath ?? record.id);
}
}
const stats = {
files: files.length,
directories: directoryRecords.length,
families: families.length,
singles: records.filter((record) => !record.familyId).length,
rows: families.length + records.filter((record) => !record.familyId).length + directoryRecords.length,
withPurpose: records.filter((record) => record.purpose && record.purpose.source === BADGE.docstring).length,
withUsage: records.filter((record) => record.usage.length && !record.usageNote?.startsWith("参数未在")).length,
};
return { records, families, directories: directoryRecords, envUsage, stats, badges: BADGE };
}
export { ENV_DOCS, BADGE };