import { execFileSync } from "node:child_process"; import { lstatSync, readFileSync, readdirSync } from "node:fs"; import { posix, resolve } from "node:path"; const isReadme = (name: string) => /^readme(?:\..*)?$/i.test(name); const scriptPattern = /\.(?:[cm]?js|jsx|tsx?|sh|bash|py|ps1)$/; const testPattern = /^(.*)\.test\.(?:[cm]?js|jsx|tsx?)$/; /** 只合并同目录内唯一的同名脚本/测试对,资源文件和独立测试各计 1。 */ export function fileUnits(names: string[]): string[][] { const files = [...new Set(names)].filter(name => !isReadme(name)).sort(); const sources = new Map(); const tests = new Map(); for (const name of files) { const test = name.match(testPattern); const key = test?.[1] ?? (scriptPattern.test(name) ? name.replace(scriptPattern, "") : undefined); if (key === undefined) continue; const target = test ? tests : sources; target.set(key, [...(target.get(key) ?? []), name]); } const paired = new Map(); for (const [stem, source] of sources) { const test = tests.get(stem); if (source.length === 1 && test?.length === 1) paired.set(source[0]!, test[0]!); } const consumed = new Set(paired.values()); return files.filter(name => !consumed.has(name)).map(name => paired.has(name) ? [name, paired.get(name)!] : [name]); } export interface DirectoryResult { directory: string; expectedReadme: string; fileUnits: string[][]; directoryWeight: number; weight: number; required: boolean; status: "ok" | "not-required" | "missing" | "misnamed" | "empty" | "invalid-file"; foundReadmes: string[]; } export function checkReadmes(directory: string, threshold = 5) { if (!Number.isSafeInteger(threshold) || threshold < 0) throw new Error("threshold 必须为非负安全整数"); const git = (args: string[]) => execFileSync("git", ["-C", resolve(directory), ...args], { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }); const root = git(["rev-parse", "--show-toplevel"]).trim(); const tracked = execFileSync("git", ["-C", root, "ls-files", "--cached", "-z"], { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }); const tree = new Map; directories: Set }>(); const ensure = (path: string) => { if (!tree.has(path)) tree.set(path, { files: new Set(), directories: new Set() }); return tree.get(path)!; }; ensure("."); for (const path of new Set(tracked.split("\0").filter(Boolean))) { let stat; try { stat = lstatSync(resolve(root, path)); } catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") continue; throw error; } let parent = posix.dirname(path); // 子模块只计为直接子目录;不进入另一个 Git 仓库。符号链接按文件计,不跟随。 if (stat.isDirectory()) ensure(parent).directories.add(posix.basename(path)); else ensure(parent).files.add(posix.basename(path)); while (parent !== ".") { const ancestor = posix.dirname(parent); ensure(ancestor).directories.add(posix.basename(parent)); parent = ancestor; } } const results: DirectoryResult[] = [...tree.entries()].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([path, members]) => { const units = fileUnits([...members.files]); const weight = units.length + members.directories.size; const required = path === "." || weight > threshold; const expectedReadme = path === "." ? "README.md" : `README.${posix.basename(path)}.md`; const result: DirectoryResult = { directory: path, expectedReadme, fileUnits: units, directoryWeight: members.directories.size, weight, required, status: "not-required", foundReadmes: [] }; if (!required) return result; const absolute = resolve(root, path); // 必须比较目录条目的真实大小写,不能依赖 macOS 的大小写不敏感路径查询。 result.foundReadmes = readdirSync(absolute).filter(isReadme).sort(); if (!result.foundReadmes.includes(expectedReadme)) { result.status = result.foundReadmes.length ? "misnamed" : "missing"; } else if (!lstatSync(resolve(absolute, expectedReadme)).isFile()) { result.status = "invalid-file"; } else { result.status = readFileSync(resolve(absolute, expectedReadme), "utf8").trim() ? "ok" : "empty"; } return result; }); const required = results.filter(result => result.required); return { root, threshold, directories: results.length, required: required.length, failed: required.filter(result => result.status !== "ok").length, results }; } export function main(args: string[]): number { const json = args.includes("--json"); try { let root = resolve(import.meta.dir, "../.."); let threshold = 5; for (let i = 0; i < args.length; i++) { const arg = args[i]!; if (arg === "--json") continue; if (arg === "--help" || arg === "-h") { console.log("用法:bun run check:readme [--threshold=5] [--root=] [--json]\n根目录始终检查;其余目录的直接文件单位 + 直接子目录数 > threshold 时要求 README.{目录名}.md。\n只统计 Git 已跟踪且工作区仍存在的成员;同名脚本与唯一的 .test.* 测试文件合计 1。只读检查。"); return 0; } const match = arg.match(/^--(threshold|root)(?:=(.*))?$/); if (!match) throw new Error(`未知参数:${arg}`); const value = match[2] ?? args[++i]; if (!value || value.startsWith("--")) throw new Error(`参数缺少值:${arg}`); if (match[1] === "root") root = resolve(value); else { if (!/^\d+$/.test(value)) throw new Error("threshold 必须为非负安全整数"); threshold = Number(value); } } const report = checkReadmes(root, threshold); if (json) console.log(JSON.stringify(report, null, 2)); else { const labels = { missing: "缺失", misnamed: "错名", empty: "空文档", "invalid-file": "不是普通文件", ok: "通过", "not-required": "未达阈值" }; for (const result of report.results.filter(item => item.required && item.status !== "ok")) { console.log(`${labels[result.status]} ${result.directory}/ 权重 ${result.weight},预期 ${result.expectedReadme}${result.foundReadmes.length ? `,发现 ${result.foundReadmes.join("、")}` : ""}`); } console.log(`检查 ${report.directories} 个目录;要求 README ${report.required} 个,通过 ${report.required - report.failed} 个,失败 ${report.failed} 个;其余 ${report.directories - report.required} 个未达阈值。`); } return report.failed ? 1 : 0; } catch (error) { const message = error instanceof Error ? error.message : String(error); if (json) console.log(JSON.stringify({ error: message })); else console.error(`README 校验失败:${message}`); return 2; } } if (import.meta.main) process.exitCode = main(process.argv.slice(2));