mo3ta-coverage 1.0.11 → 1.0.13

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
@@ -27,7 +27,8 @@ const program = new Command();
27
27
 
28
28
  program
29
29
  .name('mo3ta-coverage')
30
- .description('Run tests and report uncovered changed lines in a PR. Checks cumulative coverage for all changed lines against a specified limit. Useful for CI and code review workflows.');
30
+ .description('Run tests and report uncovered changed lines in a PR. Checks cumulative coverage for all changed lines against a specified limit. Useful for CI and code review workflows.')
31
+ .version('1.0.13', '-v, --version', 'Output the current version');
31
32
 
32
33
  program
33
34
  .option('--base <branch>', 'Base branch to compare against (e.g., origin/main)')
@@ -35,6 +36,7 @@ program
35
36
  .option('--limit <percent>', 'Minimum required coverage percentage for all changed lines (e.g., 80)', '80')
36
37
  .option('--showCovered <bool>', 'Show covered changed lines in the output', false)
37
38
  .option('--mode <mode>', 'Execution mode: fast, smart, or full', 'smart')
39
+ .option('--maxDepth <number>', 'Maximum reverse dependency depth for smart mode', '3')
38
40
  .enablePositionalOptions(); // used to allow using same options in subcommands
39
41
 
40
42
 
@@ -43,6 +45,7 @@ program
43
45
  .description('Set or get configuration options')
44
46
  .option('--base <branch>', 'Set default base branch')
45
47
  .option('--mode <mode>', 'Set default mode (fast/smart/full)')
