checkchange 0.4.2 → 0.4.4

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.
@@ -0,0 +1,188 @@
1
+ import * as path from 'node:path';
2
+ import * as fs from 'node:fs';
3
+ /**
4
+ * Typed parse failure. `reason` carries the EXISTING CoverageResult.reason
5
+ * value ('malformed', src/coverage.ts:487) so a caller maps a Cobertura refusal
6
+ * onto the current taxonomy without inventing a reason string.
7
+ * The size/line guards throw this too, so a single `instanceof` catch covers
8
+ * every provider-side refusal.
9
+ */
10
+ export class CoberturaParseError extends Error {
11
+ reason = 'malformed';
12
+ constructor(message) {
13
+ super(message);
14
+ this.name = 'CoberturaParseError';
15
+ }
16
+ }
17
+ /**
18
+ * Parse Cobertura XML content and convert it to the same Map shape the core
19
+ * package's parseCoverageReport produces, so coverageForMethods can attribute
20
+ * methods.
21
+ * @param coberturaContent The Cobertura XML file content as string
22
+ * @param cwd Current working directory for path normalization
23
+ * @returns Map<filePath, { statements: Array<{ span: { startLine: number, startColumn: number, endLine: number, endColumn: number }, hits: number }>, branches: [], functions: [] }>
24
+ * Branches and functions are always empty: a `<line branch="true">` element
25
+ * does NOT fabricate a branches array (same precedent as LCOV BRDA being
26
+ * ignored at lcovProvider.ts:70-71). Merge Cobertura with LCOV via
27
+ * mergeCoverageMaps rather than by concatenating raw maps.
28
+ * @throws {CoberturaParseError} on an oversized / over-long / malformed document
29
+ */
30
+ export function parseCoberturaContent(coberturaContent, cwd) {
31
+ // Security: limit Cobertura size to prevent OOM — same cap as lcovProvider.ts:19
32
+ const MAX_SIZE = 100 * 1024 * 1024; // 100MB
33
+ if (coberturaContent.length > MAX_SIZE) {
34
+ throw new CoberturaParseError(`Cobertura content exceeds maximum allowed size of ${MAX_SIZE} bytes`);
35
+ }
36
+ const lines = coberturaContent.split('\n');
37
+ if (lines.length > 1_000_000) {
38
+ throw new CoberturaParseError('Cobertura contains too many lines (over 1,000,000)');
39
+ }
40
+ // Empty artifact yields an empty map, mirroring parseLcovContent's empty input.
41
+ if (coberturaContent.trim() === '') {
42
+ return new Map();
43
+ }
44
+ if (!/<coverage[\s/>]/.test(coberturaContent)) {
45
+ throw new CoberturaParseError('Cobertura document has no <coverage> root element');
46
+ }
47
+ if (!coberturaContent.includes('</coverage>')) {
48
+ throw new CoberturaParseError('Cobertura document is truncated: no closing </coverage>');
49
+ }
50
+ const result = new Map();
51
+ // <class filename> is relative to <sources><source> (Coverlet writes an
52
+ // absolute source root), so the base is needed to resolve the real file.
53
+ let sourceBase = '';
54
+ let currentFile = '';
55
+ // Keyed by line number so a repeated <line number="N"> overwrites, as in LCOV.
56
+ const statements = {};
57
+ const flush = () => {
58
+ if (currentFile && Object.keys(statements).length > 0) {
59
+ const joined = sourceBase ? path.join(sourceBase, currentFile) : currentFile;
60
+ const normalized = normalizePath(joined, cwd);
61
+ if (normalized !== null) {
62
+ const incoming = Object.values(statements);
63
+ const existing = result.get(normalized);
64
+ if (existing === undefined) {
65
+ // Single-class path: plain set, unchanged from before the merge.
66
+ result.set(normalized, { statements: incoming, branches: [], functions: [] });
67
+ }
68
+ else {
69
+ // One file can host several <class> elements (Coverlet emits one per
70
+ // type, all sharing filename="Foo.cs"), so flush() is called again
71
+ // for the same key. Overwriting here dropped the earlier classes'
72
+ // lines and left only the last <class> covered. Merge instead,
73
+ // deduped by start line with MAX hits — a line shared by two types is
74
+ // covered if EITHER type executed it.
75
+ for (const unit of incoming) {
76
+ const at = existing.statements.findIndex(s => s.span.startLine === unit.span.startLine);
77
+ if (at === -1)
78
+ existing.statements.push(unit);
79
+ else if (unit.hits > existing.statements[at].hits)
80
+ existing.statements[at] = unit;
81
+ }
82
+ }
83
+ }
84
+ }
85
+ Object.keys(statements).forEach(k => delete statements[k]);
86
+ currentFile = '';
87
+ };
88
+ for (const raw of lines) {
89
+ const line = raw.trim();
90
+ if (line === '')
91
+ continue;
92
+ const source = line.match(/<source>([^<]*)<\/source>/);
93
+ if (source) {
94
+ sourceBase = decodeXml(source[1]);
95
+ continue;
96
+ }
97
+ // The \b keeps these from also matching <sources>, <classes> and <lines>.
98
+ const openClass = line.match(/<class\b([^>]*)>/);
99
+ if (openClass) {
100
+ flush(); // finalize the previous class before starting a new one
101
+ currentFile = decodeXml(attr(openClass[1], 'filename') ?? '');
102
+ }
103
+ // No `continue` after either match: <class>, <lines>, <line> and </class>
104
+ // are commonly emitted on ONE line, and each must still be seen.
105
+ // Scan EVERY <line> occurrence — a compact document packs several per line.
106
+ for (const lineTag of line.matchAll(/<line\b([^>]*?)\/?>/g)) {
107
+ if (!currentFile)
108
+ continue;
109
+ const numberStr = attr(lineTag[1], 'number');
110
+ const hitsStr = attr(lineTag[1], 'hits');
111
+ const lineNum = numberStr === null ? NaN : Number(numberStr);
112
+ const hits = hitsStr === null ? NaN : Number(hitsStr);
113
+ // Record-level garbage is skipped, not fatal — same as a bad `DA:` line.
114
+ if (Number.isInteger(lineNum) && Number.isFinite(hits)) {
115
+ statements[numberStr] = {
116
+ // Cobertura reports no column info, assume 0
117
+ span: { startLine: lineNum, startColumn: 0, endLine: lineNum, endColumn: 0 },
118
+ hits
119
+ };
120
+ }
121
+ }
122
+ if (/<\/class>/.test(line)) {
123
+ flush();
124
+ }
125
+ }
126
+ flush(); // handle the last class
127
+ return result;
128
+ }
129
+ /** Read a `name="value"` attribute out of a captured start tag. */
130
+ function attr(attrs, name) {
131
+ const match = attrs.match(new RegExp(`\\b${name}="([^"]*)"`));
132
+ return match ? match[1] : null;
133
+ }
134
+ function decodeXml(value) {
135
+ return value
136
+ .replace(/&lt;/g, '<')
137
+ .replace(/&gt;/g, '>')
138
+ .replace(/&quot;/g, '"')
139
+ .replace(/&apos;/g, "'")
140
+ .replace(/&amp;/g, '&');
141
+ }
142
+ /**
143
+ * Check if an absolute file path is within the given cwd.
144
+ * ponytail: duplicated from lcovProvider.ts:94-132 instead of exported from
145
+ * there — this task's file scope is coberturaProvider.ts + coverage.ts + 2 test
146
+ * files, and widening lcovProvider.ts is out of scope. Collapse both copies into
147
+ * a shared module when a third format provider lands.
148
+ */
149
+ function isWithinCwd(filePath, cwd) {
150
+ if (!path.isAbsolute(filePath)) {
151
+ filePath = path.resolve(cwd, filePath);
152
+ }
153
+ const rel = path.relative(cwd, filePath);
154
+ return !rel.startsWith('..') && !path.isAbsolute(rel);
155
+ }
156
+ /**
157
+ * Normalize a Cobertura filename to be relative to cwd if possible, using the
158
+ * same suffix-rebase idea as normalizeCoveragePaths (src/coverage.ts:302-336):
159
+ * an absolute path from another checkout is re-based onto cwd by longest
160
+ * existing suffix.
161
+ * @returns normalized path within cwd, or null if the path escapes cwd and cannot be rebased
162
+ */
163
+ function normalizePath(filePath, cwd) {
164
+ if (!path.isAbsolute(filePath)) {
165
+ const resolved = path.resolve(cwd, filePath);
166
+ return isWithinCwd(resolved, cwd) ? resolved : null;
167
+ }
168
+ // If absolute, first check if it's already within cwd
169
+ if (isWithinCwd(filePath, cwd)) {
170
+ return filePath;
171
+ }
172
+ // Try to rebase to cwd by suffix
173
+ const segments = filePath.split(path.sep);
174
+ for (let i = 1; i < segments.length; i++) {
175
+ const candidate = path.join(cwd, ...segments.slice(i));
176
+ if (!isWithinCwd(candidate, cwd))
177
+ continue;
178
+ try {
179
+ if (fs.existsSync(candidate)) {
180
+ return candidate;
181
+ }
182
+ }
183
+ catch {
184
+ // ignore
185
+ }
186
+ }
187
+ return null;
188
+ }
@@ -14,11 +14,98 @@ export interface CoverageResult {
14
14
  contentSha256?: string;
15
15
  }
