mo3ta-coverage 1.0.8 → 1.0.11

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
@@ -5,6 +5,7 @@ import { Command } from 'commander';
5
5
  import { main } from './src/cli.js';
6
6
  import fs from 'fs';
7
7
  import path from 'path';
8
+ import { verifyBaseBranchExists } from './src/gitUtils.js';
8
9
 
9
10
  const CONFIG_PATH = path.resolve(process.cwd(), '.mo3ta-coverage.json');
10
11
 
@@ -33,31 +34,37 @@ program
33
34
  .option('--lcov <path>', 'Path to lcov.info file generated by test coverage tools', 'coverage/lcov.info')
34
35
  .option('--limit <percent>', 'Minimum required coverage percentage for all changed lines (e.g., 80)', '80')
35
36
  .option('--showCovered <bool>', 'Show covered changed lines in the output', false)
36
- .option('--shallowTests <bool>', 'Run test files only without deep in tests tree', true)
37
- .passThroughOptions()
38
- .enablePositionalOptions();
37
+ .option('--mode <mode>', 'Execution mode: fast, smart, or full', 'smart')
38
+ .enablePositionalOptions(); // used to allow using same options in subcommands
39
39
 
40
40
 
41
41
  program
42
42
  .command('config')
43
43
  .description('Set or get configuration options')
44
44
  .option('--base <branch>', 'Set default base branch')
