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/src/fileUtils.js CHANGED
@@ -1,3 +1,6 @@
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+
1
4
  export function getJsOnlyFiles(files, runTestsOnly) {
2
5
  // Only include source code files, exclude test, config, and json files
3
6
  return files.filter(f => {
@@ -13,3 +16,215 @@ export function getJsOnlyFiles(files, runTestsOnly) {
13
16
  return f.endsWith('.js') || f.endsWith('.ts') || f.endsWith('.jsx') || f.endsWith('.tsx');
14
17
  });
15
18
  }
19
+
20
+ /**
21
+ * Separates files into source files and test files
22
+ * @param {string[]} files - Array of file paths
23
+ * @returns {{sourceFiles: string[], testFiles: string[]}}
24
+ */
25
+ export function separateSourceAndTestFiles(files) {
26
+ const sourceFiles = [];
27
+ const testFiles = [];
28
+
29
+ files.forEach(file => {
30
+ // Exclude config files
31
+ if (file.match(/(jest|babel|webpack|tsconfig|eslint|prettier|rollup|vite|package)\.(js|ts|json)$/) || file.includes('.config.')) {
32
+ return;
33
+ }
34
+ // Exclude json files
35
+ if (file.endsWith('.json')) {
36
+ return;
37
+ }
38
+
39
+ // Check if it's a test file
40
+ if (file.match(/(\.test|\.spec)\.(js|ts|jsx|tsx)$/)) {
41
+ testFiles.push(file);
42
+ } else if (file.match(/\.(js|ts|jsx|tsx)$/)) {
43
+ sourceFiles.push(file);
44
+ }
45
+ });
46
+
47
+ return { sourceFiles, testFiles };
48
+ }
49
+
50
+ /**
51
+ * Finds potential test files for a given source file
52
+ * Checks multiple naming conventions and locations
53
+ * @param {string} sourceFile - Path to source file
54
+ * @returns {string[]} - Array of potential test file paths
55
+ */
56
+ export function findTestFilesForSource(sourceFile) {
57
+ const testFiles = [];
58
+ const parsed = path.parse(sourceFile);
59
+ const extensions = ['.js', '.ts', '.jsx', '.tsx'];
60
+
61
+ // Pattern 1: Same directory with .test or .spec suffix
62
+ // e.g., src/utils/helper.js → src/utils/helper.test.js
63
+ extensions.forEach(ext => {
64
+ testFiles.push(path.join(parsed.dir, `${parsed.name}.test${ext}`));
65
+ testFiles.push(path.join(parsed.dir, `${parsed.name}.spec${ext}`));
66
+ });
67
+
68
+ // Pattern 2: __tests__ subdirectory
69
+ // e.g., src/utils/helper.js → src/utils/__tests__/helper.test.js
70
+ extensions.forEach(ext => {
71
+ testFiles.push(path.join(parsed.dir, '__tests__', `${parsed.name}.test${ext}`));
72
+ testFiles.push(path.join(parsed.dir, '__tests__', `${parsed.name}.spec${ext}`));
73
+ testFiles.push(path.join(parsed.dir, '__tests__', `${parsed.name}${ext}`));
74
+ });
75
+
76
+ // Pattern 3: tests directory at same level
77
+ // e.g., src/utils/helper.js → src/tests/utils/helper.test.js
78
+ const srcMatch = sourceFile.match(/^(.*?\/src)\/(.*)/);
79
+ if (srcMatch) {
80
+ const baseDir = srcMatch[1];
81
+ const relativePath = srcMatch[2];
82
+ const relParsed = path.parse(relativePath);
83
+
84
+ extensions.forEach(ext => {
85
+ testFiles.push(path.join(baseDir, 'tests', relParsed.dir, `${relParsed.name}.test${ext}`));
86
+ testFiles.push(path.join(baseDir, 'tests', relParsed.dir, `${relParsed.name}.spec${ext}`));
87
+ });
88
+ }
89
+
90
+ // Check which test files actually exist
91
+ return testFiles.filter(testFile => fs.existsSync(testFile));
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,4 +1,7 @@
1
- import { getJsOnlyFiles } from './fileUtils';
1
+ import { getJsOnlyFiles, separateSourceAndTestFiles, findReverseDeps, findTestFilesForSource } from './fileUtils';
2
+ import fs from 'fs';
3
+ import os from 'os';
4
+ import path from 'path';
2
5
 
3
6
  describe('getJsOnlyFiles', () => {
4
7
  const files = [
@@ -81,4 +84,182 @@ describe('getJsOnlyFiles', () => {
81
84
  'src/page.tsx'
82
85
  ]);
83
86
  });
87
+ });
88
+
89
+ describe('separateSourceAndTestFiles', () => {
90
+ it('should separate source and test files correctly', () => {
91
+ const files = [
92
+ 'src/app.js',
93
+ 'src/utils.ts',
94
+ 'src/app.test.js',
95
+ 'src/utils.spec.ts',
96
+ 'src/component.jsx',
97
+ 'src/component.test.jsx'
98
+ ];
99
+
100
+ const result = separateSourceAndTestFiles(files);
101
+
102
+ expect(result.sourceFiles).toEqual([
103
+ 'src/app.js',
104
+ 'src/utils.ts',
105
+ 'src/component.jsx'
106
+ ]);
107
+ expect(result.testFiles).toEqual([
108
+ 'src/app.test.js',
109
+ 'src/utils.spec.ts',
110
+ 'src/component.test.jsx'
111
+ ]);
112
+ });
113
+
114
+ it('should exclude config and json files', () => {
115
+ const files = [
116
+ 'src/app.js',
117
+ 'jest.config.js',
118
+ 'package.json',
119
+ 'src/data.json'
120
+ ];
121
+
122
+ const result = separateSourceAndTestFiles(files);
123
+
124
+ expect(result.sourceFiles).toEqual(['src/app.js']);
125
+ expect(result.testFiles).toEqual([]);
126
+ });
127
+
128
+ it('should handle empty array', () => {
129
+ const result = separateSourceAndTestFiles([]);
130
+
131
+ expect(result.sourceFiles).toEqual([]);
132
+ expect(result.testFiles).toEqual([]);
133
+ });
134
+
135
+ it('should handle all test files', () => {
136
+ const files = [
137
+ 'src/app.test.js',
138
+ 'src/utils.spec.ts'
139
+ ];
140
+
141
+ const result = separateSourceAndTestFiles(files);
142
+
143
+ expect(result.sourceFiles).toEqual([]);
144
+ expect(result.testFiles).toEqual([
145
+ 'src/app.test.js',
146
+ 'src/utils.spec.ts'
147
+ ]);
148
+ });
149
+ });
150
+
151
+ describe('findTestFilesForSource', () => {
152
+ // Mock fs.existsSync for testing
153
+ const originalExistsSync = fs.existsSync;
154
+
155
+ beforeEach(() => {
156
+ // Reset mock before each test
157
+ fs.existsSync = jest.fn();
158
+ });
159
+
160
+ afterEach(() => {
161
+ // Restore original function
162
+ fs.existsSync = originalExistsSync;
163
+ });
164
+
165
+ it('should find test file in same directory with .test.js pattern', () => {
166
+ fs.existsSync.mockImplementation((path) => {
167
+ return path === 'src/utils/helper.test.js';
168
+ });
169
+
170
+ const result = findTestFilesForSource('src/utils/helper.js');
171
+
172
+ expect(result).toContain('src/utils/helper.test.js');
173
+ });
174
+
175
+ it('should find test file in __tests__ subdirectory', () => {
176
+ fs.existsSync.mockImplementation((path) => {
177
+ return path === 'src/utils/__tests__/helper.test.js';
178
+ });
179
+
180
+ const result = findTestFilesForSource('src/utils/helper.js');
181
+
182
+ expect(result).toContain('src/utils/__tests__/helper.test.js');
183
+ });
184
+
185
+ it('should find multiple test files if they exist', () => {
186
+ fs.existsSync.mockImplementation((path) => {
187
+ return path === 'src/utils/helper.test.js' ||
188
+ path === 'src/utils/helper.spec.js';
189
+ });
190
+
191
+ const result = findTestFilesForSource('src/utils/helper.js');
192
+
193
+ expect(result).toContain('src/utils/helper.test.js');
194
+ expect(result).toContain('src/utils/helper.spec.js');
195
+ expect(result.length).toBe(2);
196
+ });
197
+
198
+ it('should return empty array if no test files exist', () => {
199
+ fs.existsSync.mockReturnValue(false);
200
+
201
+ const result = findTestFilesForSource('src/utils/helper.js');
202
+
203
+ expect(result).toEqual([]);
204
+ });
205
+
206
+ it('should find test files in parallel tests directory structure', () => {
207
+ fs.existsSync.mockImplementation((path) => {
208
+ // path.join normalizes paths, removing leading './'
209
+ return path === 'src/tests/utils/helper.test.js';
210
+ });
211
+
212
+ const result = findTestFilesForSource('./src/utils/helper.js');
213
+
214
+ expect(result).toContain('src/tests/utils/helper.test.js');
215
+ });
216
+
217
+ it('should handle TypeScript files', () => {
218
+ fs.existsSync.mockImplementation((path) => {
219
+ return path === 'src/utils/helper.test.ts';
220
+ });
221
+
222
+ const result = findTestFilesForSource('src/utils/helper.ts');
223
+
224
+ expect(result).toContain('src/utils/helper.test.ts');
225
+ });
226
+
227
+ it('should handle JSX files', () => {
228
+ fs.existsSync.mockImplementation((path) => {
229
+ return path === 'src/components/Button.test.jsx';
230
+ });
231
+
232
+ const result = findTestFilesForSource('src/components/Button.jsx');
233
+
234
+ expect(result).toContain('src/components/Button.test.jsx');
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
+ });
84
265
  });