check-file-budgets.mjs
3.98 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
#!/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;
}