checkchange 0.4.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/LICENSE +21 -0
- package/README.md +150 -0
- package/dist/attribution.d.ts +19 -0
- package/dist/attribution.js +175 -0
- package/dist/auto-coverage.d.ts +8 -0
- package/dist/auto-coverage.js +93 -0
- package/dist/cache.d.ts +70 -0
- package/dist/cache.js +458 -0
- package/dist/cli.d.ts +51 -0
- package/dist/cli.js +810 -0
- package/dist/complexity-providers/pythonASTComplexityProvider.d.ts +9 -0
- package/dist/complexity-providers/pythonASTComplexityProvider.js +148 -0
- package/dist/complexity-providers/pythonDescriptorProvider.d.ts +17 -0
- package/dist/complexity-providers/pythonDescriptorProvider.js +119 -0
- package/dist/complexity-providers.d.ts +6 -0
- package/dist/complexity-providers.js +1 -0
- package/dist/complexity.d.ts +14 -0
- package/dist/complexity.js +75 -0
- package/dist/coverage-providers/lcovProvider.d.ts +12 -0
- package/dist/coverage-providers/lcovProvider.js +126 -0
- package/dist/coverage.d.ts +28 -0
- package/dist/coverage.js +451 -0
- package/dist/crap.d.ts +31 -0
- package/dist/crap.js +84 -0
- package/dist/crapCalc.d.ts +5 -0
- package/dist/crapCalc.js +11 -0
- package/dist/delta.d.ts +100 -0
- package/dist/delta.js +214 -0
- package/dist/evidence.d.ts +201 -0
- package/dist/evidence.js +906 -0
- package/dist/execute.d.ts +59 -0
- package/dist/execute.js +92 -0
- package/dist/formatters/github.d.ts +5 -0
- package/dist/formatters/github.js +27 -0
- package/dist/formatters/index.d.ts +47 -0
- package/dist/formatters/index.js +14 -0
- package/dist/formatters/junit.d.ts +5 -0
- package/dist/formatters/junit.js +32 -0
- package/dist/formatters/sarif.d.ts +5 -0
- package/dist/formatters/sarif.js +35 -0
- package/dist/fs-safety.d.ts +10 -0
- package/dist/fs-safety.js +47 -0
- package/dist/git.d.ts +50 -0
- package/dist/git.js +137 -0
- package/dist/help.d.ts +40 -0
- package/dist/help.js +274 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.js +4 -0
- package/dist/providers/config.d.ts +41 -0
- package/dist/providers/config.js +172 -0
- package/dist/providers/genericCommand.d.ts +3 -0
- package/dist/providers/genericCommand.js +89 -0
- package/dist/providers/index.d.ts +7 -0
- package/dist/providers/index.js +4 -0
- package/dist/providers/prepare.d.ts +124 -0
- package/dist/providers/prepare.js +459 -0
- package/dist/providers/runner-detection.d.ts +30 -0
- package/dist/providers/runner-detection.js +207 -0
- package/dist/rules.d.ts +27 -0
- package/dist/rules.js +54 -0
- package/package.json +52 -0
package/dist/coverage.js
ADDED
|
@@ -0,0 +1,451 @@
|
|
|
1
|
+
import * as path from 'node:path';
|
|
2
|
+
import * as fs from 'node:fs';
|
|
3
|
+
import { access, constants, readFile } from 'node:fs/promises';
|
|
4
|
+
import { spawnSync } from 'node:child_process';
|
|
5
|
+
import { createHash } from 'node:crypto';
|
|
6
|
+
import { parseCoverageReport } from '@barney-media/crap-typescript-core';
|
|
7
|
+
import { parseLcovContent } from './coverage-providers/lcovProvider.js';
|
|
8
|
+
import { openWithinRoot } from './fs-safety.js';
|
|
9
|
+
import { providerRegistry } from './evidence.js';
|
|
10
|
+
// Provenance for the coverage lineage stage: artifact parser from the core package.
|
|
11
|
+
export const coverageProvenance = { tool: '@barney-media/crap-typescript-core', version: '0.5.0' };
|
|
12
|
+
const MAX_COVERAGE_SIZE = 100 * 1024 * 1024; // 100MB
|
|
13
|
+
export const PYTHON_COVERAGE_FILES = ['.coverage', 'coverage.xml', 'coverage.json', 'coverage/coverage-final.json']; // kept for backward compat; prefer config-driven coverageFiles
|
|
14
|
+
/**
|
|
15
|
+
* Validate file size and read auto-detected files from one fail-closed descriptor.
|
|
16
|
+
* Explicit files (user-provided) retain the containment exception.
|
|
17
|
+
*/
|
|
18
|
+
async function validateAndReadFile(filePath, cwd, isExplicit = false) {
|
|
19
|
+
try {
|
|
20
|
+
if (isExplicit) {
|
|
21
|
+
const fs = await import('node:fs/promises');
|
|
22
|
+
const stats = await fs.stat(filePath);
|
|
23
|
+
if (stats.size > MAX_COVERAGE_SIZE) {
|
|
24
|
+
return null;
|
|
25
|
+
}
|
|
26
|
+
return await readFile(filePath, 'utf8');
|
|
27
|
+
}
|
|
28
|
+
const handle = await openWithinRoot(cwd, filePath);
|
|
29
|
+
try {
|
|
30
|
+
const stats = await handle.stat();
|
|
31
|
+
if (stats.size > MAX_COVERAGE_SIZE) {
|
|
32
|
+
return null;
|
|
33
|
+
}
|
|
34
|
+
return await handle.readFile('utf8');
|
|
35
|
+
}
|
|
36
|
+
finally {
|
|
37
|
+
await handle.close();
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
catch {
|
|
41
|
+
return null;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Attempt to convert Python coverage format to Istanbul JSON using `coverage json`.
|
|
46
|
+
* Returns the path to the generated JSON file, or null if conversion fails.
|
|
47
|
+
*/
|
|
48
|
+
async function convertPythonCoverageToJson(inputPath, cwd) {
|
|
49
|
+
const outputPath = path.join(cwd, `.checkchange-coverage-temp-${process.pid}-${Math.random().toString(36).slice(2)}.json`);
|
|
50
|
+
// Best effort: delete stale temp file before writing new one
|
|
51
|
+
try {
|
|
52
|
+
await import('node:fs/promises').then(fs => fs.unlink(outputPath));
|
|
53
|
+
}
|
|
54
|
+
catch {
|
|
55
|
+
// ignore
|
|
56
|
+
}
|
|
57
|
+
// Try `coverage json` first (coverage.py v7+), then fallback to `python3 -m coverage json`
|
|
58
|
+
const commands = [
|
|
59
|
+
['coverage', 'json', '-o', outputPath],
|
|
60
|
+
['python3', '-m', 'coverage', 'json', '-o', outputPath],
|
|
61
|
+
];
|
|
62
|
+
for (const cmd of commands) {
|
|
63
|
+
const command = cmd[0];
|
|
64
|
+
const args = cmd.slice(1);
|
|
65
|
+
try {
|
|
66
|
+
const result = spawnSync(command, args, {
|
|
67
|
+
cwd,
|
|
68
|
+
encoding: 'utf8',
|
|
69
|
+
timeout: 30000,
|
|
70
|
+
});
|
|
71
|
+
if (result.status === 0) {
|
|
72
|
+
// Verify output was created and is valid
|
|
73
|
+
const content = await validateAndReadFile(outputPath, cwd);
|
|
74
|
+
if (content) {
|
|
75
|
+
// Transform Python coverage JSON format to Istanbul format
|
|
76
|
+
const transformedPath = await transformPythonCoverageToIstanbul(outputPath, cwd);
|
|
77
|
+
if (transformedPath) {
|
|
78
|
+
// Cleanup the intermediate Python JSON temp file
|
|
79
|
+
try {
|
|
80
|
+
await import('node:fs/promises').then(fs => fs.unlink(outputPath));
|
|
81
|
+
}
|
|
82
|
+
catch {
|
|
83
|
+
// ignore
|
|
84
|
+
}
|
|
85
|
+
return transformedPath;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
// Command succeeded but output invalid/missing - cleanup and continue
|
|
89
|
+
try {
|
|
90
|
+
await import('node:fs/promises').then(fs => fs.unlink(outputPath));
|
|
91
|
+
}
|
|
92
|
+
catch {
|
|
93
|
+
// ignore cleanup failure
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
catch {
|
|
98
|
+
// Command not found or failed, try next
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
// Final cleanup attempt for any partial file left behind
|
|
102
|
+
try {
|
|
103
|
+
await import('node:fs/promises').then(fs => fs.unlink(outputPath));
|
|
104
|
+
}
|
|
105
|
+
catch {
|
|
106
|
+
// ignore
|
|
107
|
+
}
|
|
108
|
+
return null;
|
|
109
|
+
}
|
|
110
|
+
// Read + validate the Python coverage artifact and return its `files` map.
|
|
111
|
+
// Returns null when the artifact is unreadable, unparseable, or not Python-shaped;
|
|
112
|
+
// callers treat null and the caller's own null-check as the single failure seam.
|
|
113
|
+
async function readPythonCoverageFiles(pythonJsonPath, cwd) {
|
|
114
|
+
const content = await validateAndReadFile(pythonJsonPath, cwd);
|
|
115
|
+
if (!content) {
|
|
116
|
+
return null;
|
|
117
|
+
}
|
|
118
|
+
const pythonCoverage = JSON.parse(content);
|
|
119
|
+
const files = pythonCoverage.files;
|
|
120
|
+
if (!files || typeof files !== 'object') {
|
|
121
|
+
return null;
|
|
122
|
+
}
|
|
123
|
+
return files;
|
|
124
|
+
}
|
|
125
|
+
// Dedupe-and-truncate ceiling for one file's combined executed + missing line list.
|
|
126
|
+
const MAX_LINES = 200_000;
|
|
127
|
+
// Build the Istanbul statementMap + s for one file. Dedupe-then-numeric-sort order and the
|
|
128
|
+
// sequential id assignment are load-bearing: they fix the key order the artifact serializes in.
|
|
129
|
+
function buildStatementMap(pythonFileData) {
|
|
130
|
+
const executedLines = pythonFileData.executed_lines || [];
|
|
131
|
+
const missingLines = pythonFileData.missing_lines || [];
|
|
132
|
+
const combined = [...executedLines, ...missingLines];
|
|
133
|
+
const deduped = combined.length > MAX_LINES ? [...new Set(combined)].slice(0, MAX_LINES) : [...new Set(combined)];
|
|
134
|
+
const allLines = deduped.sort((a, b) => a - b);
|
|
135
|
+
const statementMap = {};
|
|
136
|
+
const s = {};
|
|
137
|
+
let stmtId = 0;
|
|
138
|
+
for (const line of allLines) {
|
|
139
|
+
const key = String(stmtId++);
|
|
140
|
+
statementMap[key] = {
|
|
141
|
+
start: { line, column: 0 },
|
|
142
|
+
end: { line, column: 0 }
|
|
143
|
+
};
|
|
144
|
+
s[key] = executedLines.includes(line) ? 1 : 0;
|
|
145
|
+
}
|
|
146
|
+
return { statementMap, s };
|
|
147
|
+
}
|
|
148
|
+
// Build the Istanbul fnMap + f for one file. The fnId counter and the fnMap[key]
|
|
149
|
+
// assignment stay one atomic unit: they fix the key order the artifact serializes in.
|
|
150
|
+
function buildFunctionMap(pythonFileData) {
|
|
151
|
+
const fnMap = {};
|
|
152
|
+
const f = {};
|
|
153
|
+
let fnId = 0;
|
|
154
|
+
const functions = pythonFileData.functions || {};
|
|
155
|
+
for (const [funcName, funcData] of Object.entries(functions)) {
|
|
156
|
+
const func = funcData;
|
|
157
|
+
const key = String(fnId++);
|
|
158
|
+
const startLine = func.start_line || 1;
|
|
159
|
+
// coverage.py functions carry only start_line (no end_line). Statements
|
|
160
|
+
// attribute to a method only inside its fn span, so bound the end via
|
|
161
|
+
// the function's own line coverage; fall back to startLine when empty.
|
|
162
|
+
// ponytail: no end_line in artifact => synthesize; never guess beyond lines we saw.
|
|
163
|
+
const funcLines = [...(func.executed_lines || []), ...(func.missing_lines || [])];
|
|
164
|
+
const endLine = func.end_line ?? (funcLines.length > 0 ? funcLines.reduce((m, v) => v > m ? v : m, funcLines[0]) : startLine);
|
|
165
|
+
const covered = (func.summary?.percent_covered ?? 0) === 100;
|
|
166
|
+
fnMap[key] = {
|
|
167
|
+
name: funcName,
|
|
168
|
+
decl: {
|
|
169
|
+
start: { line: startLine, column: 0 },
|
|
170
|
+
end: { line: endLine, column: 0 }
|
|
171
|
+
},
|
|
172
|
+
line: startLine
|
|
173
|
+
};
|
|
174
|
+
f[key] = covered ? 1 : 0;
|
|
175
|
+
}
|
|
176
|
+
return { fnMap, f };
|
|
177
|
+
}
|
|
178
|
+
// Compose one file's complete Istanbul entry from the two map builders. branchMap/b
|
|
179
|
+
// stay literally empty: the Python format carries no branch data to read.
|
|
180
|
+
function assembleIstanbulFileCoverage(pythonFileData) {
|
|
181
|
+
const { statementMap, s } = buildStatementMap(pythonFileData);
|
|
182
|
+
const { fnMap, f } = buildFunctionMap(pythonFileData);
|
|
183
|
+
return {
|
|
184
|
+
statementMap,
|
|
185
|
+
s,
|
|
186
|
+
fnMap,
|
|
187
|
+
f,
|
|
188
|
+
branchMap: {},
|
|
189
|
+
b: {}
|
|
190
|
+
};
|
|
191
|
+
}
|
|
192
|
+
/**
|
|
193
|
+
* Transform Python coverage JSON format to Istanbul format expected by parseCoverageReport.
|
|
194
|
+
* Python format: { meta, files: { filepath: { executed_lines, missing_lines, functions: {...}, summary, ... } }, totals }
|
|
195
|
+
* Istanbul format: { filepath: { statementMap, s, fnMap, f, branchMap, b } }
|
|
196
|
+
*/
|
|
197
|
+
async function transformPythonCoverageToIstanbul(pythonJsonPath, cwd) {
|
|
198
|
+
const outputPath = path.join(cwd, `.checkchange-coverage-temp-istanbul-${process.pid}-${Math.random().toString(36).slice(2)}.json`);
|
|
199
|
+
try {
|
|
200
|
+
const files = await readPythonCoverageFiles(pythonJsonPath, cwd);
|
|
201
|
+
if (!files) {
|
|
202
|
+
return null;
|
|
203
|
+
}
|
|
204
|
+
// Convert to Istanbul format
|
|
205
|
+
const istanbulCoverage = {};
|
|
206
|
+
for (const [filePath, fileData] of Object.entries(files)) {
|
|
207
|
+
const absPath = path.isAbsolute(filePath) ? filePath : path.resolve(cwd, filePath);
|
|
208
|
+
const pythonFileData = fileData;
|
|
209
|
+
istanbulCoverage[absPath] = assembleIstanbulFileCoverage(pythonFileData);
|
|
210
|
+
}
|
|
211
|
+
await import('node:fs/promises').then(fs => fs.writeFile(outputPath, JSON.stringify(istanbulCoverage)));
|
|
212
|
+
return outputPath;
|
|
213
|
+
}
|
|
214
|
+
catch {
|
|
215
|
+
try {
|
|
216
|
+
await import('node:fs/promises').then(fs => fs.unlink(outputPath));
|
|
217
|
+
}
|
|
218
|
+
catch {
|
|
219
|
+
// ignore
|
|
220
|
+
}
|
|
221
|
+
return null;
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
/**
|
|
225
|
+
* F-03 remediation: rebase absolute Istanbul coverage keys onto the current cwd.
|
|
226
|
+
*
|
|
227
|
+
* Istanbul `coverage-final.json` records file paths as absolute paths from the
|
|
228
|
+
* generation environment. `parseCoverageReport` preserves these absolute paths
|
|
229
|
+
* in the returned Map. When the artifact is replayed in a different cwd
|
|
230
|
+
* (cross-machine, cross-CI, or re-clone after relocation), the absolute keys
|
|
231
|
+
* no longer match the project's tracked file paths.
|
|
232
|
+
*
|
|
233
|
+
* `src/attribution.ts` uses `endsWith()` suffix matching against repo-relative
|
|
234
|
+
* complexity paths, which works when the absolute key shares a tail with the
|
|
235
|
+
* relative path. But when the absolute prefix is entirely different (e.g.
|
|
236
|
+
* `/var/folders/.../other-repo/h3/src/x.ts` vs cwd `/Users/me/h3`), the
|
|
237
|
+
* suffix still matches if the repo-relative tail (`src/x.ts`) is identical.
|
|
238
|
+
* In practice the suffix-match still works for the attribution stage, BUT
|
|
239
|
+
* `parseFileMethods(coverageKey)` may be called with an absolute path that
|
|
240
|
+
* doesn't exist on disk in the current environment.
|
|
241
|
+
*
|
|
242
|
+
* Strategy: if the absolute key's tail matches a tracked file under the current
|
|
243
|
+
* cwd, rewrite the key to the absolute path of the matching file under cwd.
|
|
244
|
+
* Otherwise leave the key unchanged (attribution's endsWith will still
|
|
245
|
+
* succeed for the original cross-environment case via suffix overlap).
|
|
246
|
+
*
|
|
247
|
+
* F-04 (test-file expansion) is unrelated and is handled separately in
|
|
248
|
+
* `src/complexity.ts` and documentation.
|
|
249
|
+
*/
|
|
250
|
+
function normalizeCoveragePaths(coverageMap, cwd) {
|
|
251
|
+
const normalized = new Map();
|
|
252
|
+
for (const [key, value] of coverageMap.entries()) {
|
|
253
|
+
if (!path.isAbsolute(key)) {
|
|
254
|
+
normalized.set(key, value);
|
|
255
|
+
continue;
|
|
256
|
+
}
|
|
257
|
+
// Find the longest suffix of `key` that, when resolved against `cwd`,
|
|
258
|
+
// points to an existing file. This re-bases cross-environment absolute
|
|
259
|
+
// paths onto the current checkout.
|
|
260
|
+
// ponytail: resolve against cwd as given (no realpath) so rebased keys
|
|
261
|
+
// keep the caller's path form (macOS /var vs /private/var).
|
|
262
|
+
const segments = key.split(path.sep);
|
|
263
|
+
let rebased = key;
|
|
264
|
+
for (let i = 1; i < segments.length; i++) {
|
|
265
|
+
const candidate = path.join(cwd, ...segments.slice(i));
|
|
266
|
+
// Boundary check: candidate must stay within cwd
|
|
267
|
+
const rel = path.relative(cwd, candidate);
|
|
268
|
+
if (rel.startsWith('..') || path.isAbsolute(rel))
|
|
269
|
+
continue;
|
|
270
|
+
try {
|
|
271
|
+
if (fs.existsSync(candidate)) {
|
|
272
|
+
rebased = candidate;
|
|
273
|
+
break;
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
catch {
|
|
277
|
+
// ignore and continue
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
normalized.set(rebased, value);
|
|
281
|
+
}
|
|
282
|
+
return normalized;
|
|
283
|
+
}
|
|
284
|
+
export async function readCoverage(cwd, coverageFile, trace, autoGenerated) {
|
|
285
|
+
// 1. Explicit coverageFile provided - use it directly (existing behavior)
|
|
286
|
+
if (coverageFile !== undefined && coverageFile !== null && coverageFile !== '') {
|
|
287
|
+
const coveragePath = path.isAbsolute(coverageFile) ? coverageFile : path.resolve(cwd, coverageFile);
|
|
288
|
+
return await readCoverageFile(coveragePath, cwd, true, autoGenerated);
|
|
289
|
+
}
|
|
290
|
+
// 2. Auto-detect coverage files in precedence order with fallthrough on conversion failure
|
|
291
|
+
// Precedence: config-driven — all providers' coverageFiles deduped in builtin order
|
|
292
|
+
let artifactFound = false;
|
|
293
|
+
const registry = providerRegistry();
|
|
294
|
+
const coverageCandidates = registry
|
|
295
|
+
? [...new Set([...registry.values()].flatMap((r) => r.coverageFiles))]
|
|
296
|
+
: [...PYTHON_COVERAGE_FILES];
|
|
297
|
+
for (const file of coverageCandidates) {
|
|
298
|
+
const filePath = path.join(cwd, file);
|
|
299
|
+
try {
|
|
300
|
+
await access(filePath, constants.R_OK);
|
|
301
|
+
artifactFound = true;
|
|
302
|
+
const result = await readCoverageFile(filePath, cwd, false);
|
|
303
|
+
// If conversion/read succeeded (error: false), return it
|
|
304
|
+
if (!result.error) {
|
|
305
|
+
return result;
|
|
306
|
+
}
|
|
307
|
+
// Conversion/read failed - warn and continue to next candidate
|
|
308
|
+
const message = `Coverage conversion failed for ${filePath}: ${result.reason}`;
|
|
309
|
+
if (trace) {
|
|
310
|
+
trace.recordWarning('coverage', message);
|
|
311
|
+
}
|
|
312
|
+
else {
|
|
313
|
+
console.warn(message);
|
|
314
|
+
}
|
|
315
|
+
// Continue to next file in precedence
|
|
316
|
+
}
|
|
317
|
+
catch {
|
|
318
|
+
// File doesn't exist or not readable, continue to next
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
// 3. All candidates exhausted
|
|
322
|
+
if (artifactFound) {
|
|
323
|
+
// At least one artifact existed but all failed conversion
|
|
324
|
+
return { available: true, coverageMap: null, error: true, reason: 'malformed' };
|
|
325
|
+
}
|
|
326
|
+
else {
|
|
327
|
+
// No coverage files found at all
|
|
328
|
+
return { available: false, coverageMap: null, error: false };
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
/**
|
|
332
|
+
* Detect the coverage format and dispatch to the matching parser.
|
|
333
|
+
*
|
|
334
|
+
* Routes:
|
|
335
|
+
* - LCOV: by extension (`.info`/`.lcov`) or content sniffing (TN:/SF:/DA: lines).
|
|
336
|
+
* - Python coverage JSON (files key + meta/summary/totals): transformed to Istanbul
|
|
337
|
+
* first, unless alreadyConverted (i.e. convertPythonCoverageToJson already ran).
|
|
338
|
+
* - Otherwise: parsed directly as Istanbul JSON.
|
|
339
|
+
*/
|
|
340
|
+
export async function detectCoverageFormat(content, actualPath, cwd, isLcovByExt, alreadyConverted) {
|
|
341
|
+
// Check if LCOV by content
|
|
342
|
+
let isLcov = isLcovByExt;
|
|
343
|
+
if (!isLcovByExt) {
|
|
344
|
+
if (content.startsWith('TN:') || content.includes('\nSF:') || content.includes('\nDA:')) {
|
|
345
|
+
isLcov = true;
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
if (isLcov) {
|
|
349
|
+
// Security: limit LCOV size - validateAndReadFile already enforces stats.size pre-read
|
|
350
|
+
return parseLcovContent(content, cwd);
|
|
351
|
+
}
|
|
352
|
+
// Check if this is Python coverage JSON format (has 'files' key + 'meta'/'summary'/'totals')
|
|
353
|
+
// If so, transform to Istanbul format before parsing
|
|
354
|
+
// Skip if already converted via convertPythonCoverageToJson (prevents double-transform)
|
|
355
|
+
let parsePath = actualPath;
|
|
356
|
+
let parseTempFile = null;
|
|
357
|
+
if (!alreadyConverted) {
|
|
358
|
+
try {
|
|
359
|
+
const jsonData = JSON.parse(content);
|
|
360
|
+
if (jsonData.files && typeof jsonData.files === 'object' && (jsonData.meta || jsonData.summary || jsonData.totals)) {
|
|
361
|
+
// Python coverage format detected - transform to Istanbul
|
|
362
|
+
const transformedPath = await transformPythonCoverageToIstanbul(actualPath, cwd);
|
|
363
|
+
if (transformedPath) {
|
|
364
|
+
parsePath = transformedPath;
|
|
365
|
+
parseTempFile = transformedPath;
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
catch {
|
|
370
|
+
// Not valid JSON or not Python format, proceed as-is
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
// Treat as Istanbul JSON (including converted Python coverage.json)
|
|
374
|
+
const coverageMap = await parseCoverageReport(parsePath, cwd);
|
|
375
|
+
// Cleanup transform temp file if created
|
|
376
|
+
if (parseTempFile) {
|
|
377
|
+
try {
|
|
378
|
+
await import('node:fs/promises').then(fs => fs.unlink(parseTempFile));
|
|
379
|
+
}
|
|
380
|
+
catch {
|
|
381
|
+
// ignore
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
return coverageMap;
|
|
385
|
+
}
|
|
386
|
+
async function readCoverageFile(coveragePath, cwd, isExplicit, autoGenerated) {
|
|
387
|
+
// Check if file exists and is readable
|
|
388
|
+
try {
|
|
389
|
+
await access(coveragePath, constants.R_OK);
|
|
390
|
+
}
|
|
391
|
+
catch {
|
|
392
|
+
if (isExplicit && !autoGenerated) {
|
|
393
|
+
return { available: true, coverageMap: null, error: true, reason: 'missing' };
|
|
394
|
+
}
|
|
395
|
+
else {
|
|
396
|
+
return { available: false, coverageMap: null, error: false };
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
// Determine file type by extension + basename (handles .coverage dotfile)
|
|
400
|
+
const ext = path.extname(coveragePath).toLowerCase();
|
|
401
|
+
const basename = path.basename(coveragePath);
|
|
402
|
+
const isLcovByExt = ext === '.info' || ext === '.lcov';
|
|
403
|
+
const isPythonCoverageBinary = basename === '.coverage';
|
|
404
|
+
const isPythonCoverageXml = ext === '.xml' && basename.startsWith('coverage');
|
|
405
|
+
// For Python .coverage binary or coverage.xml, try to convert to JSON first
|
|
406
|
+
let actualPath = coveragePath;
|
|
407
|
+
let tempFileToCleanup = null;
|
|
408
|
+
let alreadyConverted = false;
|
|
409
|
+
if (isPythonCoverageBinary || isPythonCoverageXml) {
|
|
410
|
+
const convertedPath = await convertPythonCoverageToJson(coveragePath, cwd);
|
|
411
|
+
if (convertedPath) {
|
|
412
|
+
actualPath = convertedPath;
|
|
413
|
+
tempFileToCleanup = convertedPath;
|
|
414
|
+
alreadyConverted = true;
|
|
415
|
+
}
|
|
416
|
+
else {
|
|
417
|
+
// Conversion failed - warn and fall back to generic path
|
|
418
|
+
if (autoGenerated)
|
|
419
|
+
return { available: false, coverageMap: null, error: false };
|
|
420
|
+
return { available: true, coverageMap: null, error: true, reason: 'malformed' };
|
|
421
|
+
}
|
|
422
|
+
}
|
|
423
|
+
try {
|
|
424
|
+
// Read and validate file
|
|
425
|
+
const content = await validateAndReadFile(actualPath, cwd, isExplicit);
|
|
426
|
+
if (content === null) {
|
|
427
|
+
if (autoGenerated)
|
|
428
|
+
return { available: false, coverageMap: null, error: false };
|
|
429
|
+
return { available: true, coverageMap: null, error: true, reason: 'malformed' };
|
|
430
|
+
}
|
|
431
|
+
const coverageMap = await detectCoverageFormat(content, actualPath, cwd, isLcovByExt, alreadyConverted);
|
|
432
|
+
const normalizedCoverageMap = normalizeCoveragePaths(coverageMap, cwd);
|
|
433
|
+
// Lineage input identity: hash of the artifact bytes actually read (in hand, no new reads)
|
|
434
|
+
return { available: true, coverageMap: normalizedCoverageMap, error: false, contentSha256: createHash('sha256').update(content).digest('hex') };
|
|
435
|
+
}
|
|
436
|
+
catch {
|
|
437
|
+
// Malformed or unreadable
|
|
438
|
+
return { available: true, coverageMap: null, error: true, reason: 'malformed' };
|
|
439
|
+
}
|
|
440
|
+
finally {
|
|
441
|
+
// Cleanup temp file if created - runs on ALL paths (success, early return, throw)
|
|
442
|
+
if (tempFileToCleanup) {
|
|
443
|
+
try {
|
|
444
|
+
await import('node:fs/promises').then(fs => fs.unlink(tempFileToCleanup));
|
|
445
|
+
}
|
|
446
|
+
catch {
|
|
447
|
+
// ignore cleanup failure
|
|
448
|
+
}
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
}
|
package/dist/crap.d.ts
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
export interface MethodEvidence {
|
|
2
|
+
file: string;
|
|
3
|
+
method: string;
|
|
4
|
+
lineStart: number;
|
|
5
|
+
lineEnd: number;
|
|
6
|
+
cc: number;
|
|
7
|
+
crap: number | null;
|
|
8
|
+
coverage: number | null;
|
|
9
|
+
coverageKind: string;
|
|
10
|
+
analyzerStatus: 'passed' | 'failed' | 'skipped';
|
|
11
|
+
}
|
|
12
|
+
export interface CrapResult {
|
|
13
|
+
methodEvidence: MethodEvidence[];
|
|
14
|
+
rawJson: string;
|
|
15
|
+
exitCode: number | null;
|
|
16
|
+
stderr: string;
|
|
17
|
+
durationMs: number;
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Runs crap-typescript and returns the parsed result.
|
|
21
|
+
* @param cwd The current working directory (defaults to process.cwd())
|
|
22
|
+
* @returns Promise<CrapResult>
|
|
23
|
+
*/
|
|
24
|
+
export declare function runCrap(cwd?: string): Promise<CrapResult>;
|
|
25
|
+
/**
|
|
26
|
+
* Parses a crap-typescript JSON string into method evidence.
|
|
27
|
+
* Used for unit tests.
|
|
28
|
+
* @param jsonStr The JSON string output from crap-typescript
|
|
29
|
+
* @returns MethodEvidence[]
|
|
30
|
+
*/
|
|
31
|
+
export declare function parseCrapJson(jsonStr: string): MethodEvidence[];
|
package/dist/crap.js
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import { execute } from './execute.js';
|
|
2
|
+
/**
|
|
3
|
+
* Runs crap-typescript and returns the parsed result.
|
|
4
|
+
* @param cwd The current working directory (defaults to process.cwd())
|
|
5
|
+
* @returns Promise<CrapResult>
|
|
6
|
+
*/
|
|
7
|
+
export async function runCrap(cwd = process.cwd()) {
|
|
8
|
+
const start = Date.now();
|
|
9
|
+
const result = await execute('npx', ['--no-install', 'crap-typescript', '--format', 'json'], { cwd });
|
|
10
|
+
const end = Date.now();
|
|
11
|
+
const durationMs = end - start;
|
|
12
|
+
let exitCode = result.exitCode;
|
|
13
|
+
// We'll keep exitCode as is (number | null)
|
|
14
|
+
let methodEvidence = [];
|
|
15
|
+
// Try to parse the JSON
|
|
16
|
+
let parsed;
|
|
17
|
+
try {
|
|
18
|
+
parsed = JSON.parse(result.stdout);
|
|
19
|
+
}
|
|
20
|
+
catch {
|
|
21
|
+
// If JSON parsing fails, we return empty methodEvidence and the exitCode as is
|
|
22
|
+
return {
|
|
23
|
+
methodEvidence: [],
|
|
24
|
+
rawJson: result.stdout,
|
|
25
|
+
exitCode,
|
|
26
|
+
stderr: result.stderr,
|
|
27
|
+
durationMs
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
// Check if we have a methods array
|
|
31
|
+
if (parsed && Array.isArray(parsed.methods)) {
|
|
32
|
+
methodEvidence = parsed.methods.map((method) => ({
|
|
33
|
+
file: method.src,
|
|
34
|
+
method: method.method,
|
|
35
|
+
lineStart: method.lineStart,
|
|
36
|
+
lineEnd: method.lineEnd,
|
|
37
|
+
cc: method.cc,
|
|
38
|
+
crap: method.crap !== undefined && method.crap !== null ? method.crap : null,
|
|
39
|
+
coverage: method.cov !== undefined && method.cov !== null ? method.cov : null,
|
|
40
|
+
coverageKind: method.covKind === 'stmt' ? 'stmt' :
|
|
41
|
+
method.covKind === 'N/A' ? 'N/A' :
|
|
42
|
+
method.covKind,
|
|
43
|
+
analyzerStatus: method.status
|
|
44
|
+
}));
|
|
45
|
+
}
|
|
46
|
+
return {
|
|
47
|
+
methodEvidence,
|
|
48
|
+
rawJson: result.stdout,
|
|
49
|
+
exitCode,
|
|
50
|
+
stderr: result.stderr,
|
|
51
|
+
durationMs
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Parses a crap-typescript JSON string into method evidence.
|
|
56
|
+
* Used for unit tests.
|
|
57
|
+
* @param jsonStr The JSON string output from crap-typescript
|
|
58
|
+
* @returns MethodEvidence[]
|
|
59
|
+
*/
|
|
60
|
+
export function parseCrapJson(jsonStr) {
|
|
61
|
+
try {
|
|
62
|
+
const parsed = JSON.parse(jsonStr);
|
|
63
|
+
if (parsed && Array.isArray(parsed.methods)) {
|
|
64
|
+
return parsed.methods.map((method) => ({
|
|
65
|
+
file: method.src,
|
|
66
|
+
method: method.method,
|
|
67
|
+
lineStart: method.lineStart,
|
|
68
|
+
lineEnd: method.lineEnd,
|
|
69
|
+
cc: method.cc,
|
|
70
|
+
crap: method.crap !== undefined && method.crap !== null ? method.crap : null,
|
|
71
|
+
coverage: method.cov !== undefined && method.cov !== null ? method.cov : null,
|
|
72
|
+
coverageKind: method.covKind === 'stmt' ? 'stmt' :
|
|
73
|
+
method.covKind === 'N/A' ? 'N/A' :
|
|
74
|
+
method.covKind,
|
|
75
|
+
analyzerStatus: method.status
|
|
76
|
+
}));
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
catch {
|
|
80
|
+
// Return empty array on error
|
|
81
|
+
return [];
|
|
82
|
+
}
|
|
83
|
+
return [];
|
|
84
|
+
}
|
package/dist/crapCalc.js
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
// Provenance for the crapCalc lineage stage. Self tool version tracks package.json
|
|
2
|
+
// (matches existing hard-coded '0.5.0' style for the core package).
|
|
3
|
+
export const crapCalcProvenance = { tool: 'checkchange', version: '0.4.0' };
|
|
4
|
+
export function calculateCrap(cc, coveragePercent) {
|
|
5
|
+
if (coveragePercent == null) {
|
|
6
|
+
return null;
|
|
7
|
+
}
|
|
8
|
+
const fraction = coveragePercent / 100.0;
|
|
9
|
+
const term = Math.pow(1 - fraction, 3);
|
|
10
|
+
return cc * cc * term + cc;
|
|
11
|
+
}
|
package/dist/delta.d.ts
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
import type { ChangedFunction, DiagnosticLineageEntry, DiagnosticQuality } from './evidence.js';
|
|
2
|
+
import type { RuleResult } from './rules.js';
|
|
3
|
+
/**
|
|
4
|
+
* D2 baseline/delta sidecar: pure comparator over two EvidenceOutput runs
|
|
5
|
+
* (schema 0.5). Emits DeltaOutput — an evidence diff, not a score diff.
|
|
6
|
+
* Additive only: gate semantics frozen (Q6, mem:44649), schema 0.5 frozen,
|
|
7
|
+
* no engine files touched. Same inputs -> byte-identical JSON (arrays sorted
|
|
8
|
+
* by key, object keys in fixed literal order).
|
|
9
|
+
*/
|
|
10
|
+
export interface EvidenceOutput {
|
|
11
|
+
schemaVersion: string;
|
|
12
|
+
analysis: {
|
|
13
|
+
base: string;
|
|
14
|
+
target: string;
|
|
15
|
+
};
|
|
16
|
+
changedFunctions: ChangedFunction[];
|
|
17
|
+
policy: {
|
|
18
|
+
crapThreshold: number;
|
|
19
|
+
};
|
|
20
|
+
ruleResults: RuleResult[];
|
|
21
|
+
analysisStatus: string;
|
|
22
|
+
gate: string | null;
|
|
23
|
+
completeness: string;
|
|
24
|
+
coverageErrorReason?: string;
|
|
25
|
+
diagnostics?: {
|
|
26
|
+
lineage: DiagnosticLineageEntry[];
|
|
27
|
+
quality: DiagnosticQuality;
|
|
28
|
+
fingerprints?: Record<string, string>;
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
export interface DeltaOutput {
|
|
32
|
+
command: 'delta';
|
|
33
|
+
schemaVersion: '0.5';
|
|
34
|
+
inputs: {
|
|
35
|
+
baseline: {
|
|
36
|
+
base: string;
|
|
37
|
+
analysisStatus: string;
|
|
38
|
+
gate: string | null;
|
|
39
|
+
changedFunctions: number;
|
|
40
|
+
};
|
|
41
|
+
current: {
|
|
42
|
+
base: string;
|
|
43
|
+
analysisStatus: string;
|
|
44
|
+
gate: string | null;
|
|
45
|
+
changedFunctions: number;
|
|
46
|
+
};
|
|
47
|
+
thresholds: {
|
|
48
|
+
baseline: number;
|
|
49
|
+
current: number;
|
|
50
|
+
equal: boolean;
|
|
51
|
+
};
|
|
52
|
+
};
|
|
53
|
+
summary: {
|
|
54
|
+
added: number;
|
|
55
|
+
removed: number;
|
|
56
|
+
changed: number;
|
|
57
|
+
unchanged: number;
|
|
58
|
+
gateTransition: string | null;
|
|
59
|
+
completenessTransition: string | null;
|
|
60
|
+
};
|
|
61
|
+
functions: {
|
|
62
|
+
added: Array<{
|
|
63
|
+
key: string;
|
|
64
|
+
current: ChangedFunction;
|
|
65
|
+
ruleResult?: RuleResult;
|
|
66
|
+
}>;
|
|
67
|
+
removed: Array<{
|
|
68
|
+
key: string;
|
|
69
|
+
baseline: ChangedFunction;
|
|
70
|
+
ruleResult?: RuleResult;
|
|
71
|
+
}>;
|
|
72
|
+
changed: Array<{
|
|
73
|
+
key: string;
|
|
74
|
+
baseline: ChangedFunction;
|
|
75
|
+
current: ChangedFunction;
|
|
76
|
+
fingerprintChanged: boolean;
|
|
77
|
+
deltas: {
|
|
78
|
+
cc: number | null;
|
|
79
|
+
crap: number | null;
|
|
80
|
+
coverage: number | null;
|
|
81
|
+
};
|
|
82
|
+
ruleTransition: string | null;
|
|
83
|
+
}>;
|
|
84
|
+
unchanged: string[];
|
|
85
|
+
};
|
|
86
|
+
provenance?: {
|
|
87
|
+
baseline: {
|
|
88
|
+
lineage: DiagnosticLineageEntry[] | null;
|
|
89
|
+
quality: DiagnosticQuality | null;
|
|
90
|
+
};
|
|
91
|
+
current: {
|
|
92
|
+
lineage: DiagnosticLineageEntry[] | null;
|
|
93
|
+
quality: DiagnosticQuality | null;
|
|
94
|
+
};
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
/** Pure comparator: no I/O, deterministic (all output arrays sorted by key). */
|
|
98
|
+
export declare function compareEvidenceOutputs(baseline: EvidenceOutput, current: EvidenceOutput): DeltaOutput;
|
|
99
|
+
/** File-pair mode: read two EvidenceOutput JSON files with guards, compare. */
|
|
100
|
+
export declare function compareFromFiles(baselinePath: string, currentPath: string, cwd?: string): Promise<DeltaOutput>;
|