crap-ts 0.2.0 → 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CONTRIBUTING.md +1 -0
- package/README.md +329 -67
- package/package.json +3 -15
- package/src/cli.js +105 -105
- package/src/crap-analysis.d.ts +40 -19
- package/src/crap-analysis.js +485 -200
- package/src/crap-runner.d.ts +15 -1
- package/src/crap-runner.js +415 -76
- package/src/crap-score.d.ts +4 -29
- package/src/crap-score.js +0 -51
- package/src/index.d.ts +2 -10
- package/src/index.js +1 -7
package/src/crap-runner.d.ts
CHANGED
|
@@ -1,9 +1,19 @@
|
|
|
1
1
|
export interface CrapAuditOptions {
|
|
2
2
|
all?: boolean;
|
|
3
|
+
/** Accept listed coverage JSON files with no source entries. Defaults to false. */
|
|
4
|
+
allowEmptyCoverage?: boolean;
|
|
3
5
|
coverageCommand?: string;
|
|
4
|
-
|
|
6
|
+
/** Istanbul `coverage-final.json` files, merged by source position. Defaults to `["coverage/unit/coverage-final.json"]`. */
|
|
7
|
+
coveragePaths?: string[];
|
|
5
8
|
cwd?: string;
|
|
9
|
+
/** Skip files matching these path substrings or root-anchored `dir/**` patterns. */
|
|
10
|
+
excludes?: string[];
|
|
11
|
+
/** Fail on functions with ignored evidence and require coverage entries for executable files with an ignore-file comment. Defaults to false. */
|
|
12
|
+
failOnIgnored?: boolean;
|
|
13
|
+
/** Analyze files matching these path substrings or root-anchored `dir/**` patterns. */
|
|
6
14
|
includes?: string[];
|
|
15
|
+
/** Print the JSON report (schema version 1) to stdout instead of the text report. */
|
|
16
|
+
json?: boolean;
|
|
7
17
|
limit?: number;
|
|
8
18
|
maxScore?: number;
|
|
9
19
|
minLines?: number;
|
|
@@ -13,4 +23,8 @@ export interface CrapAuditOptions {
|
|
|
13
23
|
warnScore?: number;
|
|
14
24
|
}
|
|
15
25
|
|
|
26
|
+
/**
|
|
27
|
+
* Resolves to the process exit code: 0 pass, 1 gate failure, failed coverage command or missing coverage file, 2 usage error (including non-finite numeric options).
|
|
28
|
+
* Rejects when coverage or source input is malformed or stale, or when a coverage file is empty and `allowEmptyCoverage` is false.
|
|
29
|
+
*/
|
|
16
30
|
export function runCrapAudit(options?: CrapAuditOptions): Promise<number>;
|
package/src/crap-runner.js
CHANGED
|
@@ -1,20 +1,25 @@
|
|
|
1
1
|
import { spawnSync } from "node:child_process";
|
|
2
|
-
import { existsSync, readFileSync } from "node:fs";
|
|
3
|
-
import { isAbsolute, relative, resolve } from "node:path";
|
|
4
|
-
|
|
5
|
-
import {
|
|
6
|
-
analyzeFileRisk,
|
|
7
|
-
extractCoverageFunctions,
|
|
8
|
-
formatRiskLine,
|
|
9
|
-
} from "./crap-analysis.js";
|
|
2
|
+
import { existsSync, readdirSync, readFileSync, realpathSync } from "node:fs";
|
|
3
|
+
import { isAbsolute, join, relative, resolve } from "node:path";
|
|
4
|
+
|
|
5
|
+
import { analyzeSource } from "./crap-analysis.js";
|
|
10
6
|
import { normalizePath } from "./path-utils.js";
|
|
11
7
|
|
|
8
|
+
const reportSchemaVersion = 1;
|
|
9
|
+
|
|
10
|
+
const sourceFilePattern = /\.[cm]?tsx?$/;
|
|
11
|
+
const declarationFilePattern = /\.d\.[cm]?ts$/;
|
|
12
|
+
|
|
12
13
|
export async function runCrapAudit({
|
|
13
14
|
all = false,
|
|
15
|
+
allowEmptyCoverage = false,
|
|
14
16
|
coverageCommand,
|
|
15
|
-
|
|
17
|
+
coveragePaths = ["coverage/unit/coverage-final.json"],
|
|
16
18
|
cwd = process.cwd(),
|
|
19
|
+
excludes = [],
|
|
20
|
+
failOnIgnored = false,
|
|
17
21
|
includes = [],
|
|
22
|
+
json = false,
|
|
18
23
|
limit = 20,
|
|
19
24
|
maxScore = 30,
|
|
20
25
|
minLines = 10,
|
|
@@ -22,6 +27,18 @@ export async function runCrapAudit({
|
|
|
22
27
|
skipCoverage = false,
|
|
23
28
|
warnScore,
|
|
24
29
|
} = {}) {
|
|
30
|
+
for (const [label, value] of [
|
|
31
|
+
["max", maxScore],
|
|
32
|
+
["warn", warnScore ?? 0],
|
|
33
|
+
["minLines", minLines],
|
|
34
|
+
["limit", limit],
|
|
35
|
+
]) {
|
|
36
|
+
if (!Number.isFinite(value)) {
|
|
37
|
+
console.error(`CRAP ${label} must be a finite number.`);
|
|
38
|
+
return 2;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
25
42
|
if (warnScore !== undefined && warnScore > maxScore) {
|
|
26
43
|
console.error(
|
|
27
44
|
`CRAP warn (${warnScore}) must not exceed max (${maxScore}).`,
|
|
@@ -29,101 +46,135 @@ export async function runCrapAudit({
|
|
|
29
46
|
return 2;
|
|
30
47
|
}
|
|
31
48
|
|
|
49
|
+
const unsupportedPattern = [...includes, ...excludes].find((pattern) =>
|
|
50
|
+
normalizePath(pattern)
|
|
51
|
+
.replace(/\/\*\*$/, "")
|
|
52
|
+
.includes("*"),
|
|
53
|
+
);
|
|
54
|
+
if (unsupportedPattern !== undefined) {
|
|
55
|
+
console.error(
|
|
56
|
+
`Unsupported path pattern ${JSON.stringify(unsupportedPattern)}. Use a substring or a directory pattern such as src/**.`,
|
|
57
|
+
);
|
|
58
|
+
return 2;
|
|
59
|
+
}
|
|
60
|
+
|
|
32
61
|
if (!skipCoverage && coverageCommand) {
|
|
33
62
|
const result = spawnSync(coverageCommand, {
|
|
34
63
|
cwd,
|
|
35
64
|
shell: true,
|
|
36
|
-
|
|
65
|
+
// Keep stdout clean for the JSON report.
|
|
66
|
+
stdio: ["inherit", json ? 2 : "inherit", "inherit"],
|
|
37
67
|
});
|
|
38
68
|
|
|
39
69
|
if (result.status !== 0) {
|
|
40
|
-
|
|
70
|
+
console.error(
|
|
71
|
+
result.status === null
|
|
72
|
+
? `Coverage command failed: ${result.error?.message ?? `killed by ${result.signal}`}`
|
|
73
|
+
: `Coverage command failed with exit code ${result.status}.`,
|
|
74
|
+
);
|
|
75
|
+
return 1;
|
|
41
76
|
}
|
|
42
77
|
}
|
|
43
78
|
|
|
44
|
-
const
|
|
79
|
+
const resolvedCoveragePaths = coveragePaths.map((path) => resolve(cwd, path));
|
|
80
|
+
const missingCoveragePath = resolvedCoveragePaths.find(
|
|
81
|
+
(path) => !existsSync(path),
|
|
82
|
+
);
|
|
45
83
|
|
|
46
|
-
if (
|
|
47
|
-
console.error(`Missing coverage JSON: ${
|
|
84
|
+
if (missingCoveragePath) {
|
|
85
|
+
console.error(`Missing coverage JSON: ${missingCoveragePath}`);
|
|
48
86
|
console.error(
|
|
49
87
|
"Run coverage first, pass --coverage-file, or use a valid --coverage-command.",
|
|
50
88
|
);
|
|
51
89
|
return 1;
|
|
52
90
|
}
|
|
53
91
|
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
const
|
|
92
|
+
// Coverage tools report real paths; compare everything in the file
|
|
93
|
+
// system's canonical form (`.native` also canonicalises letter case).
|
|
94
|
+
const root = realpathSync.native(cwd);
|
|
95
|
+
const coverageByFile = readCoverageFiles(
|
|
96
|
+
resolvedCoveragePaths,
|
|
97
|
+
root,
|
|
98
|
+
allowEmptyCoverage,
|
|
99
|
+
);
|
|
100
|
+
const isSelected = (path) => {
|
|
101
|
+
const relativePath = relative(root, path);
|
|
102
|
+
return (
|
|
103
|
+
matchesAny(relativePath, includes, true) &&
|
|
104
|
+
!matchesAny(relativePath, excludes, false)
|
|
105
|
+
);
|
|
106
|
+
};
|
|
107
|
+
const sourcePaths = new Set(listSourceFiles(root).filter(isSelected));
|
|
57
108
|
|
|
58
|
-
for (const
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
] of coverageByFile.entries()) {
|
|
62
|
-
if (!shouldIncludePath(coverageFilePath, includes)) {
|
|
63
|
-
continue;
|
|
109
|
+
for (const path of coverageByFile.keys()) {
|
|
110
|
+
if (existsSync(path) && isSelected(path)) {
|
|
111
|
+
sourcePaths.add(path);
|
|
64
112
|
}
|
|
113
|
+
}
|
|
65
114
|
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
115
|
+
const functions = [];
|
|
116
|
+
const missingFiles = [];
|
|
117
|
+
|
|
118
|
+
for (const sourceFilePath of [...sourcePaths].sort()) {
|
|
119
|
+
const filePath = normalizePath(relative(root, sourceFilePath));
|
|
120
|
+
const coverage = coverageByFile.get(sourceFilePath);
|
|
121
|
+
const analysis = await analyzeSource({
|
|
122
|
+
coverage,
|
|
123
|
+
failOnIgnored,
|
|
124
|
+
filePath,
|
|
125
|
+
sourceFilePath,
|
|
126
|
+
sourceText: readFileSync(sourceFilePath, "utf8"),
|
|
127
|
+
});
|
|
69
128
|
|
|
70
|
-
if (!
|
|
71
|
-
|
|
129
|
+
if (!coverage && analysis.executable) {
|
|
130
|
+
missingFiles.push(filePath);
|
|
72
131
|
}
|
|
73
132
|
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
risks.push(
|
|
78
|
-
...(await analyzeFileRisk({
|
|
79
|
-
coverageFunctions,
|
|
80
|
-
filePath: relativeFilePath,
|
|
81
|
-
minLines,
|
|
82
|
-
sourceFilePath,
|
|
83
|
-
sourceText,
|
|
84
|
-
})),
|
|
133
|
+
functions.push(
|
|
134
|
+
...analysis.functions.filter((risk) => risk.lineCount >= minLines),
|
|
85
135
|
);
|
|
86
136
|
}
|
|
87
137
|
|
|
88
|
-
const
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
);
|
|
98
|
-
const warningSummary =
|
|
99
|
-
warnScore === undefined
|
|
100
|
-
? ""
|
|
101
|
-
: `, ${warningRisks.length} above ${warnScore} (warn)`;
|
|
138
|
+
const report = buildReport({
|
|
139
|
+
failOnIgnored,
|
|
140
|
+
files: sourcePaths.size,
|
|
141
|
+
functions,
|
|
142
|
+
maxScore,
|
|
143
|
+
minLines,
|
|
144
|
+
missingFiles,
|
|
145
|
+
warnScore,
|
|
146
|
+
});
|
|
102
147
|
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
148
|
+
if (json) {
|
|
149
|
+
console.log(JSON.stringify(report, null, 2));
|
|
150
|
+
} else {
|
|
151
|
+
printTextReport({ all, limit, maxScore, report, warnScore });
|
|
152
|
+
}
|
|
107
153
|
|
|
108
|
-
const
|
|
154
|
+
const { summary } = report;
|
|
109
155
|
|
|
110
|
-
|
|
111
|
-
console.
|
|
112
|
-
|
|
156
|
+
if (summary.warning > 0) {
|
|
157
|
+
console.error("");
|
|
158
|
+
console.error(
|
|
159
|
+
`CRAP warning: ${summary.warning} function(s) above ${warnScore}. Add coverage or simplify them before they cross ${maxScore}.`,
|
|
113
160
|
);
|
|
114
161
|
}
|
|
115
162
|
|
|
116
|
-
if (
|
|
163
|
+
if (missingFiles.length > 0) {
|
|
117
164
|
console.error("");
|
|
118
165
|
console.error(
|
|
119
|
-
`
|
|
166
|
+
`Missing coverage evidence for ${missingFiles.length} source file(s):`,
|
|
120
167
|
);
|
|
168
|
+
|
|
169
|
+
for (const filePath of missingFiles) {
|
|
170
|
+
console.error(` ${filePath}`);
|
|
171
|
+
}
|
|
121
172
|
}
|
|
122
173
|
|
|
123
|
-
if (
|
|
174
|
+
if (!summary.passed && !reportOnly) {
|
|
124
175
|
console.error("");
|
|
125
176
|
console.error(
|
|
126
|
-
"CRAP check failed. Use --report-only while calibrating, or lower complexity / add coverage for the listed functions.",
|
|
177
|
+
"CRAP check failed. Use --report-only while calibrating, or lower complexity / add coverage for the listed functions and files.",
|
|
127
178
|
);
|
|
128
179
|
return 1;
|
|
129
180
|
}
|
|
@@ -131,26 +182,314 @@ export async function runCrapAudit({
|
|
|
131
182
|
return 0;
|
|
132
183
|
}
|
|
133
184
|
|
|
134
|
-
function
|
|
135
|
-
|
|
136
|
-
|
|
185
|
+
function buildReport({
|
|
186
|
+
failOnIgnored,
|
|
187
|
+
files,
|
|
188
|
+
functions,
|
|
189
|
+
maxScore,
|
|
190
|
+
minLines,
|
|
191
|
+
missingFiles,
|
|
192
|
+
warnScore,
|
|
193
|
+
}) {
|
|
194
|
+
const rows = functions
|
|
195
|
+
.sort(
|
|
196
|
+
(left, right) =>
|
|
197
|
+
// Keep ignored scores below rows that use coverage to score the gate.
|
|
198
|
+
Number(left.evidence === "ignored") -
|
|
199
|
+
Number(right.evidence === "ignored") ||
|
|
200
|
+
right.crapScore - left.crapScore ||
|
|
201
|
+
left.filePath.localeCompare(right.filePath) ||
|
|
202
|
+
left.startLine - right.startLine ||
|
|
203
|
+
left.startColumn - right.startColumn,
|
|
204
|
+
)
|
|
205
|
+
.map((risk) => ({
|
|
206
|
+
file: risk.filePath,
|
|
207
|
+
name: risk.name,
|
|
208
|
+
line: risk.startLine,
|
|
209
|
+
column: risk.startColumn,
|
|
210
|
+
endLine: risk.endLine,
|
|
211
|
+
lines: risk.lineCount,
|
|
212
|
+
complexity: risk.complexity,
|
|
213
|
+
coverage: risk.coveragePercent,
|
|
214
|
+
statements: risk.statements,
|
|
215
|
+
coveredStatements: risk.coveredStatements,
|
|
216
|
+
evidence: risk.evidence,
|
|
217
|
+
crap: risk.crapScore,
|
|
218
|
+
level: getRiskLevel(risk, { failOnIgnored, maxScore, warnScore }),
|
|
219
|
+
}));
|
|
220
|
+
const count = (predicate) => rows.filter(predicate).length;
|
|
221
|
+
const summary = {
|
|
222
|
+
files,
|
|
223
|
+
functions: rows.length,
|
|
224
|
+
aboveMax: count((row) => row.evidence !== "ignored" && row.crap > maxScore),
|
|
225
|
+
warning: count((row) => row.level === "warn"),
|
|
226
|
+
missingEvidence: count((row) => row.evidence === "missing"),
|
|
227
|
+
ignored: count((row) => row.evidence === "ignored"),
|
|
228
|
+
missingFiles: missingFiles.length,
|
|
229
|
+
};
|
|
230
|
+
|
|
231
|
+
return {
|
|
232
|
+
schemaVersion: reportSchemaVersion,
|
|
233
|
+
thresholds: { max: maxScore, warn: warnScore ?? null, minLines },
|
|
234
|
+
summary: {
|
|
235
|
+
...summary,
|
|
236
|
+
passed:
|
|
237
|
+
summary.aboveMax === 0 &&
|
|
238
|
+
summary.missingEvidence === 0 &&
|
|
239
|
+
summary.missingFiles === 0 &&
|
|
240
|
+
(!failOnIgnored || summary.ignored === 0),
|
|
241
|
+
},
|
|
242
|
+
functions: rows,
|
|
243
|
+
missingFiles,
|
|
244
|
+
};
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
function printTextReport({ all, limit, maxScore, report, warnScore }) {
|
|
248
|
+
const { functions, summary } = report;
|
|
249
|
+
const warningSummary =
|
|
250
|
+
warnScore === undefined
|
|
251
|
+
? ""
|
|
252
|
+
: `, ${summary.warning} above ${warnScore} (warn)`;
|
|
253
|
+
const missingSummary =
|
|
254
|
+
summary.missingEvidence === 0
|
|
255
|
+
? ""
|
|
256
|
+
: `, ${summary.missingEvidence} without coverage evidence`;
|
|
257
|
+
const ignoredSummary =
|
|
258
|
+
summary.ignored === 0 ? "" : `, ${summary.ignored} ignored by coverage`;
|
|
259
|
+
|
|
260
|
+
console.log();
|
|
261
|
+
console.log(
|
|
262
|
+
`CRAP report: ${summary.functions} functions checked, ${summary.aboveMax} above ${maxScore}${warningSummary}${missingSummary}${ignoredSummary}.`,
|
|
263
|
+
);
|
|
264
|
+
|
|
265
|
+
const visibleRows = all ? functions : functions.slice(0, limit);
|
|
266
|
+
for (const row of visibleRows) {
|
|
267
|
+
console.log(formatReportRow(row));
|
|
268
|
+
}
|
|
269
|
+
for (const row of functions.slice(visibleRows.length)) {
|
|
270
|
+
if (row.evidence === "ignored" && row.level === "fail") {
|
|
271
|
+
console.log(formatReportRow(row));
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
const rowTags = { fail: "FAIL", ignored: "SKIP", ok: " ok", warn: "WARN" };
|
|
277
|
+
|
|
278
|
+
function formatReportRow(row) {
|
|
279
|
+
return [
|
|
280
|
+
`${rowTags[row.level]} ${row.file}:${row.line}`,
|
|
281
|
+
row.name,
|
|
282
|
+
`CRAP ${row.crap.toFixed(1)}`,
|
|
283
|
+
`complexity ${row.complexity}`,
|
|
284
|
+
row.evidence === "missing" || row.evidence === "ignored"
|
|
285
|
+
? `coverage ${row.evidence}`
|
|
286
|
+
: `coverage ${row.coverage.toFixed(0)}%`,
|
|
287
|
+
`${row.lines} lines`,
|
|
288
|
+
].join(" | ");
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
function getRiskLevel(risk, { failOnIgnored, maxScore, warnScore }) {
|
|
292
|
+
if (risk.evidence === "ignored") {
|
|
293
|
+
return failOnIgnored ? "fail" : "ignored";
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
if (risk.crapScore > maxScore || risk.evidence === "missing") {
|
|
297
|
+
return "fail";
|
|
137
298
|
}
|
|
138
299
|
|
|
139
300
|
if (warnScore !== undefined && risk.crapScore > warnScore) {
|
|
140
|
-
return "
|
|
301
|
+
return "warn";
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
return "ok";
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
function readCoverageFiles(coveragePaths, root, allowEmptyCoverage) {
|
|
308
|
+
const coverageByFile = new Map();
|
|
309
|
+
|
|
310
|
+
for (const coveragePath of coveragePaths) {
|
|
311
|
+
const coverageJson = parseCoverageJson(coveragePath);
|
|
312
|
+
assertObject(coverageJson, coveragePath);
|
|
313
|
+
const entries = Object.entries(coverageJson);
|
|
314
|
+
|
|
315
|
+
if (!allowEmptyCoverage && entries.length === 0) {
|
|
316
|
+
throw new Error(`Empty coverage JSON: ${coveragePath}`);
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
for (const [key, entry] of entries) {
|
|
320
|
+
const label = `${coveragePath} (${key})`;
|
|
321
|
+
validateFileCoverage(entry, label);
|
|
322
|
+
|
|
323
|
+
const resolvedKey = isAbsolute(key) ? key : resolve(root, key);
|
|
324
|
+
const sourcePath = existsSync(resolvedKey)
|
|
325
|
+
? realpathSync.native(resolvedKey)
|
|
326
|
+
: resolvedKey;
|
|
327
|
+
coverageByFile.set(
|
|
328
|
+
sourcePath,
|
|
329
|
+
mergeFileCoverage(
|
|
330
|
+
coverageByFile.get(sourcePath) ?? emptyCoverage(),
|
|
331
|
+
entry,
|
|
332
|
+
),
|
|
333
|
+
);
|
|
334
|
+
}
|
|
141
335
|
}
|
|
142
336
|
|
|
143
|
-
return
|
|
337
|
+
return coverageByFile;
|
|
144
338
|
}
|
|
145
339
|
|
|
146
|
-
function
|
|
147
|
-
|
|
148
|
-
return
|
|
340
|
+
function parseCoverageJson(coveragePath) {
|
|
341
|
+
try {
|
|
342
|
+
return JSON.parse(readFileSync(coveragePath, "utf8"));
|
|
343
|
+
} catch (error) {
|
|
344
|
+
throw new Error(`Invalid coverage JSON ${coveragePath}: ${error.message}`, {
|
|
345
|
+
cause: error,
|
|
346
|
+
});
|
|
149
347
|
}
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
// Merge by original source position, never by counter id: separate runs
|
|
351
|
+
// number their counters independently.
|
|
352
|
+
function mergeFileCoverage(target, entry) {
|
|
353
|
+
mergeCounters(
|
|
354
|
+
target.statementMap,
|
|
355
|
+
target.s,
|
|
356
|
+
entry.statementMap,
|
|
357
|
+
entry.s,
|
|
358
|
+
(location) => locationKey(location),
|
|
359
|
+
);
|
|
360
|
+
mergeCounters(target.fnMap, target.f, entry.fnMap, entry.f, (metadata) =>
|
|
361
|
+
locationKey(metadata.loc),
|
|
362
|
+
);
|
|
150
363
|
|
|
151
|
-
|
|
364
|
+
return target;
|
|
365
|
+
}
|
|
152
366
|
|
|
153
|
-
|
|
154
|
-
|
|
367
|
+
function mergeCounters(targetMap, targetCounts, map, counts, getKey) {
|
|
368
|
+
const idsByKey = new Map(
|
|
369
|
+
Object.entries(targetMap).map(([id, value]) => [getKey(value), id]),
|
|
155
370
|
);
|
|
371
|
+
|
|
372
|
+
for (const [id, value] of Object.entries(map)) {
|
|
373
|
+
const key = getKey(value);
|
|
374
|
+
const existingId = idsByKey.get(key);
|
|
375
|
+
|
|
376
|
+
if (existingId === undefined) {
|
|
377
|
+
const newId = String(idsByKey.size);
|
|
378
|
+
idsByKey.set(key, newId);
|
|
379
|
+
targetMap[newId] = value;
|
|
380
|
+
targetCounts[newId] = counts[id];
|
|
381
|
+
} else {
|
|
382
|
+
targetCounts[existingId] += counts[id];
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
function emptyCoverage() {
|
|
388
|
+
return { f: {}, fnMap: {}, s: {}, statementMap: {} };
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
function locationKey({ end, start }) {
|
|
392
|
+
return `${start.line}:${start.column}-${end.line}:${end.column}`;
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
function validateFileCoverage(entry, label) {
|
|
396
|
+
assertObject(entry, label);
|
|
397
|
+
|
|
398
|
+
for (const key of ["statementMap", "s", "fnMap", "f"]) {
|
|
399
|
+
assertObject(entry[key], `${label} ${key}`);
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
for (const [map, counts, name] of [
|
|
403
|
+
[entry.statementMap, entry.s, "statement"],
|
|
404
|
+
[entry.fnMap, entry.f, "function"],
|
|
405
|
+
]) {
|
|
406
|
+
for (const [id, value] of Object.entries(map)) {
|
|
407
|
+
assertRange(
|
|
408
|
+
name === "function" ? value?.loc : value,
|
|
409
|
+
`${label} ${name} ${id}`,
|
|
410
|
+
);
|
|
411
|
+
|
|
412
|
+
if (!Number.isSafeInteger(counts[id]) || counts[id] < 0) {
|
|
413
|
+
throw new Error(`Invalid coverage counter: ${label} ${name} ${id}`);
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
function assertObject(value, label) {
|
|
420
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
421
|
+
throw new Error(`Invalid coverage data: ${label}`);
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
function assertRange(range, label) {
|
|
426
|
+
assertObject(range, label);
|
|
427
|
+
assertObject(range.start, label);
|
|
428
|
+
assertObject(range.end, label);
|
|
429
|
+
|
|
430
|
+
const { end, start } = range;
|
|
431
|
+
// Source-mapped Istanbul data serializes an end-of-line column as null.
|
|
432
|
+
const validEndColumn =
|
|
433
|
+
end.column === null || (Number.isInteger(end.column) && end.column >= 0);
|
|
434
|
+
|
|
435
|
+
if (
|
|
436
|
+
!Number.isInteger(start.line) ||
|
|
437
|
+
start.line < 1 ||
|
|
438
|
+
!Number.isInteger(start.column) ||
|
|
439
|
+
start.column < 0 ||
|
|
440
|
+
!Number.isInteger(end.line) ||
|
|
441
|
+
!validEndColumn ||
|
|
442
|
+
// A null end column means end of line, which never precedes the start.
|
|
443
|
+
comparePositions(end, start, Number.POSITIVE_INFINITY) < 0
|
|
444
|
+
) {
|
|
445
|
+
throw new Error(`Invalid coverage position: ${label}`);
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
function comparePositions(left, right, nullColumn) {
|
|
450
|
+
return (
|
|
451
|
+
left.line - right.line ||
|
|
452
|
+
(left.column ?? nullColumn) - (right.column ?? nullColumn)
|
|
453
|
+
);
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
function listSourceFiles(directory) {
|
|
457
|
+
return readdirSync(directory, { withFileTypes: true }).flatMap((entry) => {
|
|
458
|
+
const path = join(directory, entry.name);
|
|
459
|
+
|
|
460
|
+
if (entry.isDirectory()) {
|
|
461
|
+
return entry.name === "node_modules" || entry.name.startsWith(".")
|
|
462
|
+
? []
|
|
463
|
+
: listSourceFiles(path);
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
return entry.isFile() &&
|
|
467
|
+
sourceFilePattern.test(entry.name) &&
|
|
468
|
+
!declarationFilePattern.test(entry.name)
|
|
469
|
+
? [path]
|
|
470
|
+
: [];
|
|
471
|
+
});
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
function matchesAny(path, patterns, emptyResult) {
|
|
475
|
+
if (patterns.length === 0) {
|
|
476
|
+
return emptyResult;
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
const normalizedPath = normalizePath(path);
|
|
480
|
+
|
|
481
|
+
return patterns.some((pattern) => {
|
|
482
|
+
const normalizedPattern = normalizePath(pattern);
|
|
483
|
+
|
|
484
|
+
if (normalizedPattern.endsWith("/**")) {
|
|
485
|
+
return (
|
|
486
|
+
!isAbsolute(path) &&
|
|
487
|
+
normalizedPath !== ".." &&
|
|
488
|
+
!normalizedPath.startsWith("../") &&
|
|
489
|
+
normalizedPath.startsWith(normalizedPattern.slice(0, -2))
|
|
490
|
+
);
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
return normalizedPath.includes(normalizedPattern);
|
|
494
|
+
});
|
|
156
495
|
}
|
package/src/crap-score.d.ts
CHANGED
|
@@ -1,33 +1,8 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
}
|
|
6
|
-
|
|
7
|
-
export interface CrapScore {
|
|
8
|
-
file: string;
|
|
9
|
-
name: string;
|
|
10
|
-
complexity: number;
|
|
11
|
-
coverage: number;
|
|
12
|
-
crap: number;
|
|
13
|
-
}
|
|
14
|
-
|
|
1
|
+
/**
|
|
2
|
+
* CRAP = complexity² × (1 − coverage/100)³ + complexity.
|
|
3
|
+
* `coverage` is a percentage in [0, 100]; values outside are clamped.
|
|
4
|
+
*/
|
|
15
5
|
export function calculateCrapScore(input: {
|
|
16
6
|
complexity: number;
|
|
17
7
|
coverage: number;
|
|
18
8
|
}): number;
|
|
19
|
-
|
|
20
|
-
export function calculateCrapScoreFromPercent(
|
|
21
|
-
complexity: number,
|
|
22
|
-
coveragePercent: number,
|
|
23
|
-
): number;
|
|
24
|
-
|
|
25
|
-
export function buildCrapScores(input: {
|
|
26
|
-
coverageSummary: Record<string, unknown>;
|
|
27
|
-
metrics: ComplexityMetric[];
|
|
28
|
-
}): CrapScore[];
|
|
29
|
-
|
|
30
|
-
export function getCoverageForFile(
|
|
31
|
-
coverageSummary: Record<string, unknown>,
|
|
32
|
-
file: string,
|
|
33
|
-
): number;
|
package/src/crap-score.js
CHANGED
|
@@ -1,5 +1,3 @@
|
|
|
1
|
-
import { normalizePath } from "./path-utils.js";
|
|
2
|
-
|
|
3
1
|
export function calculateCrapScore({ complexity, coverage }) {
|
|
4
2
|
assertFiniteNumber(complexity, "complexity");
|
|
5
3
|
assertFiniteNumber(coverage, "coverage");
|
|
@@ -8,55 +6,6 @@ export function calculateCrapScore({ complexity, coverage }) {
|
|
|
8
6
|
return complexity ** 2 * uncoveredRatio ** 3 + complexity;
|
|
9
7
|
}
|
|
10
8
|
|
|
11
|
-
export function calculateCrapScoreFromPercent(complexity, coveragePercent) {
|
|
12
|
-
return calculateCrapScore({ complexity, coverage: coveragePercent });
|
|
13
|
-
}
|
|
14
|
-
|
|
15
|
-
export function buildCrapScores({ coverageSummary, metrics }) {
|
|
16
|
-
return metrics.map((metric) => {
|
|
17
|
-
const coverage = getCoverageForFile(coverageSummary, metric.file);
|
|
18
|
-
const score = calculateCrapScore({
|
|
19
|
-
complexity: metric.complexity,
|
|
20
|
-
coverage,
|
|
21
|
-
});
|
|
22
|
-
|
|
23
|
-
return {
|
|
24
|
-
file: metric.file,
|
|
25
|
-
name: metric.name,
|
|
26
|
-
complexity: metric.complexity,
|
|
27
|
-
coverage,
|
|
28
|
-
crap: Number(score.toFixed(2)),
|
|
29
|
-
};
|
|
30
|
-
});
|
|
31
|
-
}
|
|
32
|
-
|
|
33
|
-
export function getCoverageForFile(coverageSummary, file) {
|
|
34
|
-
const entry = findCoverageEntry(coverageSummary, file);
|
|
35
|
-
|
|
36
|
-
if (!entry?.lines || typeof entry.lines.pct !== "number") {
|
|
37
|
-
return 0;
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
return entry.lines.pct;
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
function findCoverageEntry(coverageSummary, file) {
|
|
44
|
-
if (coverageSummary[file]) {
|
|
45
|
-
return coverageSummary[file];
|
|
46
|
-
}
|
|
47
|
-
|
|
48
|
-
const normalizedFile = normalizePath(file);
|
|
49
|
-
const match = Object.entries(coverageSummary).find(([key]) => {
|
|
50
|
-
const normalizedKey = normalizePath(key);
|
|
51
|
-
return (
|
|
52
|
-
normalizedKey === normalizedFile ||
|
|
53
|
-
normalizedKey.endsWith(`/${normalizedFile}`)
|
|
54
|
-
);
|
|
55
|
-
});
|
|
56
|
-
|
|
57
|
-
return match?.[1];
|
|
58
|
-
}
|
|
59
|
-
|
|
60
9
|
function clamp(value, min, max) {
|
|
61
10
|
return Math.min(Math.max(value, min), max);
|
|
62
11
|
}
|