45
- .option('--shallowTests <bool>', 'Set default shallowTests value (true/false)')
45
+ .option('--mode <mode>', 'Set default mode (fast/smart/full)')
46
46
  .action((opts) => {
47
47
  let config = readConfig();
48
48
 
49
49
  let updated = false;
50
50
 
51
51
  if (opts.base) {
52
+ verifyBaseBranchExists(opts.base);
53
+
52
54
  config.base = opts.base;
53
55
  updated = true;
54
56
  console.log(`Default base branch set to: ${opts.base}`);
55
57
  }
56
58
 
57
- if (typeof opts.shallowTests !== 'undefined') {
58
- config.shallowTests = opts.shallowTests === 'true' || opts.shallowTests === true;
59
+ if (opts.mode !== undefined) {
60
+ const normalizedMode = String(opts.mode).toLowerCase();
61
+ if (!['fast', 'smart', 'full'].includes(normalizedMode)) {
62
+ console.error(`Invalid mode: ${opts.mode}. Expected one of: fast, smart, full.`);
63
+ process.exit(1);
64
+ }
65
+ config.mode = normalizedMode;
59
66
  updated = true;
60
- console.log(`Default shallowTests set to: ${config.shallowTests}`);
67
+ console.log(`Default mode set to: ${config.mode}`);
61
68
  }
62
69
  if (updated) {
63
70
  writeConfig(config);
@@ -72,20 +79,23 @@ program
72
79
  program.action((opts) => {
73
80
  const config = readConfig();
74
81
  const options = program.opts();
75
- console.log(`Current config: ${JSON.stringify(config, null, 2)}`);
76
- console.log(`Current options: ${JSON.stringify(options, null, 2)}`);
77
- console.log(`Current wqwqw: ${JSON.stringify(opts, null, 2)}`);
78
-
82
+
79
83
  // Use config base if not provided in CLI
80
84
  if (!options.base && config.base) {
81
85
  options.base = config.base;
82
86
  } else if (!options.base) {
83
87
  options.base = 'origin/main';
84
88
  }
85
- // Use config shallowTests if not provided in CLI
86
- console.log(`Using shallowTests: ${options.shallowTests} ${config.shallowTests}`);
87
89
 
88
- options.shallowTests = config.shallowTests ?? options.shallowTests;
90
+ if (!options.mode && config.mode) {
91
+ options.mode = config.mode;
92
+ }
93
+
94
+ options.mode = String(options.mode || 'smart').toLowerCase();
95
+ if (!['fast', 'smart', 'full'].includes(options.mode)) {
96
+ console.error(`Invalid mode: ${options.mode}. Expected one of: fast, smart, full.`);
97
+ process.exit(1);
98
+ }
89
99
 
90
100
  console.log(`Final options: ${JSON.stringify(options, null, 2)}`);
91
101
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mo3ta-coverage",
3
- "version": "1.0.8",
3
+ "version": "1.0.11",
4
4
  "description": "Run tests and report uncovered changed lines in a PR",
5
5
  "main": "index.js",
6
6
  "bin": {
package/src/cli.js CHANGED
@@ -2,97 +2,158 @@ import { execSync } from 'child_process';
2
2
  import fs from 'fs';
3
3
  import path from 'path';
4
4
  import { exit } from 'process';
5
+ import { verifyBaseBranchExists, verifyGitRepoExists } from './gitUtils.js';
6
+ import { getJsOnlyFiles, separateSourceAndTestFiles, findTestFilesForSource } from './fileUtils.js';
5
7
 
6
8
  export function main(options) {
7
- // Check if current directory is a git repository
8
9
  try {
9
- execSync('git rev-parse --is-inside-work-tree', { stdio: 'ignore' });
10
- } catch (err) {
11
- console.error(`❌ Not a git repository. Please run this tool inside a git repo. ${err.message}`);
12
-
10
+ // Check if current directory is a git repository
11
+ verifyGitRepoExists();
12
+
13
+ const BASE_BRANCH = options.base;
14
+ const LCOV_PATH = options.lcov;
15
+ const COVERAGE_LIMIT = parseFloat(options.limit);
16
+ const SHOW_COVERED = options.showCovered === true || options.showCovered === 'true';
17
+ const MODE = options.mode;
18
+
19
+ console.log(`Options:\nBase Branch: ${BASE_BRANCH} \nLCOV Path: ${LCOV_PATH} \nCoverage Limit: ${COVERAGE_LIMIT} \nShow Covered Lines: ${SHOW_COVERED} \nMode: ${MODE}`);
20
+
21
+ const changedFiles = getChangedFiles(BASE_BRANCH);
22
+ runRelatedTests(changedFiles, MODE);
23
+ reportUncoveredChangedLines(changedFiles, LCOV_PATH, BASE_BRANCH, COVERAGE_LIMIT, SHOW_COVERED);
24
+ } catch (error) {
25
+ console.error('❌ An unexpected error occurred:', error.message || error);
13
26
  exit(1);
14
27
  }
15
-
16
-
17
- const BASE_BRANCH = options.base;
18
- const LCOV_PATH = options.lcov;
19
- const COVERAGE_LIMIT = parseFloat(options.limit);
20
- const SHOW_COVERED = options.showCovered === true || options.showCovered === 'true';
21
- const SHALLOW_TESTS = options.shallowTests === true || options.shallowTests === 'true';
22
-
23
- console.log(`Options:\nBase Branch: ${BASE_BRANCH} \nLCOV Path: ${LCOV_PATH} \nCoverage Limit: ${COVERAGE_LIMIT} \nShow Covered Lines: ${SHOW_COVERED} \nShallow Tests: ${SHALLOW_TESTS}`);
24
-
25
- const changedFiles = getChangedFiles(BASE_BRANCH);
26
- runRelatedTests(changedFiles, SHALLOW_TESTS);
27
- reportUncoveredChangedLines(changedFiles, LCOV_PATH, BASE_BRANCH, COVERAGE_LIMIT, SHOW_COVERED);
28
-
29
28
  }
30
29
 
30
+
31
31
  function getChangedFiles(BASE_BRANCH) {
32
+ // Check if BASE_BRANCH exists
33
+ verifyBaseBranchExists(BASE_BRANCH);
34
+
32
35
  const command = `(
33
36
  git log --pretty=format: --name-only --diff-filter=AM --author="$(git config user.name)" $(git merge-base HEAD ${BASE_BRANCH})..HEAD
34
37
  git diff --name-only --diff-filter=AM
35
38
  git diff --cached --name-only --diff-filter=AM
36
39
  ) | sort -u`;
37
40
 
38
- const output = execSync(command).toString();
39
-
40
- return output
41
- .split('\n')
42
- .filter(f => f.trim().length > 0 && f.match(/\.(js|ts|jsx|tsx)$/));
41
+ try {
42
+ const output = execSync(command).toString();
43
+ console.log(`Changed files:\n${output}`);
44
+ return output
45
+ .split('\n')
46
+ .filter(f => f.trim().length > 0 && f.match(/\.(js|ts|jsx|tsx)$/));
47
+ } catch (error) {
48
+ console.error('Error getting changed files:', error.message || error);
49
+ return [];
50
+ }
43
51
  }
44
52
 
45
- function runRelatedTests(files, runTestsOnly) {
53
+ function runRelatedTests(files, mode) {
46
54
  if (files.length === 0) {
47
55
  console.log('✅ No changed source files found.');
48
-
49
56
  exit(0);
50
57
  }
51
58
 
52
- let runRelatedFilesArgs = '';
53
- if (!runTestsOnly) {
54
- runRelatedFilesArgs = '--findRelatedTests';
59
+ console.log('🔍 Analyzing changed files for optimal test execution...');
60
+
61
+ // Separate source files and test files
62
+ const { sourceFiles, testFiles } = separateSourceAndTestFiles(files);
63
+
64
+ console.log(`\n📊 Changed files breakdown:`);
65
+ console.log(` Source files: ${sourceFiles.length}`);
66
+ console.log(` Test files: ${testFiles.length}`);
67
+ if (sourceFiles.length > 0) {
68
+ console.log(' Source file list:');
69
+ sourceFiles.forEach(file => console.log(` - ${file}`));
70
+ }
71
+ if (testFiles.length > 0) {
72
+ console.log(' Changed test file list:');
73
+ testFiles.forEach(file => console.log(` - ${file}`));
55
74
  }
56
75
 
57
- console.log('🧪 Running tests related to the changed files:\n', files.join('\n'));
76
+ // Find test files for changed source files
77
+ const testFilesToRun = new Set(testFiles);
78
+ const mappedTests = new Map(); // Track which tests map to which source files
79
+
80
+ sourceFiles.forEach(sourceFile => {
81
+ const relatedTests = findTestFilesForSource(sourceFile);
82
+ if (relatedTests.length > 0) {
83
+ console.log(` ✓ ${sourceFile} → ${relatedTests.length} test file(s)`);
84
+ relatedTests.forEach(test => {
85
+ testFilesToRun.add(test);
86
+ if (!mappedTests.has(test)) {
87
+ mappedTests.set(test, []);
88
+ }
89
+ mappedTests.get(test).push(sourceFile);
90
+ });
91
+ } else {
92
+ console.log(` ⚠ ${sourceFile} → No test file found`);
93
+ }
94
+ });
58
95
 
59
- // filter files to only those that are JavaScript or TypeScript files
60
- files = getJsOnlyFiles(files, runTestsOnly);
96
+ const finalTestFiles = Array.from(testFilesToRun);
61
97
 
62
- if (files.length === 0) {
63
- console.log('✅ No relevant files found for testing.');
64
-
98
+ if (finalTestFiles.length === 0) {
99
+ console.log('\n⚠️ No test files found to run.');
100
+ console.log('Consider creating test files for your changed source files.');
65
101
  exit(0);
66
102
  }
67
103
 
68
- // log files to be tested
69
- console.log('\nFiles to be tested:', files.join('\n'));
70
-
71
- const command = `npx jest ${runRelatedFilesArgs} --passWithNoTests --coverage ${files.join(' ')}`;
72
- try {
73
- execSync(command, { stdio: 'inherit' });
74
- } catch (err) {
75
- console.error('Error:', err.message || err);
76
- exit(1);
104
+ console.log(`\n🧪 Running ${finalTestFiles.length} test file(s):\n`, finalTestFiles.join('\n'));
105
+
106
+ if (mode === 'fast') {
107
+ console.log(`\n📝 Test strategy: fast (Direct execution, no Jest dependency traversal)`);
108
+ console.log(` Test files: ${finalTestFiles.length}`);
109
+ console.log(` Source files detected: ${sourceFiles.length}`);
110
+ console.log(' Files passed to Jest:');
111
+ finalTestFiles.forEach(file => console.log(` - ${file}`));
112
+ const command = `npx jest --passWithNoTests --coverage ${finalTestFiles.join(' ')}`;
113
+ console.log(` Jest command: ${command}`);
114
+
115
+ try {
116
+ execSync(command, { stdio: 'inherit' });
117
+ } catch (err) {
118
+ console.error('❌ Tests failed:', err.message || err);
119
+ exit(1);
120
+ }
121
+ } else if (mode === 'smart') {
122
+ console.log(`\n📝 Test strategy: smart (Combine source and mapped test files, no Jest dependency traversal)`);
123
+ console.log(` Test files: ${finalTestFiles.length}`);
124
+ console.log(` Source files for coverage: ${sourceFiles.length}`);
125
+ const allFiles = [...sourceFiles, ...finalTestFiles];
126
+ console.log(` Total files passed to Jest: ${allFiles.length}`);
127
+ console.log(' Files passed to Jest:');
128
+ allFiles.forEach(file => console.log(` - ${file}`));
129
+ const command = `npx jest --passWithNoTests --coverage ${allFiles.join(' ')}`;
130
+ console.log(` Jest command: ${command}`);
131
+
132
+ try {
133
+ execSync(command, { stdio: 'inherit' });
134
+ } catch (err) {
135
+ console.error('❌ Tests failed:', err.message || err);
136
+ exit(1);
137
+ }
138
+ } else {
139
+ console.log(`\n📝 Test strategy: full (Run mapped tests through Jest --findRelatedTests)`);
140
+ console.log(` Running tests for ${sourceFiles.length} source file(s) + ${testFiles.length} changed test(s)`);
141
+ console.log(` Test files in Jest command: ${finalTestFiles.length}`);
142
+ console.log(` ⚠️ If this expands to too many tests, switch to --mode smart`);
143
+ console.log(' Test files passed to Jest:');
144
+ finalTestFiles.forEach(file => console.log(` - ${file}`));
145
+ const command = `npx jest --findRelatedTests --passWithNoTests --coverage ${finalTestFiles.join(' ')}`;
146
+ console.log(` Jest command: ${command}`);
147
+
148
+ try {
149
+ execSync(command, { stdio: 'inherit' });
150
+ } catch (err) {
151
+ console.error('❌ Tests failed:', err.message || err);
152
+ exit(1);
153
+ }
77
154
  }
78
155
  }
79
156
 
80
- function getJsOnlyFiles(files, runTestsOnly) {
81
- // Only include source code files, exclude test, config, and json files
82
- return files.filter(f => {
83
- // Exclude test files
84
- if (f.match(/(\.test|\.spec)\.(js|ts|jsx|tsx)$/)) return false;
85
- // skip non test files when running only test files
86
- if (runTestsOnly) return false;
87
- // Exclude config files
88
- if (f.match(/(jest|babel|webpack|tsconfig|eslint|prettier|rollup|vite|package)\.(js|ts|json)$/)) return false;
89
- // Exclude json files
90
- if (f.endsWith('.json')) return false;
91
- // Only include code files
92
- return f.endsWith('.js') || f.endsWith('.ts') || f.endsWith('.jsx') || f.endsWith('.tsx');
93
- });
94
- }
95
-
96
157
  function getChangedLines(filePath, BASE_BRANCH) {
97
158
  const diff = execSync(`git diff -U0 ${BASE_BRANCH} -- ${filePath}`).toString();
98
159
  const lines = [];
@@ -110,7 +171,7 @@ function getChangedLines(filePath, BASE_BRANCH) {
110
171
  return lines;
111
172
  }
112
173
 
113
- function parseLcov(LCOV_PATH) {
174
+ export function parseLcov(LCOV_PATH) {
114
175
  const lcovRaw = fs.readFileSync(LCOV_PATH, 'utf8');
115
176
  const files = {};
116
177
  let currentFile = null;
@@ -118,11 +179,15 @@ function parseLcov(LCOV_PATH) {
118
179
  lcovRaw.split('\n').forEach(line => {
119
180
  if (line.startsWith('SF:')) {
120
181
  currentFile = path.resolve(line.substring(3).trim());
121
- files[currentFile] = new Set();
182
+ files[currentFile] = {
183
+ coverableLines: new Set(),
184
+ uncoveredLines: new Set()
185
+ };
122
186
  } else if (line.startsWith('DA:') && currentFile) {
123
187
  const [lineNo, hits] = line.substring(3).split(',').map(Number);
188
+ files[currentFile].coverableLines.add(lineNo);
124
189
  if (hits === 0) {
125
- files[currentFile].add(lineNo);
190
+ files[currentFile].uncoveredLines.add(lineNo);
126
191
  }
127
192
  }
128
193
  });
@@ -130,13 +195,77 @@ function parseLcov(LCOV_PATH) {
130
195
  return files;
131
196
  }
132
197
 
198
+ export function classifyChangedLineCoverage(changedLines, fileCoverage) {
199
+ const coverage = fileCoverage || {
200
+ coverableLines: new Set(),
201
+ uncoveredLines: new Set()
202
+ };
203
+
204
+ const coveredLines = [];
205
+ const uncoveredLines = [];
206
+
207
+ changedLines.forEach(line => {
208
+ // Only classify lines that appear in LCOV (are coverable).
209
+ // Lines not in LCOV (imports, non-executable lines) are filtered out.
210
+ if (!coverage.coverableLines.has(line)) {
211
+ return;
212
+ }
213
+
214
+ if (coverage.uncoveredLines.has(line)) {
215
+ uncoveredLines.push(line);
216
+ } else {
217
+ coveredLines.push(line);
218
+ }
219
+ });
220
+
221
+ return {
222
+ coveredLines,
223
+ uncoveredLines
224
+ };
225
+ }
226
+
227
+ export function summarizeCoverageResult(totalChanged, totalNotCovered, coverageLimit) {
228
+ if (totalChanged === 0) {
229
+ return {
230
+ overallCoverage: null,
231
+ passed: true,
232
+ icon: '✅'
233
+ };
234
+ }
235
+
236
+ const overallCoverage = ((totalChanged - totalNotCovered) / totalChanged) * 100;
237
+ const passed = overallCoverage >= coverageLimit;
238
+
239
+ return {
240
+ overallCoverage,
241
+ passed,
242
+ icon: passed ? '✅' : '🚨'
243
+ };
244
+ }
245
+
246
+ export function formatMissedLinesSummary(uncoveredByFile) {
247
+ if (uncoveredByFile.length === 0) {
248
+ return [];
249
+ }
250
+
251
+ return [
252
+ '',
253
+ 'Missed changed lines by file:',
254
+ ...uncoveredByFile.flatMap(({ filePath, lines }) => {
255
+ const absolutePath = path.resolve(filePath);
256
+
257
+ return lines.map(line => ` - ${absolutePath}:${line}`);
258
+ })
259
+ ];
260
+ }
261
+
133
262
  function reportUncoveredChangedLines(changedFiles, LCOV_PATH, BASE_BRANCH, COVERAGE_LIMIT, SHOW_COVERED) {
134
263
  if (!fs.existsSync(LCOV_PATH)) {
135
264
  console.error('❌ lcov.info not found. Make sure coverage ran correctly.');
136
265
  process.exit(1);
137
266
  }
138
267
 
139
- const uncoveredLines = parseLcov(LCOV_PATH);
268
+ const coverageByFile = parseLcov(LCOV_PATH);
140
269
 
141
270
  console.log(`\n🔍 Checking coverage of changed lines vs branch: ${BASE_BRANCH}\n`);
142
271
 
@@ -150,46 +279,61 @@ function reportUncoveredChangedLines(changedFiles, LCOV_PATH, BASE_BRANCH, COVER
150
279
  console.log('Files with changed lines:', changedFiles.join('\n'));
151
280
 
152
281
  let totalChanged = 0;
153
- let totalUncovered = 0;
282
+ let totalNotCovered = 0;
283
+ const uncoveredByFile = [];
154
284
 
155
285
  changedFiles.forEach(relPath => {
156
286
  const absPath = path.resolve(relPath);
157
- if (!uncoveredLines[absPath]) {
158
- console.log(`⚠️ No coverage info for: ${absPath}`);
287
+ const addedLines = getChangedLines(relPath, BASE_BRANCH);
288
+
289
+ if (addedLines.length === 0) {
290
+ console.log(`ℹ️ ${absPath} - No changed lines detected.`);
159
291
  return;
160
292
  }
161
293
 
162
- const addedLines = getChangedLines(relPath, BASE_BRANCH);
163
- const fileUncovered = uncoveredLines[absPath];
294
+ const fileCoverage = coverageByFile[absPath];
295
+ if (!fileCoverage) {
296
+ console.log(`⚠️ No coverage info for: ${absPath}`);
297
+ }
164
298
 
165
- const uncoveredInDiff = addedLines.filter(line => fileUncovered.has(line));
166
- const coveredInDiff = addedLines.length - uncoveredInDiff.length;
299
+ const {
300
+ coveredLines,
301
+ uncoveredLines
302
+ } = classifyChangedLineCoverage(addedLines, fileCoverage);
303
+ const trackedChangedLines = coveredLines.length + uncoveredLines.length;
167
304
 
168
- totalChanged += addedLines.length;
169
- totalUncovered += uncoveredInDiff.length;
305
+ totalChanged += trackedChangedLines;
306
+ totalNotCovered += uncoveredLines.length;
170
307
 
171
- if (addedLines.length === 0) {
172
- console.log(`ℹ️ ${absPath} - No changed lines detected.`);
173
- return;
308
+ if (uncoveredLines.length > 0) {
309
+ uncoveredByFile.push({
310
+ filePath: relPath,
311
+ lines: uncoveredLines
312
+ });
174
313
  }
175
314
 
176
- if (uncoveredInDiff.length > 0) {
177
- console.log(`🚨 ${absPath} - Uncovered changed lines: [${uncoveredInDiff.join(', ')}]`);
178
- } else {
315
+ if (uncoveredLines.length > 0) {
316
+ console.log(`🚨 ${absPath} - Uncovered changed lines: [${uncoveredLines.join(', ')}]`);
317
+ } else if (trackedChangedLines > 0) {
179
318
  console.log(`✅ ${absPath} - All changed lines are covered`);
180
319
  }
181
- // Display covered lines if option is enabled
182
- const coveredLines = addedLines.filter(line => !fileUncovered.has(line));
183
- console.log(` Total changed lines: ${addedLines.length}, Covered: ${coveredInDiff}, Uncovered: ${uncoveredInDiff.length}`);
184
- if (SHOW_COVERED) {
320
+
321
+ console.log(` Total coverable changed lines: ${trackedChangedLines}, Covered: ${coveredLines.length}, Uncovered: ${uncoveredLines.length}`)
322
+ if (SHOW_COVERED && coveredLines.length > 0) {
185
323
  console.log(` Covered lines: [${coveredLines.join(', ')}]`);
186
324
  }
187
- console.log(` Coverage for changed lines: ${((coveredInDiff / addedLines.length) * 100).toFixed(2)}%`);
325
+ if (trackedChangedLines > 0) {
326
+ console.log(` Coverage for changed lines: ${((coveredLines.length / trackedChangedLines) * 100).toFixed(2)}%`);
327
+ } else {
328
+ console.log(` No coverable lines in this file's changed lines (e.g., imports, comments).`);
329
+ }
188
330
  });
189
331
 
190
332
  // Cumulative coverage check
191
333
  if (totalChanged > 0) {
192
- const overallCoverage = (((totalChanged - totalUncovered) / totalChanged) * 100).toFixed(2);
193
- console.log(`\n🔢 Overall coverage for all changed lines: ${overallCoverage}% limit is ${COVERAGE_LIMIT}% with Uncovered: ${totalUncovered} (${totalChanged})`);
334
+ const { overallCoverage, icon } = summarizeCoverageResult(totalChanged, totalNotCovered, COVERAGE_LIMIT);
335
+ console.log(`\n${icon} Overall coverage for all changed lines: ${overallCoverage.toFixed(2)}% (limit: ${COVERAGE_LIMIT}%)`);
336
+ console.log(`Not covered lines: ${totalNotCovered} out of ${totalChanged} changed lines`);
337
+ formatMissedLinesSummary(uncoveredByFile).forEach(line => console.log(line));
194
338
  }
195
339
  }