16
16
  export declare const PYTHON_COVERAGE_FILES: readonly string[];
17
+ /**
18
+ * Union two coverage maps by file path — the seam a Cobertura artifact and an
19
+ * LCOV artifact feed (parseCoberturaContent + parseLcovContent).
20
+ *
21
+ * A path in only one map is carried through unchanged. A path in both has its
22
+ * statements concatenated and then deduped by start line, keeping the MAX hits:
23
+ * both formats report one statement per source line, so the same line reported
24
+ * twice is one statement, and the higher count is the honest one. Branch and
25
+ * function units are concatenated without dedupe — Cobertura never populates
26
+ * them, and this keeps the seam a plain union rather than a guess about which
27
+ * side is authoritative.
28
+ *
29
+ * KEY MATCHING IS CASE-INSENSITIVE. The parsers disagree on casing for the same
30
+ * file: `parseCoverageReport` (Istanbul) lowercases the whole absolute path,
31
+ * while `parseCoberturaContent` / `parseLcovContent` keep native case. Merging
32
+ * those two with a plain `Map.get(key)` silently matched nothing — one file
33
+ * landed in the merged map TWICE and the MAX-on-conflict rule never ran, which
34
+ * defeats the entire point of merging. Lookup is therefore folded to lower case;
35
+ * the FIRST-SEEN spelling is what the merged map emits, so a map whose keys all
36
+ * agree (Cobertura+LCOV, or any single format) round-trips byte-identical.
37
+ *
38
+ * ponytail: fold for LOOKUP only. Emitting the folded key would rewrite every
39
+ * key of a same-case merge, breaking callers that assert exact key spelling.
40
+ * First-seen wins, which keeps this a pure lookup change and leaves key casing
41
+ * as a property of whichever artifact the caller passed first.
42
+ *
43
+ * Neither input Map nor its FileCoverage values are mutated.
44
+ */
45
+ export declare function mergeCoverageMaps(a: CoverageMap, b: CoverageMap): CoverageMap;
46
+ /**
47
+ * Depth-bounded readdir scan for a `coverage.cobertura.xml` inside any per-run
48
+ * subdirectory of a `TestResults` directory under cwd.
49
+ *
50
+ * Bounded by construction: the `TestResults` directory name is matched at depth 1,
51
+ * 2 and 3 only (cwd itself, each direct child, and each grandchild), so the walk is
52
+ * O(entries in those dirs) with no glob dependency and no unbounded recursion.
53
+ * Depth 3 is required because `dotnet test` run from a REPO ROOT writes the artifact
54
+ * under the TEST PROJECT's directory, not the root — `test/GuardClauses.UnitTests/
55
+ * TestResults/<guid>/` (measured, SHA f96b823e). See `SKIP_SCAN_DIRS` for the prune
56
+ * that keeps `node_modules` out of the grandchild pass.
57
+ *
58
+ * Newest-mtime wins: vstest mints a fresh GUID directory per run and never prunes
59
+ * the old ones, so the most recently written artifact is the one that matches the
60
+ * working tree. Ties break on the lexicographically smaller absolute path so the
61
+ * result is deterministic across filesystems.
62
+ *
63
+ /**
64
+ * EXPORTED for the cached path: src/cache.ts calls this as its last resort so a
65
+ * cached C# run sees the same Coverlet `TestResults/<GUID>/` artifact an uncached
66
+ * run does. The cache used to document that divergence as a KNOWN LIMITATION
67
+ * because this function was module-private.
68
+ *
69
+ * @returns absolute path of the newest match, or null when there is none
70
+ */
71
+ export declare function scanCoberturaUnderTestResults(cwd: string): string | null;
72
+ /**
73
+ * Read the coverage artifacts discoverable under `cwd`.
74
+ *
75
+ * PRECEDENCE (top wins):
76
+ * 1. explicit `--coverage-file` — read alone, returned as-is, never merged
77
+ * 2. literal `coverageFiles` candidates — EVERY readable one is parsed and
78
+ * the resulting maps are REDUCED with `mergeCoverageMaps` in scan order
79
+ * 3. `TestResults` scan (newest mtime) — last resort, only when no literal
80
+ * candidate produced a map
81
+ *
82
+ * Multi-artifact merge (WS2.1): a repo routinely emits more than one coverage
83
+ * format at once (Coverlet Cobertura + an Istanbul `coverage.json`, or pytest-cov
84
+ * + LCOV). First-success-return silently dropped every artifact after the first,
85
+ * so a format that is the ONLY source of coverage for a given file reported it as
86
+ * uncovered. Accumulate-then-reduce unions them instead, keeping MAX hits per
87
+ * source line (`mergeFileCoverage`), which is the honest value when two tools
88
+ * instrument the same line.
89
+ *
90
+ * @lineage `contentSha256` is the hash of the FIRST artifact that produced a map
91
+ * (scan order), NOT of the merged result. `CoverageResult` carries a single hash
92
+ * and `src/evidence.ts:439` consumes it as the coverage lineage input, so the
93
+ * merged-map lineage stays per-artifact and is NOT a digest of the union. Any
94
+ * future consumer needing full-merge lineage must widen `CoverageResult` (a
95
+ * separate, schema-touching change) rather than silently reinterpreting this one.
96
+ *
97
+ * Malformed taxonomy is unchanged: if >=1 candidate was READABLE but none parsed,
98
+ * this returns `{ available:true, error:true, reason:'malformed' }` exactly as
99
+ * before — a partial success is a success, not a malformed read.
100
+ */
17
101
  export declare function readCoverage(cwd: string, coverageFile?: string, trace?: TraceRun, autoGenerated?: boolean): Promise<CoverageResult>;
18
102
  /**
19
103
  * Detect the coverage format and dispatch to the matching parser.
20
104
  *
21
105
  * Routes:
106
+ * - Cobertura: by basename ending `.cobertura.xml`, BEFORE the Python-JSON probe.
107
+ * Coverlet and pytest-cov emit the same Cobertura schema, so the filename is the
108
+ * only robust discriminator; content sniffing cannot separate them.
22
109
  * - LCOV: by extension (`.info`/`.lcov`) or content sniffing (TN:/SF:/DA: lines).
23
110
  * - Python coverage JSON (files key + meta/summary/totals): transformed to Istanbul
24
111
  * first, unless alreadyConverted (i.e. convertPythonCoverageToJson already ran).