48
+ .option('--maxDepth <number>', 'Set default reverse dependency depth for smart mode')
46
49
  .action((opts) => {
47
50
  let config = readConfig();
48
51
 
@@ -66,6 +69,18 @@ program
66
69
  updated = true;
67
70
  console.log(`Default mode set to: ${config.mode}`);
68
71
  }
72
+
73
+ if (opts.maxDepth !== undefined) {
74
+ const parsedMaxDepth = parseInt(opts.maxDepth, 10);
75
+ if (!Number.isInteger(parsedMaxDepth) || parsedMaxDepth < 0) {
76
+ console.error(`Invalid maxDepth: ${opts.maxDepth}. Expected a non-negative integer.`);
77
+ process.exit(1);
78
+ }
79
+ config.maxDepth = parsedMaxDepth;
80
+ updated = true;
81
+ console.log(`Default max depth set to: ${config.maxDepth}`);
82
+ }
83
+
69
84
  if (updated) {
70
85
  writeConfig(config);
71
86
  } else {
@@ -91,9 +106,40 @@ program.action((opts) => {
91
106
  options.mode = config.mode;
92
107
  }
93
108
 
94
- options.mode = String(options.mode || 'smart').toLowerCase();
109
+ if ((options.maxDepth === undefined || options.maxDepth === '3') && config.maxDepth !== undefined) {
110
+ options.maxDepth = config.maxDepth;
111
+ }
112
+
113
+ // Validate mode
114
+ options.mode = options.mode || 'smart'; // Default to smart if not provided
115
+
116
+ // Check if mode is invalid (boolean, empty string, etc.)
117
+ if (typeof options.mode === 'boolean' || options.mode === '') {
118
+ console.error(`❌ Missing or invalid --mode value.`);
119
+ console.error(`Available options: fast, smart, full`);
120
+ console.error(`\nMode descriptions:`);
121
+ console.error(` • fast - Direct execution of mapped test files only`);
122
+ console.error(` • smart - Combine source and mapped test files with reverse deps (recommended)`);
123
+ console.error(` • full - Run mapped tests through Jest --findRelatedTests`);
124
+ console.error(`\nExample: mo3ta-coverage --mode smart`);
125
+ process.exit(1);
126
+ }
127
+
128
+ options.mode = String(options.mode).toLowerCase();
95
129
  if (!['fast', 'smart', 'full'].includes(options.mode)) {
96
- console.error(`Invalid mode: ${options.mode}. Expected one of: fast, smart, full.`);
130
+ console.error(`❌ Invalid mode: "${options.mode}"`);
131
+ console.error(`Available options: fast, smart, full`);
132
+ console.error(`\nMode descriptions:`);
133
+ console.error(` • fast - Direct execution of mapped test files only`);
134
+ console.error(` • smart - Combine source and mapped test files with reverse deps (recommended)`);
135
+ console.error(` • full - Run mapped tests through Jest --findRelatedTests`);
136
+ console.error(`\nExample: mo3ta-coverage --mode smart`);
137
+ process.exit(1);
138
+ }
139
+
140
+ options.maxDepth = parseInt(options.maxDepth ?? 3, 10);
141
+ if (!Number.isInteger(options.maxDepth) || options.maxDepth < 0) {
142
+ console.error(`Invalid maxDepth: ${options.maxDepth}. Expected a non-negative integer.`);
97
143
  process.exit(1);
98
144
  }
99
145
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mo3ta-coverage",
3
- "version": "1.0.11",
3
+ "version": "1.0.13",
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
@@ -4,6 +4,41 @@ import path from 'path';
4
4
  import { exit } from 'process';
5
5
  import { verifyBaseBranchExists, verifyGitRepoExists } from './gitUtils.js';
6
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 {
@@ -15,11 +50,12 @@ export function main(options) {
15
50
  const COVERAGE_LIMIT = parseFloat(options.limit);
16
51
  const SHOW_COVERED = options.showCovered === true || options.showCovered === 'true';
17
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} \nMode: ${MODE}`);
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, MODE);
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);
@@ -33,7 +69,7 @@ function getChangedFiles(BASE_BRANCH) {
33
69
  verifyBaseBranchExists(BASE_BRANCH);
34
70
 
35
71
  const command = `(
36
- git log --pretty=format: --name-only --diff-filter=AM --author="$(git config user.name)" $(git merge-base HEAD ${BASE_BRANCH})..HEAD
72
+ git log --pretty=format: --name-only --diff-filter=AM $(git merge-base HEAD ${BASE_BRANCH})..HEAD
37
73
  git diff --name-only --diff-filter=AM
38
74
  git diff --cached --name-only --diff-filter=AM
39
75
  ) | sort -u`;
@@ -50,7 +86,7 @@ function getChangedFiles(BASE_BRANCH) {
50
86
  }
51
87
  }
52
88
 
53
- function runRelatedTests(files, mode) {
89
+ function runRelatedTests(files, mode, maxDepth) {
54
90
  if (files.length === 0) {
55
91
  console.log('✅ No changed source files found.');
56
92
  exit(0);
@@ -119,11 +155,25 @@ function runRelatedTests(files, mode) {
119
155
  exit(1);
120
156
  }
121
157
  } else if (mode === 'smart') {
122
- console.log(`\n📝 Test strategy: smart (Combine source and mapped test files, no Jest dependency traversal)`);
158
+ console.log(`\n📝 Test strategy: smart (Combine source and mapped test files, plus reverse deps up to depth ${maxDepth})`);
123
159
  console.log(` Test files: ${finalTestFiles.length}`);
124
160
  console.log(` Source files for coverage: ${sourceFiles.length}`);
125
- const allFiles = [...sourceFiles, ...finalTestFiles];
161
+ const { reverseDepsTests, debugResults } = findReverseDepsForSourceFiles(sourceFiles, maxDepth);
162
+ const uniqueAllFiles = new Set([...sourceFiles, ...finalTestFiles, ...reverseDepsTests]);
163
+ const allFiles = Array.from(uniqueAllFiles);
126
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
+ }
127
177
  console.log(' Files passed to Jest:');
128
178
  allFiles.forEach(file => console.log(` - ${file}`));
129
179
  const command = `npx jest --passWithNoTests --coverage ${allFiles.join(' ')}`;
package/src/fileUtils.js CHANGED
@@ -90,3 +90,141 @@ export function findTestFilesForSource(sourceFile) {
90
90
  // Check which test files actually exist
91
91
  return testFiles.filter(testFile => fs.existsSync(testFile));
92
92
  }
93
+
94
+ /**
95
+ * Extracts import paths from a file (ESM and CommonJS)
96
+ * @param {string} filePath - Path to source file
97
+ * @returns {string[]} - Array of imported file paths
98
+ */
99
+ export function extractImports(filePath) {
100
+ try {
101
+ const content = fs.readFileSync(filePath, 'utf8');
102
+ const imports = new Set();
103
+
104
+ // ESM imports: import x from 'path'
105
+ const esmRegex = /import\s+(?:.*?)\s+from\s+['"`]([^'"`]+)['"`]/g;
106
+ let match;
107
+ while ((match = esmRegex.exec(content)) !== null) {
108
+ imports.add(match[1]);
109
+ }
110
+
111
+ // ESM side-effect imports: import 'path'
112
+ const sideEffectImportRegex = /import\s+['"`]([^'"`]+)['"`]/g;
113
+ while ((match = sideEffectImportRegex.exec(content)) !== null) {
114
+ imports.add(match[1]);
115
+ }
116
+
117
+ // CommonJS requires: require('path')
118
+ const cjsRegex = /require\s*\(\s*['"`]([^'"`]+)['"`]\s*\)/g;
119
+ while ((match = cjsRegex.exec(content)) !== null) {
120
+ imports.add(match[1]);
121
+ }
122
+
123
+ return Array.from(imports);
124
+ } catch (error) {
125
+ return [];
126
+ }
127
+ }
128
+
129
+ /**
130
+ * Resolves relative imports to absolute file paths
131
+ * @param {string} importPath - Import path (relative or module name)
132
+ * @param {string} fromFile - File doing the importing
133
+ * @returns {string|null} - Resolved file path or null if not found
134
+ */
135
+ export function resolveImportPath(importPath, fromFile) {
136
+ // Skip node_modules and external packages
137
+ if (importPath.startsWith('.') === false) {
138
+ return null;
139
+ }
140
+
141
+ const fromDir = path.dirname(fromFile);
142
+ let resolvedPath = path.resolve(fromDir, importPath);
143
+
144
+ // Try with file extensions if no extension provided
145
+ const extensions = ['.js', '.ts', '.jsx', '.tsx', '/index.js', '/index.ts'];
146
+ for (const ext of extensions) {
147
+ const candidate = resolvedPath + ext;
148
+ if (fs.existsSync(candidate)) {
149
+ return candidate;
150
+ }
151
+ }
152
+
153
+ // Also try without adding extension
154
+ if (fs.existsSync(resolvedPath)) {
155
+ return resolvedPath;
156
+ }
157
+
158
+ return null;
159
+ }
160
+
161
+ /**
162
+ * Finds all files that import the given files (reverse dependencies)
163
+ * up to a specified depth
164
+ * @param {string[]} changedFiles - Changed files to find reverse deps for
165
+ * @param {number} maxDepth - Maximum depth to traverse (default 3)
166
+ * @returns {string[]} - Array of files that import changed files
167
+ */
168
+ export function findReverseDeps(changedFiles, maxDepth = 3) {
169
+ const reverseDeps = new Set();
170
+ const visited = new Set();
171
+
172
+ // Get all source files to check
173
+ let allSourceFiles = [];
174
+ try {
175
+ const srcDir = 'src';
176
+ if (fs.existsSync(srcDir)) {
177
+ const walk = (dir) => {
178
+ const files = fs.readdirSync(dir);
179
+ files.forEach(file => {
180
+ const fullPath = path.join(dir, file);
181
+ const stat = fs.statSync(fullPath);
182
+
183
+ if (stat.isDirectory() && !file.startsWith('.') && file !== 'node_modules') {
184
+ walk(fullPath);
185
+ } else if (file.match(/\.(js|ts|jsx|tsx)$/) && !file.match(/(\.test|\.spec)\./)) {
186
+ allSourceFiles.push(fullPath);
187
+ }
188
+ });
189
+ };
190
+ walk(srcDir);
191
+ }
192
+ } catch (error) {
193
+ return [];
194
+ }
195
+
196
+ // BFS to find reverse deps up to maxDepth
197
+ let currentLevel = new Set(changedFiles.map(f => path.resolve(f)));
198
+ let depth = 0;
199
+
200
+ while (depth < maxDepth && currentLevel.size > 0) {
201
+ const nextLevel = new Set();
202
+
203
+ allSourceFiles.forEach(sourceFile => {
204
+ const absoluteSourceFile = path.resolve(sourceFile);
205
+
206
+ if (visited.has(absoluteSourceFile)) return;
207
+
208
+ const imports = extractImports(sourceFile);
209
+ let importsCurrentLevel = false;
210
+
211
+ imports.forEach(imp => {
212
+ const resolved = resolveImportPath(imp, sourceFile);
213
+ if (resolved && currentLevel.has(path.resolve(resolved))) {
214
+ importsCurrentLevel = true;
215
+ }
216
+ });
217
+
218
+ if (importsCurrentLevel) {
219
+ nextLevel.add(absoluteSourceFile);
220
+ reverseDeps.add(absoluteSourceFile);
221
+ }
222
+ });
223
+
224
+ currentLevel.forEach(f => visited.add(f));
225
+ currentLevel = nextLevel;
226
+ depth++;
227
+ }
228
+
229
+ return Array.from(reverseDeps);
230
+ }
@@ -1,5 +1,7 @@
1
- import { getJsOnlyFiles, separateSourceAndTestFiles, findTestFilesForSource } from './fileUtils';
1
+ import { getJsOnlyFiles, separateSourceAndTestFiles, findReverseDeps, findTestFilesForSource } from './fileUtils';
2
2
  import fs from 'fs';
3
+ import os from 'os';
4
+ import path from 'path';
3
5
 
4
6
  describe('getJsOnlyFiles', () => {
5
7
  const files = [
@@ -231,4 +233,33 @@ describe('findTestFilesForSource', () => {
231
233
 
232
234
  expect(result).toContain('src/components/Button.test.jsx');
233
235
  });
236
+ });
237
+
238
+ describe('findReverseDeps', () => {
239
+ const originalCwd = process.cwd();
240
+
241
+ beforeEach(() => {
242
+ const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'mo3ta-reverse-deps-'));
243
+ process.chdir(tempDir);
244
+ fs.mkdirSync('src', { recursive: true });
245
+ });
246
+
247
+ afterEach(() => {
248
+ process.chdir(originalCwd);
249
+ });
250
+
251
+ it('limits traversal to the configured depth', () => {
252
+ fs.writeFileSync('src/leaf.js', 'export const leaf = 1;\n');
253
+ fs.writeFileSync('src/mid.js', "import './leaf.js';\nexport const mid = 1;\n");
254
+ fs.writeFileSync('src/top.js', "import './mid.js';\nexport const top = 1;\n");
255
+
256
+ const depthOne = findReverseDeps(['src/leaf.js'], 1);
257
+ const depthTwo = findReverseDeps(['src/leaf.js'], 2);
258
+
259
+ expect(depthOne).toEqual([path.resolve('src/mid.js')]);
260
+ expect(depthTwo).toEqual([
261
+ path.resolve('src/mid.js'),
262
+ path.resolve('src/top.js')
263
+ ]);
264
+ });
234
265
  });