mo3ta-coverage 1.0.13 → 1.0.16
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/README.md +6 -21
- package/RECOMMENDED_USAGE.md +2 -2
- package/index.js +3 -49
- package/package.json +2 -3
- package/src/cli.js +32 -66
- package/src/fileUtils.js +124 -117
- package/src/fileUtils.test.js +77 -21
- package/coverage/clover.xml +0 -427
- package/coverage/coverage-final.json +0 -5
- package/coverage/lcov-report/base.css +0 -224
- package/coverage/lcov-report/block-navigation.js +0 -87
- package/coverage/lcov-report/cli.js.html +0 -1252
- package/coverage/lcov-report/coverage/index.html +0 -116
- package/coverage/lcov-report/coverage/index.js.html +0 -364
- package/coverage/lcov-report/coverage/src/cli.js.html +0 -652
- package/coverage/lcov-report/coverage/src/fileUtils.js.html +0 -130
- package/coverage/lcov-report/coverage/src/gitUtils.js.html +0 -145
- package/coverage/lcov-report/coverage/src/index.html +0 -146
- package/coverage/lcov-report/favicon.png +0 -0
- package/coverage/lcov-report/fileUtils.js.html +0 -775
- package/coverage/lcov-report/gitUtils.js.html +0 -145
- package/coverage/lcov-report/importer.js.html +0 -1051
- package/coverage/lcov-report/index.html +0 -161
- package/coverage/lcov-report/prettify.css +0 -1
- package/coverage/lcov-report/prettify.js +0 -2
- package/coverage/lcov-report/sort-arrow-sprite.png +0 -0
- package/coverage/lcov-report/sorter.js +0 -196
- package/coverage/lcov.info +0 -799
- package/src/importer.js +0 -323
package/README.md
CHANGED
|
@@ -4,13 +4,11 @@ mo3ta-coverage checks coverage for changed lines in a pull request. It finds cha
|
|
|
4
4
|
|
|
5
5
|
## Features
|
|
6
6
|
|
|
7
|
-
- Detects changed JS/TS files from
|
|
7
|
+
- Detects changed JS/TS files from git history and working tree
|
|
8
8
|
- Maps changed source files to nearby test files automatically
|
|
9
9
|
- Supports three execution modes: `fast`, `smart`, and `full`
|
|
10
|
-
- Smart mode includes reverse dependency analysis with configurable depth
|
|
11
10
|
- Parses `lcov.info` and reports uncovered changed lines
|
|
12
11
|
- Enforces a minimum coverage threshold for changed lines
|
|
13
|
-
- Helpful error messages when invalid options are provided
|
|
14
12
|
|
|
15
13
|
## Installation
|
|
16
14
|
|
|
@@ -28,21 +26,17 @@ mo3ta-coverage --mode smart --base origin/main --limit 80
|
|
|
28
26
|
|
|
29
27
|
| Option | Description | Default |
|
|
30
28
|
|--------|-------------|---------|
|
|
31
|
-
| `-v, --version` | Output the current version | - |
|
|
32
29
|
| `--base <branch>` | Base branch to compare against | `origin/main` |
|
|
33
30
|
| `--lcov <path>` | Path to `lcov.info` | `coverage/lcov.info` |
|
|
34
31
|
| `--limit <percent>` | Minimum changed-line coverage percentage | `80` |
|
|
35
32
|
| `--showCovered <bool>` | Show covered changed lines in output | `false` |
|
|
36
|
-
| `--mode <mode>` | Execution mode: `fast`, `smart`, or `full`
|
|
37
|
-
| `--maxDepth <number>` | Maximum reverse dependency depth for smart mode | `3` |
|
|
33
|
+
| `--mode <mode>` | Execution mode: `fast`, `smart`, or `full` | `smart` |
|
|
38
34
|
|
|
39
35
|
## Modes
|
|
40
36
|
|
|
41
|
-
-
|
|
42
|
-
-
|
|
43
|
-
-
|
|
44
|
-
|
|
45
|
-
If an invalid mode is provided, the tool will display available options with descriptions.
|
|
37
|
+
- `fast`: Direct execution of mapped test files only. No Jest dependency traversal.
|
|
38
|
+
- `smart`: Direct execution of mapped test files (found by naming convention, with an import-scan fallback for spec files that don't share the source file's name). No Jest dependency traversal.
|
|
39
|
+
- `full`: Runs mapped test files through `jest --findRelatedTests`.
|
|
46
40
|
|
|
47
41
|
## Recommended Mode
|
|
48
42
|
|
|
@@ -59,20 +53,11 @@ Use `full` only when you intentionally want Jest to expand to related tests.
|
|
|
59
53
|
You can persist defaults with the `config` subcommand:
|
|
60
54
|
|
|
61
55
|
```sh
|
|
62
|
-
mo3ta-coverage config --base origin/main --mode smart
|
|
56
|
+
mo3ta-coverage config --base origin/main --mode smart
|
|
63
57
|
```
|
|
64
58
|
|
|
65
59
|
This writes `.mo3ta-coverage.json` in the project root.
|
|
66
60
|
|
|
67
|
-
## Changed Files Detection
|
|
68
|
-
|
|
69
|
-
The tool detects changed files by comparing against the specified base branch:
|
|
70
|
-
- All committed files in the current branch (from merge-base to HEAD)
|
|
71
|
-
- Uncommitted changes in the working tree
|
|
72
|
-
- Staged changes (files added with `git add`)
|
|
73
|
-
|
|
74
|
-
This means coverage is checked for all changes in your branch, not just your authored commits.
|
|
75
|
-
|
|
76
61
|
## How It Works
|
|
77
62
|
|
|
78
63
|
1. Reads CLI options and saved config from [index.js](index.js).
|
package/RECOMMENDED_USAGE.md
CHANGED
|
@@ -10,14 +10,14 @@ mo3ta-coverage --mode smart --base origin/main --limit 80
|
|
|
10
10
|
|
|
11
11
|
## Why `smart`
|
|
12
12
|
|
|
13
|
-
`smart` avoids Jest dependency traversal
|
|
13
|
+
`smart` avoids Jest dependency traversal by running only the mapped test files directly (test files found via naming conventions, plus a fallback import scan that finds spec files referencing the changed source file regardless of their naming). That makes it the most predictable mode for large projects.
|
|
14
14
|
|
|
15
15
|
## Mode Comparison
|
|
16
16
|
|
|
17
17
|
| Mode | What Jest Receives | Traversal | Typical Outcome |
|
|
18
18
|
|------|--------------------|-----------|-----------------|
|
|
19
19
|
| `fast` | mapped test files | none | fastest run |
|
|
20
|
-
| `smart` |
|
|
20
|
+
| `smart` | mapped test files (naming + import scan) | none | best balance |
|
|
21
21
|
| `full` | mapped test files via `--findRelatedTests` | yes | can expand widely |
|
|
22
22
|
|
|
23
23
|
## Project Setup
|
package/index.js
CHANGED
|
@@ -27,8 +27,7 @@ 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.')
|
|
31
|
-
.version('1.0.13', '-v, --version', 'Output the current version');
|
|
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.');
|
|
32
31
|
|
|
33
32
|
program
|
|
34
33
|
.option('--base <branch>', 'Base branch to compare against (e.g., origin/main)')
|
|
@@ -36,7 +35,6 @@ program
|
|
|
36
35
|
.option('--limit <percent>', 'Minimum required coverage percentage for all changed lines (e.g., 80)', '80')
|
|
37
36
|
.option('--showCovered <bool>', 'Show covered changed lines in the output', false)
|
|
38
37
|
.option('--mode <mode>', 'Execution mode: fast, smart, or full', 'smart')
|
|
39
|
-
.option('--maxDepth <number>', 'Maximum reverse dependency depth for smart mode', '3')
|
|
40
38
|
.enablePositionalOptions(); // used to allow using same options in subcommands
|
|
41
39
|
|
|
42
40
|
|
|
@@ -45,7 +43,6 @@ program
|
|
|
45
43
|
.description('Set or get configuration options')
|
|
46
44
|
.option('--base <branch>', 'Set default base branch')
|
|
47
45
|
.option('--mode <mode>', 'Set default mode (fast/smart/full)')
|
|
48
|
-
.option('--maxDepth <number>', 'Set default reverse dependency depth for smart mode')
|
|
49
46
|
.action((opts) => {
|
|
50
47
|
let config = readConfig();
|
|
51
48
|
|
|
@@ -69,18 +66,6 @@ program
|
|
|
69
66
|
updated = true;
|
|
70
67
|
console.log(`Default mode set to: ${config.mode}`);
|
|
71
68
|
}
|
|
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
|
-
|
|
84
69
|
if (updated) {
|
|
85
70
|
writeConfig(config);
|
|
86
71
|
} else {
|
|
@@ -106,40 +91,9 @@ program.action((opts) => {
|
|
|
106
91
|
options.mode = config.mode;
|
|
107
92
|
}
|
|
108
93
|
|
|
109
|
-
|
|
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();
|
|
94
|
+
options.mode = String(options.mode || 'smart').toLowerCase();
|
|
129
95
|
if (!['fast', 'smart', 'full'].includes(options.mode)) {
|
|
130
|
-
console.error(
|
|
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.`);
|
|
96
|
+
console.error(`Invalid mode: ${options.mode}. Expected one of: fast, smart, full.`);
|
|
143
97
|
process.exit(1);
|
|
144
98
|
}
|
|
145
99
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "mo3ta-coverage",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.16",
|
|
4
4
|
"description": "Run tests and report uncovered changed lines in a PR",
|
|
5
5
|
"main": "index.js",
|
|
6
6
|
"bin": {
|
|
@@ -37,7 +37,6 @@
|
|
|
37
37
|
"jest": "^30.0.5"
|
|
38
38
|
},
|
|
39
39
|
"dependencies": {
|
|
40
|
-
"commander": "^14.0.0"
|
|
41
|
-
"typescript": "^5.8.3"
|
|
40
|
+
"commander": "^14.0.0"
|
|
42
41
|
}
|
|
43
42
|
}
|
package/src/cli.js
CHANGED
|
@@ -3,42 +3,7 @@ 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, 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
|
-
}
|
|
6
|
+
import { getJsOnlyFiles, separateSourceAndTestFiles, findTestFilesForSource, findTestFilesByImport } from './fileUtils.js';
|
|
42
7
|
|
|
43
8
|
export function main(options) {
|
|
44
9
|
try {
|
|
@@ -50,12 +15,11 @@ export function main(options) {
|
|
|
50
15
|
const COVERAGE_LIMIT = parseFloat(options.limit);
|
|
51
16
|
const SHOW_COVERED = options.showCovered === true || options.showCovered === 'true';
|
|
52
17
|
const MODE = options.mode;
|
|
53
|
-
const MAX_DEPTH = options.maxDepth;
|
|
54
18
|
|
|
55
|
-
console.log(`Options:\nBase Branch: ${BASE_BRANCH} \nLCOV Path: ${LCOV_PATH} \nCoverage Limit: ${COVERAGE_LIMIT} \nShow Covered Lines: ${SHOW_COVERED} \nMode: ${MODE}
|
|
19
|
+
console.log(`Options:\nBase Branch: ${BASE_BRANCH} \nLCOV Path: ${LCOV_PATH} \nCoverage Limit: ${COVERAGE_LIMIT} \nShow Covered Lines: ${SHOW_COVERED} \nMode: ${MODE}`);
|
|
56
20
|
|
|
57
21
|
const changedFiles = getChangedFiles(BASE_BRANCH);
|
|
58
|
-
runRelatedTests(changedFiles, MODE
|
|
22
|
+
runRelatedTests(changedFiles, MODE);
|
|
59
23
|
reportUncoveredChangedLines(changedFiles, LCOV_PATH, BASE_BRANCH, COVERAGE_LIMIT, SHOW_COVERED);
|
|
60
24
|
} catch (error) {
|
|
61
25
|
console.error('❌ An unexpected error occurred:', error.message || error);
|
|
@@ -69,24 +33,27 @@ function getChangedFiles(BASE_BRANCH) {
|
|
|
69
33
|
verifyBaseBranchExists(BASE_BRANCH);
|
|
70
34
|
|
|
71
35
|
const command = `(
|
|
72
|
-
git log --pretty=format: --name-only --diff-filter=AM $(git merge-base HEAD ${BASE_BRANCH})..HEAD
|
|
36
|
+
git log --pretty=format: --name-only --diff-filter=AM --author="$(git config user.name)" $(git merge-base HEAD ${BASE_BRANCH})..HEAD
|
|
73
37
|
git diff --name-only --diff-filter=AM
|
|
74
38
|
git diff --cached --name-only --diff-filter=AM
|
|
75
39
|
) | sort -u`;
|
|
76
40
|
|
|
77
41
|
try {
|
|
78
42
|
const output = execSync(command).toString();
|
|
79
|
-
|
|
80
|
-
return output
|
|
43
|
+
const changedFiles = output
|
|
81
44
|
.split('\n')
|
|
82
|
-
.filter(f => f.trim().length > 0 && f.match(/\.(js|ts|jsx|tsx)$/))
|
|
45
|
+
.filter(f => f.trim().length > 0 && f.match(/\.(js|ts|jsx|tsx)$/))
|
|
46
|
+
// Defensive: ignore dependency/build/coverage artifacts even if git tracked them
|
|
47
|
+
.filter(f => !f.match(/(^|\/)(node_modules|coverage|dist|build)\/|(^|\/)\.git\//));
|
|
48
|
+
console.log(`Changed files:\n${changedFiles.join('\n')}`);
|
|
49
|
+
return changedFiles;
|
|
83
50
|
} catch (error) {
|
|
84
51
|
console.error('Error getting changed files:', error.message || error);
|
|
85
52
|
return [];
|
|
86
53
|
}
|
|
87
54
|
}
|
|
88
55
|
|
|
89
|
-
function runRelatedTests(files, mode
|
|
56
|
+
function runRelatedTests(files, mode) {
|
|
90
57
|
if (files.length === 0) {
|
|
91
58
|
console.log('✅ No changed source files found.');
|
|
92
59
|
exit(0);
|
|
@@ -114,9 +81,20 @@ function runRelatedTests(files, mode, maxDepth) {
|
|
|
114
81
|
const mappedTests = new Map(); // Track which tests map to which source files
|
|
115
82
|
|
|
116
83
|
sourceFiles.forEach(sourceFile => {
|
|
117
|
-
|
|
84
|
+
let relatedTests = findTestFilesForSource(sourceFile);
|
|
85
|
+
let matchType = 'naming convention';
|
|
86
|
+
|
|
87
|
+
// Fallback: spec files don't have to follow the same-name convention.
|
|
88
|
+
// If no name-based test file exists, look for test files that import this source file.
|
|
89
|
+
if (relatedTests.length === 0) {
|
|
90
|
+
relatedTests = findTestFilesByImport(sourceFile);
|
|
91
|
+
if (relatedTests.length > 0) {
|
|
92
|
+
matchType = 'import scan';
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
118
96
|
if (relatedTests.length > 0) {
|
|
119
|
-
console.log(` ✓ ${sourceFile} → ${relatedTests.length} test file(s)`);
|
|
97
|
+
console.log(` ✓ ${sourceFile} → ${relatedTests.length} test file(s) (${matchType})`);
|
|
120
98
|
relatedTests.forEach(test => {
|
|
121
99
|
testFilesToRun.add(test);
|
|
122
100
|
if (!mappedTests.has(test)) {
|
|
@@ -155,28 +133,12 @@ function runRelatedTests(files, mode, maxDepth) {
|
|
|
155
133
|
exit(1);
|
|
156
134
|
}
|
|
157
135
|
} else if (mode === 'smart') {
|
|
158
|
-
console.log(`\n📝 Test strategy: smart (
|
|
136
|
+
console.log(`\n📝 Test strategy: smart (Run only mapped test files, no Jest dependency traversal)`);
|
|
159
137
|
console.log(` Test files: ${finalTestFiles.length}`);
|
|
160
138
|
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
139
|
console.log(' Files passed to Jest:');
|
|
178
|
-
|
|
179
|
-
const command = `npx jest --passWithNoTests --coverage ${
|
|
140
|
+
finalTestFiles.forEach(file => console.log(` - ${file}`));
|
|
141
|
+
const command = `npx jest --passWithNoTests --coverage ${finalTestFiles.join(' ')}`;
|
|
180
142
|
console.log(` Jest command: ${command}`);
|
|
181
143
|
|
|
182
144
|
try {
|
|
@@ -381,9 +343,13 @@ function reportUncoveredChangedLines(changedFiles, LCOV_PATH, BASE_BRANCH, COVER
|
|
|
381
343
|
|
|
382
344
|
// Cumulative coverage check
|
|
383
345
|
if (totalChanged > 0) {
|
|
384
|
-
const { overallCoverage, icon } = summarizeCoverageResult(totalChanged, totalNotCovered, COVERAGE_LIMIT);
|
|
346
|
+
const { overallCoverage, passed, icon } = summarizeCoverageResult(totalChanged, totalNotCovered, COVERAGE_LIMIT);
|
|
385
347
|
console.log(`\n${icon} Overall coverage for all changed lines: ${overallCoverage.toFixed(2)}% (limit: ${COVERAGE_LIMIT}%)`);
|
|
386
348
|
console.log(`Not covered lines: ${totalNotCovered} out of ${totalChanged} changed lines`);
|
|
387
349
|
formatMissedLinesSummary(uncoveredByFile).forEach(line => console.log(line));
|
|
350
|
+
|
|
351
|
+
if (!passed) {
|
|
352
|
+
process.exit(1);
|
|
353
|
+
}
|
|
388
354
|
}
|
|
389
355
|
}
|
package/src/fileUtils.js
CHANGED
|
@@ -1,6 +1,15 @@
|
|
|
1
1
|
import fs from 'fs';
|
|
2
2
|
import path from 'path';
|
|
3
3
|
|
|
4
|
+
const TEST_FILE_RE = /(\.test|\.spec)\.(js|ts|jsx|tsx)$/;
|
|
5
|
+
const JS_EXTENSIONS = ['.js', '.ts', '.jsx', '.tsx'];
|
|
6
|
+
const SKIP_DIRS = new Set(['node_modules', '.git', 'dist', 'build', 'coverage', '.next', '.turbo']);
|
|
7
|
+
|
|
8
|
+
// Matches import/require specifiers in JS/TS files:
|
|
9
|
+
// import x from './mod'; import './mod'; export { x } from './mod';
|
|
10
|
+
// require('./mod'); await import('./mod'); jest.mock('./mod');
|
|
11
|
+
const IMPORT_SPECIFIER_RE = /(?:\bfrom\s+|\brequire\s*\(\s*|\bimport\s*\(\s*|\bimport\s+|\bjest\.mock\s*\(\s*)['"]([^'"\n]+)['"]/g;
|
|
12
|
+
|
|
4
13
|
export function getJsOnlyFiles(files, runTestsOnly) {
|
|
5
14
|
// Only include source code files, exclude test, config, and json files
|
|
6
15
|
return files.filter(f => {
|
|
@@ -91,140 +100,138 @@ export function findTestFilesForSource(sourceFile) {
|
|
|
91
100
|
return testFiles.filter(testFile => fs.existsSync(testFile));
|
|
92
101
|
}
|
|
93
102
|
|
|
103
|
+
let cachedAllTestFiles = null;
|
|
104
|
+
|
|
94
105
|
/**
|
|
95
|
-
*
|
|
96
|
-
*
|
|
97
|
-
*
|
|
106
|
+
* Collects every test file under the given root (relative to that root),
|
|
107
|
+
* skipping dependency/build directories.
|
|
108
|
+
* Results are cached per root for the lifetime of the CLI run.
|
|
109
|
+
* @param {string} [root] - Directory to scan (defaults to cwd)
|
|
110
|
+
* @returns {string[]} - Array of test file paths relative to root
|
|
98
111
|
*/
|
|
99
|
-
export function
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
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
|
-
}
|
|
112
|
+
export function findAllTestFiles(root = process.cwd()) {
|
|
113
|
+
if (cachedAllTestFiles && cachedAllTestFiles.root === root) {
|
|
114
|
+
return cachedAllTestFiles.files;
|
|
115
|
+
}
|
|
110
116
|
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
const cjsRegex = /require\s*\(\s*['"`]([^'"`]+)['"`]\s*\)/g;
|
|
119
|
-
while ((match = cjsRegex.exec(content)) !== null) {
|
|
120
|
-
imports.add(match[1]);
|
|
117
|
+
const results = [];
|
|
118
|
+
const walk = dir => {
|
|
119
|
+
let entries;
|
|
120
|
+
try {
|
|
121
|
+
entries = fs.readdirSync(dir, { withFileTypes: true });
|
|
122
|
+
} catch {
|
|
123
|
+
return;
|
|
121
124
|
}
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
125
|
+
entries.forEach(entry => {
|
|
126
|
+
const fullPath = path.join(dir, entry.name);
|
|
127
|
+
if (entry.isDirectory()) {
|
|
128
|
+
if (!SKIP_DIRS.has(entry.name) && !entry.name.startsWith('.')) {
|
|
129
|
+
walk(fullPath);
|
|
130
|
+
}
|
|
131
|
+
} else if (TEST_FILE_RE.test(entry.name)) {
|
|
132
|
+
results.push(path.relative(root, fullPath));
|
|
133
|
+
}
|
|
134
|
+
});
|
|
135
|
+
};
|
|
136
|
+
|
|
137
|
+
walk(root);
|
|
138
|
+
cachedAllTestFiles = { root, files: results };
|
|
139
|
+
return results;
|
|
127
140
|
}
|
|
128
141
|
|
|
129
142
|
/**
|
|
130
|
-
*
|
|
131
|
-
* @param {string}
|
|
132
|
-
* @
|
|
133
|
-
* @returns {string|null} - Resolved file path or null if not found
|
|
143
|
+
* Extracts quoted module specifiers from import/require statements.
|
|
144
|
+
* @param {string} content - File content
|
|
145
|
+
* @returns {string[]} - Unique specifiers
|
|
134
146
|
*/
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
147
|
+
function extractImportSpecifiers(content) {
|
|
148
|
+
const specifiers = new Set();
|
|
149
|
+
for (const match of content.matchAll(IMPORT_SPECIFIER_RE)) {
|
|
150
|
+
if (match[1]) specifiers.add(match[1]);
|
|
139
151
|
}
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
152
|
+
return Array.from(specifiers);
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/**
|
|
156
|
+
* Resolves a relative specifier ('./mod', '../src/mod') to existing file paths.
|
|
157
|
+
* Tries the exact path, each JS extension, and directory index files.
|
|
158
|
+
*/
|
|
159
|
+
function resolveSpecifierCandidates(specifier, fromDir) {
|
|
160
|
+
const base = path.resolve(fromDir, specifier);
|
|
161
|
+
const candidates = [];
|
|
162
|
+
|
|
163
|
+
const ext = path.extname(base);
|
|
164
|
+
if (ext) {
|
|
165
|
+
candidates.push(base);
|
|
166
|
+
// TypeScript convention: an explicit './mod.js' import may resolve to './mod.ts'
|
|
167
|
+
if (ext === '.js' || ext === '.jsx' || ext === '.mjs') {
|
|
168
|
+
['.ts', '.tsx'].forEach(tsExt => candidates.push(base.slice(0, -ext.length) + tsExt));
|
|
150
169
|
}
|
|
170
|
+
} else {
|
|
171
|
+
JS_EXTENSIONS.forEach(e => candidates.push(base + e));
|
|
172
|
+
JS_EXTENSIONS.forEach(e => candidates.push(path.join(base, `index${e}`)));
|
|
151
173
|
}
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
if (fs.existsSync(resolvedPath)) {
|
|
155
|
-
return resolvedPath;
|
|
156
|
-
}
|
|
157
|
-
|
|
158
|
-
return null;
|
|
174
|
+
|
|
175
|
+
return candidates.filter(candidate => fs.existsSync(candidate));
|
|
159
176
|
}
|
|
160
177
|
|
|
161
178
|
/**
|
|
162
|
-
* Finds
|
|
163
|
-
*
|
|
164
|
-
*
|
|
165
|
-
*
|
|
166
|
-
*
|
|
179
|
+
* Finds test files that import the given source file, regardless of
|
|
180
|
+
* the test file's naming convention. Two matching strategies:
|
|
181
|
+
* 1. Relative imports are resolved against the test file's directory
|
|
182
|
+
* and compared to the absolute source path.
|
|
183
|
+
* 2. Non-relative specifiers (aliases like '@/utils/helper') are matched
|
|
184
|
+
* as a path suffix against the source path (extension stripped).
|
|
185
|
+
* @param {string} sourceFile - Path to source file (relative to root)
|
|
186
|
+
* @param {string} [root] - Directory to scan for test files (defaults to cwd)
|
|
187
|
+
* @returns {string[]} - Array of test file paths (relative to root) that import the source file
|
|
167
188
|
*/
|
|
168
|
-
export function
|
|
169
|
-
const
|
|
170
|
-
const
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
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);
|
|
189
|
+
export function findTestFilesByImport(sourceFile, root = process.cwd()) {
|
|
190
|
+
const resolvedSource = path.resolve(root, sourceFile);
|
|
191
|
+
const sourceNoExt = sourceFile.replace(/\.(js|ts|jsx|tsx)$/, '').replace(/^\.\//, '');
|
|
192
|
+
const matching = [];
|
|
193
|
+
|
|
194
|
+
for (const testFile of findAllTestFiles(root)) {
|
|
195
|
+
let content;
|
|
196
|
+
try {
|
|
197
|
+
content = fs.readFileSync(path.resolve(root, testFile), 'utf8');
|
|
198
|
+
} catch {
|
|
199
|
+
continue;
|
|
191
200
|
}
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
201
|
+
|
|
202
|
+
const specifiers = extractImportSpecifiers(content);
|
|
203
|
+
let matched = false;
|
|
204
|
+
|
|
205
|
+
for (const specifier of specifiers) {
|
|
206
|
+
if (specifier.startsWith('.')) {
|
|
207
|
+
// Relative import: resolve and compare absolute paths
|
|
208
|
+
const fromDir = path.dirname(path.resolve(root, testFile));
|
|
209
|
+
const candidates = resolveSpecifierCandidates(specifier, fromDir);
|
|
210
|
+
if (candidates.includes(resolvedSource)) {
|
|
211
|
+
matched = true;
|
|
212
|
+
break;
|
|
213
|
+
}
|
|
214
|
+
} else {
|
|
215
|
+
// Alias or package-style import: compare path suffix (no extension).
|
|
216
|
+
// '@/' is the most common alias (maps to 'src/'), so strip it before comparing.
|
|
217
|
+
let specifierNoExt = specifier.replace(/\.(js|ts|jsx|tsx)$/, '');
|
|
218
|
+
if (specifierNoExt.startsWith('@/')) {
|
|
219
|
+
specifierNoExt = specifierNoExt.slice(2);
|
|
220
|
+
}
|
|
221
|
+
if (
|
|
222
|
+
specifierNoExt &&
|
|
223
|
+
(sourceNoExt === specifierNoExt || sourceNoExt.endsWith(`/${specifierNoExt}`))
|
|
224
|
+
) {
|
|
225
|
+
matched = true;
|
|
226
|
+
break;
|
|
215
227
|
}
|
|
216
|
-
});
|
|
217
|
-
|
|
218
|
-
if (importsCurrentLevel) {
|
|
219
|
-
nextLevel.add(absoluteSourceFile);
|
|
220
|
-
reverseDeps.add(absoluteSourceFile);
|
|
221
228
|
}
|
|
222
|
-
}
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
if (matched) {
|
|
232
|
+
matching.push(testFile);
|
|
233
|
+
}
|
|
227
234
|
}
|
|
228
|
-
|
|
229
|
-
return
|
|
235
|
+
|
|
236
|
+
return matching;
|
|
230
237
|
}
|