check-file-budgets.mjs 3.98 KB
#!/usr/bin/env node

import childProcess from "node:child_process";
import fs from "node:fs";
import path from "node:path";
import process from "node:process";

import { requireWorkspaceRoot } from "./workspace-root.mjs";

const repoRoot = requireWorkspaceRoot();
const configPath = path.join(repoRoot, "tools", "fitness", "file-budgets.json");
const config = JSON.parse(fs.readFileSync(configPath, "utf8"));
const ratchetMode = process.argv.includes("--ratchet");
const changedFiles = resolveChangedFiles().filter((file) => fs.existsSync(path.join(repoRoot, file)));

if (changedFiles.length === 0) {
	console.log("[file-budget] no changed files detected");
	process.exit(0);
}

const violations = [];

// 标准预算检查 + Ratchet 棘轮
for (const file of changedFiles) {
	const ext = path.extname(file);
	const defaultMax = config.defaults[ext];
	const hotspotMax = config.hotspots[file];
	if (defaultMax === undefined && hotspotMax === undefined) {
		continue;
	}

	const currentLines = countLines(file);
	const maxLimit = hotspotMax ?? defaultMax;
	const limitType = hotspotMax !== undefined ? "hotspot" : "budget";

	if (currentLines <= maxLimit) {
		// 文件在预算内,正常通过
		continue;
	}

	if (!ratchetMode) {
		// 非 Ratchet 模式:标准预算违规
		violations.push({ type: limitType, file, lines: currentLines, max: maxLimit });
		continue;
	}

	// Ratchet 模式:文件已超预算,用 HEAD 基线冻结,只允许缩小不允许膨胀
	const baselineLines = countLinesInGitHead(file);

	if (baselineLines === null) {
		// 新文件且超预算,标准违规
		violations.push({ type: limitType, file, lines: currentLines, max: maxLimit });
		continue;
	}

	if (currentLines > baselineLines) {
		// 比 HEAD 更大 → 棘轮膨胀违规
		violations.push({
			type: "ratchet",
			file,
			lines: currentLines,
			baseline: baselineLines,
			delta: currentLines - baselineLines,
		});
	} else if (currentLines === baselineLines) {
		// 与 HEAD 相等且超预算 → 冻结违规(要求缩小)
		violations.push({ type: limitType, file, lines: currentLines, max: maxLimit });
	}
	// currentLines < baselineLines → 在缩小,允许通过(鼓励精简)
}

if (violations.length > 0) {
	console.error("[file-budget] violated");
	for (const violation of violations) {
		if (violation.type === "ratchet") {
			console.error(`- Ratchet 膨胀: ${violation.file} 当前 ${violation.lines} 行,基线 ${violation.baseline} 行(+${violation.delta} 行)`);
		} else {
			const label = violation.type === "hotspot" ? "热点冻结" : "文件预算";
			console.error(`- ${label}: ${violation.file} 当前 ${violation.lines} 行,允许上限 ${violation.max} 行`);
		}
	}
	process.exit(1);
}

console.log(`[file-budget] passed${ratchetMode ? " (ratchet mode)" : ""}`);

function countLinesInGitHead(file) {
	const result = childProcess.spawnSync("git", ["show", `HEAD:${file}`], {
		cwd: repoRoot,
		encoding: "utf8",
	});
	if (result.status !== 0 || !result.stdout) {
		return null; // 文件不存在于 HEAD(新文件)
	}
	if (result.stdout.length === 0) {
		return 0;
	}
	return result.stdout.split(/\r?\n/).length;
}

function resolveChangedFiles() {
	const fromArgs = process.argv.slice(2).filter((arg) => arg && !arg.startsWith("--"));
	if (fromArgs.length > 0) {
		return normalize(fromArgs);
	}

	const combined = [
		...runGit("git diff --name-only"),
		...runGit("git diff --cached --name-only"),
		...runGit("git ls-files --others --exclude-standard"),
	];
	return normalize(combined);
}

function runGit(command) {
	const result = childProcess.spawnSync(command, {
		cwd: repoRoot,
		shell: true,
		encoding: "utf8",
	});
	if (result.status !== 0 || !result.stdout) {
		return [];
	}
	return result.stdout.split(/\r?\n/).filter(Boolean);
}

function normalize(files) {
	return [...new Set(files.map((file) => file.replaceAll("\\", "/")))];
}

function countLines(file) {
	const raw = fs.readFileSync(path.join(repoRoot, file), "utf8");
	if (raw.length === 0) {
		return 0;
	}
	return raw.split(/\r?\n/).length;
}