mo3ta-coverage 1.0.9 → 1.0.12

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/index.js CHANGED
@@ -34,7 +34,8 @@ program
34
34
  .option('--lcov <path>', 'Path to lcov.info file generated by test coverage tools', 'coverage/lcov.info')
35
35
  .option('--limit <percent>', 'Minimum required coverage percentage for all changed lines (e.g., 80)', '80')
36
36
  .option('--showCovered <bool>', 'Show covered changed lines in the output', false)
37
- .option('--shallow <bool>', 'Run test files only without deep in tests tree', true)
37
+ .option('--mode <mode>', 'Execution mode: fast, smart, or full', 'smart')
38
+ .option('--maxDepth <number>', 'Maximum reverse dependency depth for smart mode', '3')
38
39
  .enablePositionalOptions(); // used to allow using same options in subcommands
39
40
 
40
41
 
@@ -42,7 +43,8 @@ program
42
43
  .command('config')
43
44
  .description('Set or get configuration options')
44
45
  .option('--base <branch>', 'Set default base branch')
45
- .option('--shallow <bool>', 'Set default shallow value (true/false)')
46
+ .option('--mode <mode>', 'Set default mode (fast/smart/full)')
47
+ .option('--maxDepth <number>', 'Set default reverse dependency depth for smart mode')
46
48
  .action((opts) => {
47
49
  let config = readConfig();
48
50
 
@@ -56,11 +58,28 @@ program
56
58
  console.log(`Default base branch set to: ${opts.base}`);
57
59
  }
58
60
 
59
- if (typeof opts.shallow !== 'undefined') {
60
- config.shallow = opts.shallow === 'true' || opts.shallow === true;
61
+ if (opts.mode !== undefined) {
62
+ const normalizedMode = String(opts.mode).toLowerCase();
63
+ if (!['fast', 'smart', 'full'].includes(normalizedMode)) {
64
+ console.error(`Invalid mode: ${opts.mode}. Expected one of: fast, smart, full.`);
65
+ process.exit(1);
66
+ }
67
+ config.mode = normalizedMode;
61
68
  updated = true;
62
- console.log(`Default shallow set to: ${config.shallow}`);
69
+ console.log(`Default mode set to: ${config.mode}`);
63
70
  }
71
+
72
+ if (opts.maxDepth !== undefined) {
73
+ const parsedMaxDepth = parseInt(opts.maxDepth, 10);
74
+ if (!Number.isInteger(parsedMaxDepth) || parsedMaxDepth < 0) {
75
+ console.error(`Invalid maxDepth: ${opts.maxDepth}. Expected a non-negative integer.`);
76
+ process.exit(1);
77
+ }
78
+ config.maxDepth = parsedMaxDepth;
79
+ updated = true;
80
+ console.log(`Default max depth set to: ${config.maxDepth}`);
81
+ }
82
+
64
83
  if (updated) {
65
84
  writeConfig(config);
66
85
  } else {
@@ -81,10 +100,26 @@ program.action((opts) => {
81
100
  } else if (!options.base) {
82
101
  options.base = 'origin/main';
83
102
  }
84
- // Use config shallow if not provided in CLI
85
- console.log(`Using shallow: ${options.shallow} ${config.shallow}`);
86
103
 
87
- options.shallow = config.shallow ?? options.shallow;
104
+ if (!options.mode && config.mode) {
105
+ options.mode = config.mode;
106
+ }
107
+
108
+ if ((options.maxDepth === undefined || options.maxDepth === '3') && config.maxDepth !== undefined) {
109
+ options.maxDepth = config.maxDepth;
110
+ }
111
+
112
+ options.mode = String(options.mode || 'smart').toLowerCase();
113
+ if (!['fast', 'smart', 'full'].includes(options.mode)) {
114
+ console.error(`Invalid mode: ${options.mode}. Expected one of: fast, smart, full.`);
115
+ process.exit(1);
116
+ }
117
+
118
+ options.maxDepth = parseInt(options.maxDepth ?? 3, 10);
119
+ if (!Number.isInteger(options.maxDepth) || options.maxDepth < 0) {
120
+ console.error(`Invalid maxDepth: ${options.maxDepth}. Expected a non-negative integer.`);
121
+ process.exit(1);
122
+ }
88
123
 
89
124
  console.log(`Final options: ${JSON.stringify(options, null, 2)}`);
90
125
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mo3ta-coverage",
3
- "version": "1.0.9",
3
+ "version": "1.0.12",
4
4
  "description": "Run tests and report uncovered changed lines in a PR",
5
5
  "main": "index.js",
6
6
  "bin": {
@@ -37,6 +37,7 @@
37
37
  "jest": "^30.0.5"
38
38
  },
39
39
  "dependencies": {
40
- "commander": "^14.0.0"
40
+ "commander": "^14.0.0",
41
+ "typescript": "^5.8.3"
41
42
  }
42
43
  }
package/src/cli.js CHANGED
@@ -3,7 +3,42 @@ import fs from 'fs';
3
3
  import path from 'path';
4
4
  import { exit } from 'process';
5
5
  import { verifyBaseBranchExists, verifyGitRepoExists } from './gitUtils.js';
6
- import { getJsOnlyFiles } from './fileUtils.js';
6
+ import { getJsOnlyFiles, separateSourceAndTestFiles, findTestFilesForSource } from './fileUtils.js';
7
+ import { findImportersForMany } from './importer.js';
8
+
9
+ function findReverseDepsForSourceFiles(sourceFiles, maxDepth) {
10
+ if (sourceFiles.length === 0) return [];
11
+ const importerResults = findImportersForMany(sourceFiles, maxDepth, {
12
+ projectDir: process.cwd()
13
+ });
14
+ const testFilesForReverseDeps = new Set();
15
+ const debugResults = [];
16
+
17
+ importerResults.forEach((result, targetFile) => {
18
+ const importers = result.importers.map(node => node.file);
19
+
20
+ debugResults.push({
21
+ targetFile,
22
+ importerCount: importers.length,
23
+ maxDepthReached: result.maxDepthReached,
24
+ importers: result.importers.map(node => ({
25
+ file: node.file,
26
+ depth: node.depth,
27
+ importedBy: node.importedBy
28
+ }))
29
+ });
30
+
31
+ importers.forEach(file => {
32
+ const tests = findTestFilesForSource(file);
33
+ tests.forEach(test => testFilesForReverseDeps.add(test));
34
+ });
35
+ });
36
+
37
+ return {
38
+ reverseDepsTests: Array.from(testFilesForReverseDeps),
39
+ debugResults
40
+ };
41
+ }
7
42
 
8
43
  export function main(options) {
9
44
  try {
@@ -14,12 +49,13 @@ export function main(options) {
14
49
  const LCOV_PATH = options.lcov;
15
50
  const COVERAGE_LIMIT = parseFloat(options.limit);
16
51
  const SHOW_COVERED = options.showCovered === true || options.showCovered === 'true';
17
- const SHALLOW_TESTS = options.shallow === true || options.shallow === 'true';
52
+ const MODE = options.mode;
53
+ const MAX_DEPTH = options.maxDepth;
18
54
 
19
- console.log(`Options:\nBase Branch: ${BASE_BRANCH} \nLCOV Path: ${LCOV_PATH} \nCoverage Limit: ${COVERAGE_LIMIT} \nShow Covered Lines: ${SHOW_COVERED} \nShallow Tests: ${SHALLOW_TESTS}`);
55
+ console.log(`Options:\nBase Branch: ${BASE_BRANCH} \nLCOV Path: ${LCOV_PATH} \nCoverage Limit: ${COVERAGE_LIMIT} \nShow Covered Lines: ${SHOW_COVERED} \nMode: ${MODE} \nMax Depth: ${MAX_DEPTH}`);
20
56
 
21
57
  const changedFiles = getChangedFiles(BASE_BRANCH);
22
- runRelatedTests(changedFiles, SHALLOW_TESTS);
58
+ runRelatedTests(changedFiles, MODE, MAX_DEPTH);
23
59
  reportUncoveredChangedLines(changedFiles, LCOV_PATH, BASE_BRANCH, COVERAGE_LIMIT, SHOW_COVERED);
24
60
  } catch (error) {
25
61
  console.error('❌ An unexpected error occurred:', error.message || error);
@@ -50,38 +86,121 @@ function getChangedFiles(BASE_BRANCH) {
50
86
  }
51
87
  }
52
88
 
53
- function runRelatedTests(files, runTestsOnly) {
89
+ function runRelatedTests(files, mode, maxDepth) {
54
90
  if (files.length === 0) {
55
91
  console.log('✅ No changed source files found.');
56
-
57
92
  exit(0);
58
93
  }
59
94
 
60
- let runRelatedFilesArgs = '';
61
- if (!runTestsOnly) {
62
- runRelatedFilesArgs = '--findRelatedTests';
95
+ console.log('🔍 Analyzing changed files for optimal test execution...');
96
+
97
+ // Separate source files and test files
98
+ const { sourceFiles, testFiles } = separateSourceAndTestFiles(files);
99
+
100
+ console.log(`\n📊 Changed files breakdown:`);
101
+ console.log(` Source files: ${sourceFiles.length}`);
102
+ console.log(` Test files: ${testFiles.length}`);
103
+ if (sourceFiles.length > 0) {
104
+ console.log(' Source file list:');
105
+ sourceFiles.forEach(file => console.log(` - ${file}`));
106
+ }
107
+ if (testFiles.length > 0) {
108
+ console.log(' Changed test file list:');
109
+ testFiles.forEach(file => console.log(` - ${file}`));
63
110
  }
64
111
 
65
- console.log('🧪 Running tests related to the changed files:\n', files.join('\n'));
112
+ // Find test files for changed source files
113
+ const testFilesToRun = new Set(testFiles);
114
+ const mappedTests = new Map(); // Track which tests map to which source files
115
+
116
+ sourceFiles.forEach(sourceFile => {
117
+ const relatedTests = findTestFilesForSource(sourceFile);
118
+ if (relatedTests.length > 0) {
119
+ console.log(` ✓ ${sourceFile} → ${relatedTests.length} test file(s)`);
120
+ relatedTests.forEach(test => {
121
+ testFilesToRun.add(test);
122
+ if (!mappedTests.has(test)) {
123
+ mappedTests.set(test, []);
124
+ }
125
+ mappedTests.get(test).push(sourceFile);
126
+ });
127
+ } else {
128
+ console.log(` ⚠ ${sourceFile} → No test file found`);
129
+ }
130
+ });
66
131
 
67
- // filter files to only those that are JavaScript or TypeScript files
68
- files = getJsOnlyFiles(files, runTestsOnly);
132
+ const finalTestFiles = Array.from(testFilesToRun);
69
133
 
70
- if (files.length === 0) {
71
- console.log('✅ No relevant files found for testing.');
72
-
134
+ if (finalTestFiles.length === 0) {
135
+ console.log('\n⚠️ No test files found to run.');
136
+ console.log('Consider creating test files for your changed source files.');
73
137
  exit(0);
74
138
  }
75
139
 
76
- // log files to be tested
77
- console.log('\nFiles to be tested:\n', files.join('\n'));
78
-
79
- const command = `npx jest ${runRelatedFilesArgs} --passWithNoTests --coverage ${files.join(' ')}`;
80
- try {
81
- execSync(command, { stdio: 'inherit' });
82
- } catch (err) {
83
- console.error('Error:', err.message || err);
84
- exit(1);
140
+ console.log(`\n🧪 Running ${finalTestFiles.length} test file(s):\n`, finalTestFiles.join('\n'));
141
+
142
+ if (mode === 'fast') {
143
+ console.log(`\n📝 Test strategy: fast (Direct execution, no Jest dependency traversal)`);
144
+ console.log(` Test files: ${finalTestFiles.length}`);
145
+ console.log(` Source files detected: ${sourceFiles.length}`);
146
+ console.log(' Files passed to Jest:');
147
+ finalTestFiles.forEach(file => console.log(` - ${file}`));
148
+ const command = `npx jest --passWithNoTests --coverage ${finalTestFiles.join(' ')}`;
149
+ console.log(` Jest command: ${command}`);
150
+
151
+ try {
152
+ execSync(command, { stdio: 'inherit' });
153
+ } catch (err) {
154
+ console.error('❌ Tests failed:', err.message || err);
155
+ exit(1);
156
+ }
157
+ } else if (mode === 'smart') {
158
+ console.log(`\n📝 Test strategy: smart (Combine source and mapped test files, plus reverse deps up to depth ${maxDepth})`);
159
+ console.log(` Test files: ${finalTestFiles.length}`);
160
+ console.log(` Source files for coverage: ${sourceFiles.length}`);
161
+ const { reverseDepsTests, debugResults } = findReverseDepsForSourceFiles(sourceFiles, maxDepth);
162
+ const uniqueAllFiles = new Set([...sourceFiles, ...finalTestFiles, ...reverseDepsTests]);
163
+ const allFiles = Array.from(uniqueAllFiles);
164
+ console.log(` Total files passed to Jest: ${allFiles.length}`);
165
+ if (reverseDepsTests.length > 0) {
166
+ console.log(` Test files for files that import changes (reverse deps): ${reverseDepsTests.length}`);
167
+ }
168
+ if (debugResults.length > 0) {
169
+ console.log(' Reverse dependency debug:');
170
+ debugResults.forEach(({ targetFile, importerCount, maxDepthReached, importers }) => {
171
+ console.log(` - ${targetFile}: importers=${importerCount}, maxDepthReached=${maxDepthReached}`);
172
+ importers.forEach(({ file, depth, importedBy }) => {
173
+ console.log(` depth=${depth} file=${file}${importedBy ? ` importedBy=${importedBy}` : ''}`);
174
+ });
175
+ });
176
+ }
177
+ console.log(' Files passed to Jest:');
178
+ allFiles.forEach(file => console.log(` - ${file}`));
179
+ const command = `npx jest --passWithNoTests --coverage ${allFiles.join(' ')}`;
180
+ console.log(` Jest command: ${command}`);
181
+
182
+ try {
183
+ execSync(command, { stdio: 'inherit' });
184
+ } catch (err) {
185
+ console.error('❌ Tests failed:', err.message || err);
186
+ exit(1);
187
+ }
188
+ } else {
189
+ console.log(`\n📝 Test strategy: full (Run mapped tests through Jest --findRelatedTests)`);
190
+ console.log(` Running tests for ${sourceFiles.length} source file(s) + ${testFiles.length} changed test(s)`);
191
+ console.log(` Test files in Jest command: ${finalTestFiles.length}`);
192
+ console.log(` ⚠️ If this expands to too many tests, switch to --mode smart`);
193
+ console.log(' Test files passed to Jest:');
194
+ finalTestFiles.forEach(file => console.log(` - ${file}`));
195
+ const command = `npx jest --findRelatedTests --passWithNoTests --coverage ${finalTestFiles.join(' ')}`;
196
+ console.log(` Jest command: ${command}`);
197
+
198
+ try {
199
+ execSync(command, { stdio: 'inherit' });
200
+ } catch (err) {
201
+ console.error('❌ Tests failed:', err.message || err);
202
+ exit(1);
203
+ }
85
204
  }
86
205
  }
87
206
 
@@ -102,7 +221,7 @@ function getChangedLines(filePath, BASE_BRANCH) {
102
221
  return lines;
103
222
  }
104
223
 
105
- function parseLcov(LCOV_PATH) {
224
+ export function parseLcov(LCOV_PATH) {
106
225
  const lcovRaw = fs.readFileSync(LCOV_PATH, 'utf8');
107
226
  const files = {};
108
227
  let currentFile = null;
@@ -110,11 +229,15 @@ function parseLcov(LCOV_PATH) {
110
229
  lcovRaw.split('\n').forEach(line => {
111
230
  if (line.startsWith('SF:')) {
112
231
  currentFile = path.resolve(line.substring(3).trim());
113
- files[currentFile] = new Set();
232
+ files[currentFile] = {
233
+ coverableLines: new Set(),
234
+ uncoveredLines: new Set()
235
+ };
114
236
  } else if (line.startsWith('DA:') && currentFile) {
115
237
  const [lineNo, hits] = line.substring(3).split(',').map(Number);
238
+ files[currentFile].coverableLines.add(lineNo);
116
239
  if (hits === 0) {
117
- files[currentFile].add(lineNo);
240
+ files[currentFile].uncoveredLines.add(lineNo);
118
241
  }
119
242
  }
120
243
  });
@@ -122,13 +245,77 @@ function parseLcov(LCOV_PATH) {
122
245
  return files;
123
246
  }
124
247
 
248
+ export function classifyChangedLineCoverage(changedLines, fileCoverage) {
249
+ const coverage = fileCoverage || {
250
+ coverableLines: new Set(),
251
+ uncoveredLines: new Set()
252
+ };
253
+
254
+ const coveredLines = [];
255
+ const uncoveredLines = [];
256
+
257
+ changedLines.forEach(line => {
258
+ // Only classify lines that appear in LCOV (are coverable).
259
+ // Lines not in LCOV (imports, non-executable lines) are filtered out.
260
+ if (!coverage.coverableLines.has(line)) {
261
+ return;
262
+ }
263
+
264
+ if (coverage.uncoveredLines.has(line)) {
265
+ uncoveredLines.push(line);
266
+ } else {
267
+ coveredLines.push(line);
268
+ }
269
+ });
270
+
271
+ return {
272
+ coveredLines,
273
+ uncoveredLines
274
+ };
275
+ }
276
+
277
+ export function summarizeCoverageResult(totalChanged, totalNotCovered, coverageLimit) {
278
+ if (totalChanged === 0) {
279
+ return {
280
+ overallCoverage: null,
281
+ passed: true,
282
+ icon: '✅'
283
+ };
284
+ }
285
+
286
+ const overallCoverage = ((totalChanged - totalNotCovered) / totalChanged) * 100;
287
+ const passed = overallCoverage >= coverageLimit;
288
+
289
+ return {
290
+ overallCoverage,
291
+ passed,
292
+ icon: passed ? '✅' : '🚨'
293
+ };
294
+ }
295
+
296
+ export function formatMissedLinesSummary(uncoveredByFile) {
297
+ if (uncoveredByFile.length === 0) {
298
+ return [];
299
+ }
300
+
301
+ return [
302
+ '',
303
+ 'Missed changed lines by file:',
304
+ ...uncoveredByFile.flatMap(({ filePath, lines }) => {
305
+ const absolutePath = path.resolve(filePath);
306
+
307
+ return lines.map(line => ` - ${absolutePath}:${line}`);
308
+ })
309
+ ];
310
+ }
311
+
125
312
  function reportUncoveredChangedLines(changedFiles, LCOV_PATH, BASE_BRANCH, COVERAGE_LIMIT, SHOW_COVERED) {
126
313
  if (!fs.existsSync(LCOV_PATH)) {
127
314
  console.error('❌ lcov.info not found. Make sure coverage ran correctly.');
128
315
  process.exit(1);
129
316
  }
130
317
 
131
- const uncoveredLines = parseLcov(LCOV_PATH);
318
+ const coverageByFile = parseLcov(LCOV_PATH);
132
319
 
133
320
  console.log(`\n🔍 Checking coverage of changed lines vs branch: ${BASE_BRANCH}\n`);
134
321
 
@@ -142,48 +329,61 @@ function reportUncoveredChangedLines(changedFiles, LCOV_PATH, BASE_BRANCH, COVER
142
329
  console.log('Files with changed lines:', changedFiles.join('\n'));
143
330
 
144
331
  let totalChanged = 0;
145
- let totalUncovered = 0;
332
+ let totalNotCovered = 0;
333
+ const uncoveredByFile = [];
146
334
 
147
335
  changedFiles.forEach(relPath => {
148
336
  const absPath = path.resolve(relPath);
149
- if (!uncoveredLines[absPath]) {
150
- console.log(`⚠️ No coverage info for: ${absPath}`);
337
+ const addedLines = getChangedLines(relPath, BASE_BRANCH);
338
+
339
+ if (addedLines.length === 0) {
340
+ console.log(`ℹ️ ${absPath} - No changed lines detected.`);
151
341
  return;
152
342
  }
153
343
 
154
- const addedLines = getChangedLines(relPath, BASE_BRANCH);
155
- const fileUncovered = uncoveredLines[absPath];
344
+ const fileCoverage = coverageByFile[absPath];
345
+ if (!fileCoverage) {
346
+ console.log(`⚠️ No coverage info for: ${absPath}`);
347
+ }
156
348
 
157
- const uncoveredInDiff = addedLines.filter(line => fileUncovered.has(line));
158
- const coveredInDiff = addedLines.length - uncoveredInDiff.length;
349
+ const {
350
+ coveredLines,
351
+ uncoveredLines
352
+ } = classifyChangedLineCoverage(addedLines, fileCoverage);
353
+ const trackedChangedLines = coveredLines.length + uncoveredLines.length;
159
354
 
160
- totalChanged += addedLines.length;
161
- totalUncovered += uncoveredInDiff.length;
355
+ totalChanged += trackedChangedLines;
356
+ totalNotCovered += uncoveredLines.length;
162
357
 
163
- if (addedLines.length === 0) {
164
- console.log(`ℹ️ ${absPath} - No changed lines detected.`);
165
- return;
358
+ if (uncoveredLines.length > 0) {
359
+ uncoveredByFile.push({
360
+ filePath: relPath,
361
+ lines: uncoveredLines
362
+ });
166
363
  }
167
364
 
168
- if (uncoveredInDiff.length > 0) {
169
- console.log(`🚨 ${absPath} - Uncovered changed lines: [${uncoveredInDiff.join(', ')}]`);
170
- } else {
365
+ if (uncoveredLines.length > 0) {
366
+ console.log(`🚨 ${absPath} - Uncovered changed lines: [${uncoveredLines.join(', ')}]`);
367
+ } else if (trackedChangedLines > 0) {
171
368
  console.log(`✅ ${absPath} - All changed lines are covered`);
172
369
  }
173
- // Display covered lines if option is enabled
174
- const coveredLines = addedLines.filter(line => !fileUncovered.has(line));
175
- console.log(` Total changed lines: ${addedLines.length}, Covered: ${coveredInDiff}, Uncovered: ${uncoveredInDiff.length}`);
176
- if (SHOW_COVERED) {
370
+
371
+ console.log(` Total coverable changed lines: ${trackedChangedLines}, Covered: ${coveredLines.length}, Uncovered: ${uncoveredLines.length}`)
372
+ if (SHOW_COVERED && coveredLines.length > 0) {
177
373
  console.log(` Covered lines: [${coveredLines.join(', ')}]`);
178
374
  }
179
- console.log(` Coverage for changed lines: ${((coveredInDiff / addedLines.length) * 100).toFixed(2)}%`);
375
+ if (trackedChangedLines > 0) {
376
+ console.log(` Coverage for changed lines: ${((coveredLines.length / trackedChangedLines) * 100).toFixed(2)}%`);
377
+ } else {
378
+ console.log(` No coverable lines in this file's changed lines (e.g., imports, comments).`);
379
+ }
180
380
  });
181
381
 
182
382
  // Cumulative coverage check
183
383
  if (totalChanged > 0) {
184
- const overallCoverage = (((totalChanged - totalUncovered) / totalChanged) * 100).toFixed(2);
185
- console.log(`\n🔢 Overall coverage for all changed lines: ${overallCoverage}% >>> ${COVERAGE_LIMIT}% `);
186
- console.log(`Uncovered Lines: ${totalUncovered} out of ${totalChanged} changed lines`);
187
-
384
+ const { overallCoverage, icon } = summarizeCoverageResult(totalChanged, totalNotCovered, COVERAGE_LIMIT);
385
+ console.log(`\n${icon} Overall coverage for all changed lines: ${overallCoverage.toFixed(2)}% (limit: ${COVERAGE_LIMIT}%)`);
386
+ console.log(`Not covered lines: ${totalNotCovered} out of ${totalChanged} changed lines`);
387
+ formatMissedLinesSummary(uncoveredByFile).forEach(line => console.log(line));
188
388
  }
189
389
  }
@@ -0,0 +1,113 @@
1
+ import fs from 'fs';
2
+ import os from 'os';
3
+ import path from 'path';
4
+ import {
5
+ classifyChangedLineCoverage,
6
+ formatMissedLinesSummary,
7
+ parseLcov,
8
+ summarizeCoverageResult
9
+ } from './cli.js';
10
+
11
+ function writeLcovFixture(records) {
12
+ const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'mo3ta-coverage-'));
13
+ const sourceFile = path.join(tempDir, 'src/example.js');
14
+ const lcovFile = path.join(tempDir, 'lcov.info');
15
+
16
+ fs.mkdirSync(path.dirname(sourceFile), { recursive: true });
17
+ fs.writeFileSync(sourceFile, 'const x = 1;\nconst y = 2;\n');
18
+ fs.writeFileSync(
19
+ lcovFile,
20
+ [
21
+ 'TN:',
22
+ `SF:${sourceFile}`,
23
+ ...records,
24
+ 'end_of_record'
25
+ ].join('\n')
26
+ );
27
+
28
+ return { sourceFile, lcovFile };
29
+ }
30
+
31
+ describe('parseLcov', () => {
32
+ it('records both coverableLines and uncoveredLines', () => {
33
+ const { sourceFile, lcovFile } = writeLcovFixture(['DA:10,1', 'DA:11,0']);
34
+
35
+ const result = parseLcov(lcovFile);
36
+
37
+ expect(result[sourceFile].coverableLines.has(10)).toBe(true);
38
+ expect(result[sourceFile].coverableLines.has(11)).toBe(true);
39
+ expect(result[sourceFile].uncoveredLines.has(10)).toBe(false);
40
+ expect(result[sourceFile].uncoveredLines.has(11)).toBe(true);
41
+ });
42
+ });
43
+
44
+ describe('classifyChangedLineCoverage', () => {
45
+ it('filters out changed lines not in LCOV (like imports)', () => {
46
+ const { sourceFile, lcovFile } = writeLcovFixture(['DA:10,1']);
47
+ const coverage = parseLcov(lcovFile)[sourceFile];
48
+
49
+ const result = classifyChangedLineCoverage([11, 12, 13, 14], coverage);
50
+
51
+ expect(result.coveredLines).toEqual([]);
52
+ expect(result.uncoveredLines).toEqual([]);
53
+ });
54
+
55
+ it('ignores changed lines with no LCOV entry and classifies rest as covered or uncovered', () => {
56
+ const { sourceFile, lcovFile } = writeLcovFixture(['DA:10,3', 'DA:11,0']);
57
+ const coverage = parseLcov(lcovFile)[sourceFile];
58
+
59
+ const result = classifyChangedLineCoverage([10, 11, 12, 13], coverage);
60
+
61
+ expect(result.coveredLines).toEqual([10]);
62
+ expect(result.uncoveredLines).toEqual([11]);
63
+ });
64
+
65
+ it('keeps existing behavior for normal covered and uncovered LCOV lines', () => {
66
+ const { sourceFile, lcovFile } = writeLcovFixture(['DA:20,5', 'DA:21,0']);
67
+ const coverage = parseLcov(lcovFile)[sourceFile];
68
+
69
+ const result = classifyChangedLineCoverage([20, 21], coverage);
70
+
71
+ expect(result.coveredLines).toEqual([20]);
72
+ expect(result.uncoveredLines).toEqual([21]);
73
+ });
74
+ });
75
+
76
+ describe('summarizeCoverageResult', () => {
77
+ it('passes when overall coverage equals the configured limit', () => {
78
+ const result = summarizeCoverageResult(5, 1, 80);
79
+
80
+ expect(result.overallCoverage).toBe(80);
81
+ expect(result.passed).toBe(true);
82
+ expect(result.icon).toBe('✅');
83
+ });
84
+
85
+ it('fails when overall coverage is below the configured limit', () => {
86
+ const result = summarizeCoverageResult(5, 2, 80);
87
+
88
+ expect(result.overallCoverage).toBe(60);
89
+ expect(result.passed).toBe(false);
90
+ expect(result.icon).toBe('🚨');
91
+ });
92
+ });
93
+
94
+ describe('formatMissedLinesSummary', () => {
95
+ it('formats uncovered files and lines for the final summary', () => {
96
+ const result = formatMissedLinesSummary([
97
+ { filePath: 'src/a.js', lines: [10, 11] },
98
+ { filePath: 'src/b.js', lines: [7] }
99
+ ]);
100
+
101
+ expect(result).toEqual([
102
+ '',
103
+ 'Missed changed lines by file:',
104
+ ` - ${path.resolve('src/a.js')}:10`,
105
+ ` - ${path.resolve('src/a.js')}:11`,
106
+ ` - ${path.resolve('src/b.js')}:7`
107
+ ]);
108
+ });
109
+
110
+ it('returns no summary lines when no files have missed lines', () => {
111
+ expect(formatMissedLinesSummary([])).toEqual([]);
112
+ });
113
+ });