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