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

159 lines
5.3 KiB
JavaScript

/**
* Directory scan for tools/build-tools-manual.mjs.
*
* Reads only the first HEAD_BYTES of each source file: the manual documents
* tool Function/Location/Usage, which lives in headers and docstrings, and
* full reads of ~1600 files would be needless I/O.
*
* Never executes anything: several tools write into docs/current/ or append
* logs when invoked (tools/emcc-compat-bin/emcc does exactly that).
*/
import fs from "node:fs";
import path from "node:path";
import { HEAD_BYTES, READ_EXTS, SCAN_ROOTS, SKIP_DIRS, SKIP_FILE, DIRECTORY_SUMMARIES } from "./config.mjs";
function readHead(absPath, bytes) {
const fd = fs.openSync(absPath, "r");
try {
const size = Math.min(bytes, fs.fstatSync(fd).size);
const buffer = Buffer.alloc(size);
fs.readSync(fd, buffer, 0, size, 0);
return buffer.toString("utf8");
} finally {
fs.closeSync(fd);
}
}
function walk(root, relPath, recursive, out) {
const absDir = path.join(root, relPath);
let entries;
try {
entries = fs.readdirSync(absDir, { withFileTypes: true });
} catch {
return;
}
entries.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
for (const entry of entries) {
const rel = `${relPath}/${entry.name}`;
if (entry.isSymbolicLink()) continue;
if (entry.isDirectory()) {
if (!recursive || SKIP_DIRS.has(entry.name)) continue;
if (DIRECTORY_SUMMARIES.some((d) => d.relPath === rel)) continue;
walk(root, rel, recursive, out);
continue;
}
if (!entry.isFile()) continue;
if (SKIP_FILE.test(entry.name)) continue;
const ext = path.extname(entry.name).toLowerCase();
const abs = path.join(root, rel);
let bytes = 0;
try {
bytes = fs.statSync(abs).size;
} catch {
continue;
}
out.push({
relPath: rel,
name: entry.name,
ext,
bytes,
head: READ_EXTS.has(ext) ? readHead(abs, HEAD_BYTES) : "",
});
}
}
function countDirectoryFiles(root, relPath) {
const names = [];
const stack = [relPath];
while (stack.length) {
const current = stack.pop();
let entries = [];
try {
entries = fs.readdirSync(path.join(root, current), { withFileTypes: true });
} catch {
continue;
}
for (const entry of entries) {
if (entry.isSymbolicLink()) continue;
if (entry.isDirectory()) {
if (!SKIP_DIRS.has(entry.name)) stack.push(`${current}/${entry.name}`);
continue;
}
if (SKIP_FILE.test(entry.name)) continue;
names.push(`${current}/${entry.name}`);
}
}
names.sort();
return names;
}
/** Map npm script name -> the tool paths its command mentions. */
function readNpmScripts(root) {
const scripts = new Map(); // relPath -> [scriptName]
const files = ["package.json", "web/package.json"];
for (const rel of files) {
let pkg;
try {
pkg = JSON.parse(fs.readFileSync(path.join(root, rel), "utf8"));
} catch {
continue;
}
for (const [name, command] of Object.entries(pkg.scripts ?? {})) {
const matches = String(command).matchAll(/(?:^|[\s"'=])((?:\.\.\/)?(?:tools|web\/tools)\/[\w./-]+\.(?:mjs|js|ts|py|sh))/g);
for (const match of matches) {
let tool = match[1].replace(/^\.\.\//, "");
if (!tool.startsWith("tools/")) tool = `tools/${tool}`;
if (!scripts.has(tool)) scripts.set(tool, []);
const list = scripts.get(tool);
if (!list.includes(name)) list.push(name);
}
}
}
return scripts;
}
/**
* Build a reverse-import map: module path -> number of files importing it.
* Only relative ESM imports and CommonJS require() are traced; Python local
* imports are left alone (CLI markers are a better signal there).
*/
function buildImportGraph(files) {
const byRel = new Map(files.map((file) => [file.relPath, file]));
const importedBy = new Map();
for (const file of files) {
if (!file.head || !/\.(mjs|js|ts|tsx)$/.test(file.ext)) continue;
const dir = path.posix.dirname(file.relPath);
const specs = new Set();
for (const match of file.head.matchAll(/(?:from\s+|import\s*\(?\s*|require\s*\(\s*)["'](\.{1,2}\/[^"']+)["']/g)) {
specs.add(match[1]);
}
for (const spec of specs) {
const resolved = path.posix.normalize(path.posix.join(dir, spec));
for (const candidate of [resolved, `${resolved}.mjs`, `${resolved}.js`, `${resolved}.ts`, `${resolved}/index.mjs`]) {
if (byRel.has(candidate)) {
importedBy.set(candidate, (importedBy.get(candidate) ?? 0) + 1);
break;
}
}
}
}
return importedBy;
}
export function scan(root) {
const files = [];
for (const scanRoot of SCAN_ROOTS) walk(root, scanRoot.relPath, scanRoot.recursive, files);
// A file can be reached twice (web/tools top level + manual/ recursion).
const unique = [...new Map(files.map((file) => [file.relPath, file])).values()];
unique.sort((a, b) => (a.relPath < b.relPath ? -1 : a.relPath > b.relPath ? 1 : 0));
const directories = DIRECTORY_SUMMARIES.map((entry) => {
const members = countDirectoryFiles(root, entry.relPath);
return { ...entry, members, count: members.length };
}).filter((entry) => entry.count > 0);
const npmScripts = readNpmScripts(root);
const importedBy = buildImportGraph(unique);
return { files: unique, directories, npmScripts, importedBy };
}