mo3ta-coverage 1.2.1 → 1.3.3
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/AGENT.md +26 -4
- package/README.md +179 -2
- package/index.js +47 -6
- package/mcp/createServer.js +179 -0
- package/mcp/server.js +18 -0
- package/mcp/server.test.js +290 -0
- package/package.json +11 -5
- package/src/api.js +807 -0
- package/src/api.test.js +430 -0
- package/src/cli.js +425 -150
- package/src/cli.spawn.test.js +184 -0
- package/src/cli.test.js +225 -0
- package/src/fileUtils.js +18 -2
- package/src/gitUtils.js +42 -11
package/src/cli.js
CHANGED
|
@@ -3,6 +3,10 @@ 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
|
+
|
|
7
|
+
// Set when Jest exits non-zero. `main` resets it so a later in-process call
|
|
8
|
+
// does not inherit the previous failure. The CLI process still exits.
|
|
9
|
+
let testsFailed = false;
|
|
6
10
|
import {
|
|
7
11
|
getJsOnlyFiles,
|
|
8
12
|
separateSourceAndTestFiles,
|
|
@@ -12,6 +16,9 @@ import {
|
|
|
12
16
|
} from './fileUtils.js';
|
|
13
17
|
|
|
14
18
|
export function main(options) {
|
|
19
|
+
// A single CLI process exits after one run. Reset anyway so an in-process
|
|
20
|
+
// caller does not inherit a failure from an earlier invocation.
|
|
21
|
+
testsFailed = false;
|
|
15
22
|
try {
|
|
16
23
|
// Check if current directory is a git repository
|
|
17
24
|
verifyGitRepoExists();
|
|
@@ -27,12 +34,14 @@ export function main(options) {
|
|
|
27
34
|
const CI_REPORT_PATH = options.ciReport
|
|
28
35
|
? path.resolve(options.ciReport)
|
|
29
36
|
: path.resolve('coverage', 'mo3ta-coverage-report.md');
|
|
37
|
+
const JEST_FLAGS = parseJestArgs(options.jest);
|
|
38
|
+
const FILTER = parseFilter(options.filter);
|
|
30
39
|
|
|
31
40
|
// In dry run, stdout must stay a clean one-path-per-line list, so
|
|
32
41
|
// diagnostics go to stderr instead of stdout.
|
|
33
42
|
const infoLog = DRY_RUN ? console.error : console.log;
|
|
34
43
|
|
|
35
|
-
infoLog(`Options:\nBase Branch: ${BASE_BRANCH} \nLCOV Path: ${LCOV_PATH} \nCoverage Limit: ${COVERAGE_LIMIT} \nShow Covered Lines: ${SHOW_COVERED} \nMode: ${MODE} \nDepth: ${DEPTH} \nDry Run: ${DRY_RUN} \nCI Mode: ${CI}`);
|
|
44
|
+
infoLog(`Options:\nBase Branch: ${BASE_BRANCH} \nLCOV Path: ${LCOV_PATH} \nCoverage Limit: ${COVERAGE_LIMIT} \nShow Covered Lines: ${SHOW_COVERED} \nMode: ${MODE} \nDepth: ${DEPTH} \nDry Run: ${DRY_RUN} \nCI Mode: ${CI} \nJest Flags: ${JEST_FLAGS.length ? JEST_FLAGS.join(' ') : '(none)'} \nFilter: ${FILTER ? FILTER.source : '(none)'}`);
|
|
36
45
|
|
|
37
46
|
const explicitFiles = getExplicitFiles(options);
|
|
38
47
|
let changedFiles;
|
|
@@ -47,11 +56,11 @@ export function main(options) {
|
|
|
47
56
|
}
|
|
48
57
|
|
|
49
58
|
if (DRY_RUN) {
|
|
50
|
-
dryRun(changedFiles, MODE, DEPTH);
|
|
59
|
+
dryRun(changedFiles, MODE, DEPTH, FILTER);
|
|
51
60
|
return;
|
|
52
61
|
}
|
|
53
62
|
|
|
54
|
-
runRelatedTests(changedFiles, MODE, DEPTH);
|
|
63
|
+
runRelatedTests(changedFiles, MODE, DEPTH, JEST_FLAGS, FILTER);
|
|
55
64
|
reportUncoveredChangedLines(changedFiles, LCOV_PATH, BASE_BRANCH, COVERAGE_LIMIT, SHOW_COVERED, CI, CI_REPORT_PATH);
|
|
56
65
|
|
|
57
66
|
if (testsFailed) {
|
|
@@ -59,7 +68,11 @@ export function main(options) {
|
|
|
59
68
|
exit(1);
|
|
60
69
|
}
|
|
61
70
|
} catch (error) {
|
|
62
|
-
|
|
71
|
+
if (error.code === 'INVALID_FILTER') {
|
|
72
|
+
console.error(`❌ ${error.message}`);
|
|
73
|
+
} else {
|
|
74
|
+
console.error('❌ An unexpected error occurred:', error.message || error);
|
|
75
|
+
}
|
|
63
76
|
exit(1);
|
|
64
77
|
}
|
|
65
78
|
}
|
|
@@ -113,52 +126,130 @@ export function readExplicitFilesFromFile(listPath, root = process.cwd()) {
|
|
|
113
126
|
* @param {{files?: string|string[], filesFrom?: string}} options
|
|
114
127
|
* @returns {string[]}
|
|
115
128
|
*/
|
|
116
|
-
export function getExplicitFiles(options = {}) {
|
|
129
|
+
export function getExplicitFiles(options = {}, root = process.cwd()) {
|
|
117
130
|
const files = [];
|
|
118
131
|
|
|
119
132
|
if (options.files !== undefined && options.files !== null && options.files !== false) {
|
|
120
|
-
files.push(...normalizeExplicitFiles(options.files));
|
|
133
|
+
files.push(...normalizeExplicitFiles(options.files, root));
|
|
121
134
|
}
|
|
122
135
|
|
|
123
136
|
if (options.filesFrom) {
|
|
124
|
-
files.push(...readExplicitFilesFromFile(options.filesFrom));
|
|
137
|
+
files.push(...readExplicitFilesFromFile(options.filesFrom, root));
|
|
125
138
|
}
|
|
126
139
|
|
|
127
140
|
return Array.from(new Set(files));
|
|
128
141
|
}
|
|
129
142
|
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
143
|
+
/**
|
|
144
|
+
* Normalizes user-provided extra Jest CLI flags into an argument array.
|
|
145
|
+
* Accepts a single value, a comma-separated string, or an array (the CLI's
|
|
146
|
+
* repeatable `--jest` option collects each flag as its own entry). Each flag
|
|
147
|
+
* is trimmed, empty entries dropped, and duplicates removed preserving order.
|
|
148
|
+
*
|
|
149
|
+
* Values may start with `--` (they are Jest flags, e.g. `--maxWorkers=2`).
|
|
150
|
+
* @param {string|string[]} [input]
|
|
151
|
+
* @returns {string[]}
|
|
152
|
+
*/
|
|
153
|
+
export function parseJestArgs(input) {
|
|
154
|
+
if (input === undefined || input === null) return [];
|
|
155
|
+
|
|
156
|
+
const values = Array.isArray(input) ? input : [input];
|
|
157
|
+
|
|
158
|
+
return values
|
|
159
|
+
.flatMap(value => String(value ?? '').split(','))
|
|
160
|
+
.map(flag => flag.trim())
|
|
161
|
+
.filter(flag => flag.length > 0)
|
|
162
|
+
.filter((flag, index, all) => all.indexOf(flag) === index);
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/**
|
|
166
|
+
* Compiles a user-provided spec filter into a RegExp. Returns null when the
|
|
167
|
+
* filter is empty. Global/sticky flags are dropped so repeated `.test()` calls
|
|
168
|
+
* do not depend on `lastIndex`.
|
|
169
|
+
* @param {string|RegExp} [input]
|
|
170
|
+
* @returns {RegExp|null}
|
|
171
|
+
*/
|
|
172
|
+
export function parseFilter(input) {
|
|
173
|
+
if (input === undefined || input === null) return null;
|
|
174
|
+
|
|
175
|
+
if (input instanceof RegExp) {
|
|
176
|
+
return new RegExp(input.source, input.flags.replace(/[gy]/g, ''));
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
const pattern = String(input).trim();
|
|
180
|
+
if (pattern === '') return null;
|
|
181
|
+
|
|
182
|
+
try {
|
|
183
|
+
return new RegExp(pattern);
|
|
184
|
+
} catch (error) {
|
|
185
|
+
const invalid = new Error(`Invalid filter regex "${pattern}": ${error.message}`);
|
|
186
|
+
invalid.code = 'INVALID_FILTER';
|
|
187
|
+
throw invalid;
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/**
|
|
192
|
+
* Keeps the test file paths that match a user-provided regex. An empty filter
|
|
193
|
+
* returns a copy of the input unchanged.
|
|
194
|
+
* @param {string[]} files
|
|
195
|
+
* @param {string|RegExp|null} [filter]
|
|
196
|
+
* @returns {string[]}
|
|
197
|
+
*/
|
|
198
|
+
export function filterTestFiles(files, filter) {
|
|
199
|
+
const regex = parseFilter(filter);
|
|
200
|
+
if (!regex) return [...files];
|
|
201
|
+
return files.filter(file => regex.test(file));
|
|
202
|
+
}
|
|
133
203
|
|
|
204
|
+
/**
|
|
205
|
+
* Lists changed JS/TS files vs `baseBranch` without logging or exiting.
|
|
206
|
+
* Includes commits from every author since the merge base, plus staged and
|
|
207
|
+
* unstaged edits. Throws when git itself fails.
|
|
208
|
+
* @param {string} baseBranch
|
|
209
|
+
* @param {string} [root]
|
|
210
|
+
* @returns {string[]}
|
|
211
|
+
*/
|
|
212
|
+
export function listChangedSourceFiles(baseBranch, root = process.cwd()) {
|
|
134
213
|
// Compare the merge base with HEAD so every file changed on this branch is
|
|
135
214
|
// included, regardless of which author committed it.
|
|
136
215
|
//
|
|
137
216
|
// Git is always invoked with an argument array (never through a shell) so
|
|
138
217
|
// refs and file paths can't inject commands, and output is de-duplicated
|
|
139
218
|
// in JS instead of piping through `sort -u`.
|
|
219
|
+
const gitFiles = (args) => execFileSync('git', args, {
|
|
220
|
+
cwd: root,
|
|
221
|
+
stdio: ['ignore', 'pipe', 'ignore']
|
|
222
|
+
}).toString();
|
|
223
|
+
|
|
224
|
+
const mergeBase = gitFiles(['merge-base', 'HEAD', baseBranch]).trim();
|
|
225
|
+
|
|
226
|
+
const seen = new Set();
|
|
227
|
+
const changedFiles = [
|
|
228
|
+
// Added or modified files between the merge base and HEAD
|
|
229
|
+
gitFiles(['diff', '--name-only', '--diff-filter=AM', `${mergeBase}..HEAD`]),
|
|
230
|
+
// Unstaged changes in the working tree
|
|
231
|
+
gitFiles(['diff', '--name-only', '--diff-filter=AM']),
|
|
232
|
+
// Staged changes
|
|
233
|
+
gitFiles(['diff', '--cached', '--name-only', '--diff-filter=AM'])
|
|
234
|
+
]
|
|
235
|
+
.flatMap(output => output.split(/\r?\n/))
|
|
236
|
+
.map(file => file.trim())
|
|
237
|
+
.filter(file => file.length > 0 && file.match(/\.(js|ts|jsx|tsx)$/))
|
|
238
|
+
// Defensive: ignore dependency/build/coverage artifacts even if git tracked them
|
|
239
|
+
.filter(file => !file.match(/(^|\/)(node_modules|coverage|dist|build)\/|(^|\/)\.git\//))
|
|
240
|
+
// De-duplicate (replaces `sort -u`); insertion order keeps first-seen wins
|
|
241
|
+
.filter(file => (seen.has(file) ? false : (seen.add(file), true)));
|
|
242
|
+
|
|
243
|
+
changedFiles.sort();
|
|
244
|
+
return changedFiles;
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
export function getChangedFiles(BASE_BRANCH, log = console.log, root = process.cwd()) {
|
|
248
|
+
// Check if BASE_BRANCH exists (also rejects ref-like options before use)
|
|
249
|
+
verifyBaseBranchExists(BASE_BRANCH, root);
|
|
250
|
+
|
|
140
251
|
try {
|
|
141
|
-
const
|
|
142
|
-
|
|
143
|
-
const mergeBase = gitFiles(['merge-base', 'HEAD', BASE_BRANCH]).trim();
|
|
144
|
-
|
|
145
|
-
const seen = new Set();
|
|
146
|
-
const changedFiles = [
|
|
147
|
-
// Added or renamed files between the merge base and HEAD
|
|
148
|
-
gitFiles(['diff', '--name-only', '--diff-filter=AM', `${mergeBase}..HEAD`]),
|
|
149
|
-
// Unstaged changes in the working tree
|
|
150
|
-
gitFiles(['diff', '--name-only', '--diff-filter=AM']),
|
|
151
|
-
// Staged changes
|
|
152
|
-
gitFiles(['diff', '--cached', '--name-only', '--diff-filter=AM'])
|
|
153
|
-
]
|
|
154
|
-
.flatMap(output => output.split('\n'))
|
|
155
|
-
.filter(f => f.trim().length > 0 && f.match(/\.(js|ts|jsx|tsx)$/))
|
|
156
|
-
// Defensive: ignore dependency/build/coverage artifacts even if git tracked them
|
|
157
|
-
.filter(f => !f.match(/(^|\/)(node_modules|coverage|dist|build)\/|(^|\/)\.git\//))
|
|
158
|
-
// De-duplicate (replaces `sort -u`); insertion order keeps first-seen wins
|
|
159
|
-
.filter(f => (seen.has(f) ? false : (seen.add(f), true)));
|
|
160
|
-
|
|
161
|
-
changedFiles.sort();
|
|
252
|
+
const changedFiles = listChangedSourceFiles(BASE_BRANCH, root);
|
|
162
253
|
log(`Changed files:\n${changedFiles.join('\n')}`);
|
|
163
254
|
return changedFiles;
|
|
164
255
|
} catch (error) {
|
|
@@ -167,7 +258,14 @@ export function getChangedFiles(BASE_BRANCH, log = console.log) {
|
|
|
167
258
|
}
|
|
168
259
|
}
|
|
169
260
|
|
|
170
|
-
|
|
261
|
+
/**
|
|
262
|
+
* Absolute path of the Jest binary the CLI invokes directly (no shell, no npx).
|
|
263
|
+
* @param {string} [root]
|
|
264
|
+
* @returns {string}
|
|
265
|
+
*/
|
|
266
|
+
export function resolveJestBin(root = process.cwd()) {
|
|
267
|
+
return path.resolve(root, 'node_modules', 'jest', 'bin', 'jest.js');
|
|
268
|
+
}
|
|
171
269
|
|
|
172
270
|
function runJest(jestArgs) {
|
|
173
271
|
console.log(` Jest command: npx jest ${jestArgs.join(' ')}`);
|
|
@@ -176,7 +274,7 @@ function runJest(jestArgs) {
|
|
|
176
274
|
// no npx), with an argument array, so file paths with spaces or special
|
|
177
275
|
// characters can't break the invocation.
|
|
178
276
|
try {
|
|
179
|
-
const jestBin =
|
|
277
|
+
const jestBin = resolveJestBin();
|
|
180
278
|
execFileSync(process.execPath, [jestBin, ...jestArgs], { stdio: 'inherit' });
|
|
181
279
|
} catch (err) {
|
|
182
280
|
// Log and continue so the coverage report still runs and CI can
|
|
@@ -186,7 +284,133 @@ function runJest(jestArgs) {
|
|
|
186
284
|
}
|
|
187
285
|
}
|
|
188
286
|
|
|
189
|
-
|
|
287
|
+
/**
|
|
288
|
+
* Resolves the test files a mode would run, without logging, running Jest, or exiting.
|
|
289
|
+
* `testsToRun` keeps CLI insertion order (changed tests first, then matches) and
|
|
290
|
+
* is filtered by `filter` when provided. `allTestsToRun` keeps the unfiltered
|
|
291
|
+
* list so callers can log both and let the user validate the filter.
|
|
292
|
+
* Full mode cannot discover related tests without Jest; `testsToRun` is then
|
|
293
|
+
* only the changed test files, and `jestTargets` is what `--findRelatedTests` receives.
|
|
294
|
+
* @param {string[]} files
|
|
295
|
+
* @param {string} mode
|
|
296
|
+
* @param {number} [depth]
|
|
297
|
+
* @param {string} [root]
|
|
298
|
+
* @param {string[]} [jestArgs] extra Jest CLI flags to append (e.g. `--maxWorkers=2`)
|
|
299
|
+
* @param {string|RegExp|null} [filter] regex matched against the final test paths
|
|
300
|
+
*/
|
|
301
|
+
export function resolveTestPlan(files, mode, depth = 2, root = process.cwd(), jestArgs = [], filter = null) {
|
|
302
|
+
const { sourceFiles, testFiles } = separateSourceAndTestFiles(files);
|
|
303
|
+
const filterRegex = parseFilter(filter);
|
|
304
|
+
const extra = parseJestArgs(jestArgs);
|
|
305
|
+
|
|
306
|
+
if (mode === 'full') {
|
|
307
|
+
const allTestsToRun = [...testFiles];
|
|
308
|
+
const testsToRun = filterTestFiles(allTestsToRun, filterRegex);
|
|
309
|
+
const jestTargets = [...sourceFiles, ...testsToRun];
|
|
310
|
+
// Jest discovers the related specs itself in full mode, so the filter must
|
|
311
|
+
// also reach Jest. Modern Jest spells the option in the plural.
|
|
312
|
+
const fullExtra = filterRegex && !hasJestPathPattern(extra)
|
|
313
|
+
? [...extra, '--testPathPatterns', filterRegex.source]
|
|
314
|
+
: extra;
|
|
315
|
+
|
|
316
|
+
return {
|
|
317
|
+
mode,
|
|
318
|
+
depth,
|
|
319
|
+
filter: filterRegex ? filterRegex.source : null,
|
|
320
|
+
sourceFiles,
|
|
321
|
+
testFiles,
|
|
322
|
+
mappings: [],
|
|
323
|
+
allTestsToRun,
|
|
324
|
+
testsToRun,
|
|
325
|
+
jestTargets,
|
|
326
|
+
jestArgs: ['--findRelatedTests', '--passWithNoTests', '--coverage', ...jestTargets, ...fullExtra],
|
|
327
|
+
delegatedToJest: true
|
|
328
|
+
};
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
// Fast: naming-convention mapping with a direct-import fallback.
|
|
332
|
+
// Smart: naming-convention mapping plus a depth-limited reverse-dependency walk.
|
|
333
|
+
const testFilesToRun = new Set(testFiles);
|
|
334
|
+
const allTestFilesToRun = new Set(testFiles);
|
|
335
|
+
const mappings = [];
|
|
336
|
+
|
|
337
|
+
sourceFiles.forEach(sourceFile => {
|
|
338
|
+
let relatedTests;
|
|
339
|
+
let matchType;
|
|
340
|
+
|
|
341
|
+
if (mode === 'smart') {
|
|
342
|
+
relatedTests = findRelatedTestFilesBySource(sourceFile, { maxDepth: depth, root });
|
|
343
|
+
matchType = `naming + import graph, depth ≤ ${depth}`;
|
|
344
|
+
} else {
|
|
345
|
+
relatedTests = findTestFilesForSource(sourceFile, root);
|
|
346
|
+
matchType = 'naming convention';
|
|
347
|
+
|
|
348
|
+
if (relatedTests.length === 0) {
|
|
349
|
+
relatedTests = findTestFilesByImport(sourceFile, root);
|
|
350
|
+
if (relatedTests.length > 0) {
|
|
351
|
+
matchType = 'import scan';
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
const filteredTests = filterTestFiles(relatedTests, filterRegex);
|
|
357
|
+
mappings.push({
|
|
358
|
+
source: sourceFile,
|
|
359
|
+
tests: filteredTests,
|
|
360
|
+
allTests: [...relatedTests],
|
|
361
|
+
matchType
|
|
362
|
+
});
|
|
363
|
+
relatedTests.forEach(test => allTestFilesToRun.add(test));
|
|
364
|
+
filteredTests.forEach(test => testFilesToRun.add(test));
|
|
365
|
+
});
|
|
366
|
+
|
|
367
|
+
const allTestsToRun = Array.from(allTestFilesToRun);
|
|
368
|
+
const testsToRun = filterTestFiles(allTestsToRun, filterRegex);
|
|
369
|
+
return {
|
|
370
|
+
mode,
|
|
371
|
+
depth,
|
|
372
|
+
filter: filterRegex ? filterRegex.source : null,
|
|
373
|
+
sourceFiles,
|
|
374
|
+
testFiles,
|
|
375
|
+
mappings,
|
|
376
|
+
allTestsToRun,
|
|
377
|
+
testsToRun,
|
|
378
|
+
jestTargets: testsToRun,
|
|
379
|
+
jestArgs: ['--passWithNoTests', '--coverage', ...testsToRun, ...extra],
|
|
380
|
+
delegatedToJest: false
|
|
381
|
+
};
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
function hasJestPathPattern(jestArgs) {
|
|
385
|
+
return jestArgs.some(arg =>
|
|
386
|
+
arg === '--testPathPatterns' ||
|
|
387
|
+
arg.startsWith('--testPathPatterns=') ||
|
|
388
|
+
arg === '--testPathPattern' ||
|
|
389
|
+
arg.startsWith('--testPathPattern=')
|
|
390
|
+
);
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
/**
|
|
394
|
+
* Logs the full candidate list and the filtered list so the user can validate
|
|
395
|
+
* the regex before any tests run.
|
|
396
|
+
* @param {ReturnType<typeof resolveTestPlan>} plan
|
|
397
|
+
* @param {(...args: any[]) => void} [log]
|
|
398
|
+
*/
|
|
399
|
+
function logFilteredTestFiles(plan, log = console.log) {
|
|
400
|
+
if (!plan.filter) return;
|
|
401
|
+
|
|
402
|
+
log(`\n🔎 Filter regex: /${plan.filter}/`);
|
|
403
|
+
log(` All test files before filter (${plan.allTestsToRun.length}):`);
|
|
404
|
+
plan.allTestsToRun.forEach(file => log(` - ${file}`));
|
|
405
|
+
log(` Test files after filter (${plan.testsToRun.length}):`);
|
|
406
|
+
if (plan.testsToRun.length === 0) {
|
|
407
|
+
log(' (none)');
|
|
408
|
+
} else {
|
|
409
|
+
plan.testsToRun.forEach(file => log(` - ${file}`));
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
function runRelatedTests(files, mode, depth = 2, jestArgs = [], filter = null) {
|
|
190
414
|
if (files.length === 0) {
|
|
191
415
|
console.log('✅ No changed source files found.');
|
|
192
416
|
exit(0);
|
|
@@ -194,8 +418,8 @@ function runRelatedTests(files, mode, depth = 2) {
|
|
|
194
418
|
|
|
195
419
|
console.log('🔍 Analyzing changed files for optimal test execution...');
|
|
196
420
|
|
|
197
|
-
|
|
198
|
-
const { sourceFiles, testFiles } =
|
|
421
|
+
const plan = resolveTestPlan(files, mode, depth, process.cwd(), jestArgs, filter);
|
|
422
|
+
const { sourceFiles, testFiles } = plan;
|
|
199
423
|
|
|
200
424
|
console.log(`\n📊 Changed files breakdown:`);
|
|
201
425
|
console.log(` Source files: ${sourceFiles.length}`);
|
|
@@ -209,9 +433,11 @@ function runRelatedTests(files, mode, depth = 2) {
|
|
|
209
433
|
testFiles.forEach(file => console.log(` - ${file}`));
|
|
210
434
|
}
|
|
211
435
|
|
|
436
|
+
logFilteredTestFiles(plan);
|
|
437
|
+
|
|
212
438
|
// Full mode delegates discovery to Jest, so pass the changed files themselves.
|
|
213
439
|
if (mode === 'full') {
|
|
214
|
-
const jestTargets =
|
|
440
|
+
const jestTargets = plan.jestTargets;
|
|
215
441
|
|
|
216
442
|
if (jestTargets.length === 0) {
|
|
217
443
|
console.log('\n⚠️ No changed source or test files found to run.');
|
|
@@ -219,47 +445,26 @@ function runRelatedTests(files, mode, depth = 2) {
|
|
|
219
445
|
}
|
|
220
446
|
|
|
221
447
|
console.log(`\n📝 Test strategy: full (Jest --findRelatedTests, unbounded traversal)`);
|
|
222
|
-
console.log(` Running tests related to ${sourceFiles.length} source file(s) + ${
|
|
448
|
+
console.log(` Running tests related to ${sourceFiles.length} source file(s) + ${plan.testsToRun.length} changed test(s)`);
|
|
223
449
|
console.log(` ⚠️ If this expands to too many tests, switch to --mode smart`);
|
|
224
450
|
console.log(' Files passed to Jest:');
|
|
225
451
|
jestTargets.forEach(file => console.log(` - ${file}`));
|
|
226
452
|
|
|
227
|
-
runJest(
|
|
453
|
+
runJest(plan.jestArgs);
|
|
228
454
|
return;
|
|
229
455
|
}
|
|
230
456
|
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
let relatedTests;
|
|
237
|
-
let matchType;
|
|
238
|
-
|
|
239
|
-
if (mode === 'smart') {
|
|
240
|
-
relatedTests = findRelatedTestFilesBySource(sourceFile, { maxDepth: depth });
|
|
241
|
-
matchType = `naming + import graph, depth ≤ ${depth}`;
|
|
457
|
+
plan.mappings.forEach(({ source, tests, allTests, matchType }) => {
|
|
458
|
+
if (tests.length > 0) {
|
|
459
|
+
console.log(` ✓ ${source} → ${tests.length} test file(s) (${matchType})`);
|
|
460
|
+
} else if (allTests.length > 0) {
|
|
461
|
+
console.log(` ⚠ ${source} → No test file after filter (${allTests.length} matched before filter)`);
|
|
242
462
|
} else {
|
|
243
|
-
|
|
244
|
-
matchType = 'naming convention';
|
|
245
|
-
|
|
246
|
-
if (relatedTests.length === 0) {
|
|
247
|
-
relatedTests = findTestFilesByImport(sourceFile);
|
|
248
|
-
if (relatedTests.length > 0) {
|
|
249
|
-
matchType = 'import scan';
|
|
250
|
-
}
|
|
251
|
-
}
|
|
252
|
-
}
|
|
253
|
-
|
|
254
|
-
if (relatedTests.length > 0) {
|
|
255
|
-
console.log(` ✓ ${sourceFile} → ${relatedTests.length} test file(s) (${matchType})`);
|
|
256
|
-
relatedTests.forEach(test => testFilesToRun.add(test));
|
|
257
|
-
} else {
|
|
258
|
-
console.log(` ⚠ ${sourceFile} → No test file found`);
|
|
463
|
+
console.log(` ⚠ ${source} → No test file found`);
|
|
259
464
|
}
|
|
260
465
|
});
|
|
261
466
|
|
|
262
|
-
const finalTestFiles =
|
|
467
|
+
const finalTestFiles = plan.testsToRun;
|
|
263
468
|
|
|
264
469
|
if (finalTestFiles.length === 0) {
|
|
265
470
|
console.log('\n⚠️ No test files found to run.');
|
|
@@ -281,61 +486,55 @@ function runRelatedTests(files, mode, depth = 2) {
|
|
|
281
486
|
console.log(` Source files detected: ${sourceFiles.length}`);
|
|
282
487
|
}
|
|
283
488
|
|
|
284
|
-
runJest(
|
|
489
|
+
runJest(plan.jestArgs);
|
|
285
490
|
}
|
|
286
491
|
|
|
287
492
|
/**
|
|
288
493
|
* Dry run: only resolve the test files that the selected mode would run,
|
|
289
494
|
* then print one path per line and exit without running Jest or checking
|
|
290
495
|
* coverage. The stdout is clean enough for another tool to consume:
|
|
291
|
-
* node index.js --
|
|
496
|
+
* node index.js --dryRun true --files src/a.js --base origin/main
|
|
497
|
+
* When a filter is given, the before/after filter log goes to stderr so
|
|
498
|
+
* stdout stays a clean one-path-per-line list.
|
|
292
499
|
* Errors still go to stderr via the catch in main().
|
|
293
500
|
*
|
|
294
501
|
* @param {string[]} files - Changed source and test files (repo-relative)
|
|
295
502
|
* @param {string} mode - Execution mode (fast, smart, or full)
|
|
296
503
|
* @param {number} depth - Max reverse-dependency depth for smart mode
|
|
504
|
+
* @param {string|RegExp|null} [filter] regex matched against the final test paths
|
|
297
505
|
*/
|
|
298
|
-
export function dryRun(files, mode, depth = 2) {
|
|
506
|
+
export function dryRun(files, mode, depth = 2, filter = null) {
|
|
299
507
|
if (files.length === 0) {
|
|
300
508
|
// Keep stdout a clean file list; informational messages go to stderr.
|
|
301
509
|
console.error('✅ No changed source files found.');
|
|
302
510
|
exit(0);
|
|
303
511
|
}
|
|
304
512
|
|
|
305
|
-
const
|
|
513
|
+
const plan = resolveTestPlan(files, mode, depth, process.cwd(), [], filter);
|
|
514
|
+
|
|
515
|
+
// Filter diagnostics stay on stderr so stdout remains a clean list.
|
|
516
|
+
logFilteredTestFiles(plan, console.error);
|
|
306
517
|
|
|
307
518
|
// Full mode delegates discovery to Jest; without running it, the only
|
|
308
|
-
// guaranteed output is the changed files themselves.
|
|
519
|
+
// guaranteed output is the changed test files themselves.
|
|
309
520
|
if (mode === 'full') {
|
|
310
521
|
// Keep stdout clean (one path per line) for other tools; warn on stderr.
|
|
311
522
|
console.error('⚠️ full mode relies on Jest --findRelatedTests; --dry-run prints only the changed test files.');
|
|
312
|
-
testFiles.forEach(file => console.log(file));
|
|
313
|
-
exit(0);
|
|
314
523
|
}
|
|
315
524
|
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
// Same matching rules as the real run (see runRelatedTests), just no Jest.
|
|
320
|
-
const relatedTests = mode === 'smart'
|
|
321
|
-
? findRelatedTestFilesBySource(sourceFile, { maxDepth: depth })
|
|
322
|
-
: findTestFilesForSource(sourceFile);
|
|
323
|
-
|
|
324
|
-
if (mode === 'fast' && relatedTests.length === 0) {
|
|
325
|
-
relatedTests.push(...findTestFilesByImport(sourceFile));
|
|
326
|
-
}
|
|
327
|
-
|
|
328
|
-
relatedTests.forEach(test => testFilesToRun.add(test));
|
|
329
|
-
});
|
|
330
|
-
|
|
331
|
-
Array.from(testFilesToRun).sort().forEach(file => console.log(file));
|
|
525
|
+
// In full mode testsToRun is the changed test files (already filtered),
|
|
526
|
+
// which is the same as plan.testFiles when no filter is given.
|
|
527
|
+
[...plan.testsToRun].sort().forEach(file => console.log(file));
|
|
332
528
|
exit(0);
|
|
333
529
|
}
|
|
334
530
|
|
|
335
|
-
function getChangedLines(filePath, BASE_BRANCH) {
|
|
531
|
+
export function getChangedLines(filePath, BASE_BRANCH, root = process.cwd()) {
|
|
336
532
|
// Argument array + `--` separator keeps file paths (and the ref, already
|
|
337
533
|
// validated in verifyBaseBranchExists) out of any shell interpretation.
|
|
338
|
-
const diff = execFileSync('git', ['diff', '-U0', BASE_BRANCH, '--', filePath], {
|
|
534
|
+
const diff = execFileSync('git', ['diff', '-U0', BASE_BRANCH, '--', filePath], {
|
|
535
|
+
cwd: root,
|
|
536
|
+
stdio: ['ignore', 'pipe', 'ignore']
|
|
537
|
+
}).toString();
|
|
339
538
|
const lines = [];
|
|
340
539
|
|
|
341
540
|
const hunkRegex = /^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/gm;
|
|
@@ -351,14 +550,16 @@ function getChangedLines(filePath, BASE_BRANCH) {
|
|
|
351
550
|
return lines;
|
|
352
551
|
}
|
|
353
552
|
|
|
354
|
-
export function parseLcov(LCOV_PATH) {
|
|
553
|
+
export function parseLcov(LCOV_PATH, root = process.cwd()) {
|
|
355
554
|
const lcovRaw = fs.readFileSync(LCOV_PATH, 'utf8');
|
|
356
555
|
const files = {};
|
|
357
556
|
let currentFile = null;
|
|
358
557
|
|
|
359
558
|
lcovRaw.split('\n').forEach(line => {
|
|
360
559
|
if (line.startsWith('SF:')) {
|
|
361
|
-
|
|
560
|
+
// Absolute SF paths stay absolute. Relative ones resolve against `root`,
|
|
561
|
+
// which is the process cwd for the CLI.
|
|
562
|
+
currentFile = path.resolve(root, line.substring(3).trim());
|
|
362
563
|
files[currentFile] = {
|
|
363
564
|
coverableLines: new Set(),
|
|
364
565
|
uncoveredLines: new Set()
|
|
@@ -475,6 +676,107 @@ export function formatMissedLinesSummary(uncoveredByFile) {
|
|
|
475
676
|
];
|
|
476
677
|
}
|
|
477
678
|
|
|
679
|
+
/**
|
|
680
|
+
* Reads lcov and keeps only source files that participate in the coverage check.
|
|
681
|
+
* Throws an error with code LCOV_NOT_FOUND when the report file is missing.
|
|
682
|
+
* @param {string[]} changedFiles
|
|
683
|
+
* @param {string} lcovPath
|
|
684
|
+
* @param {string} [root]
|
|
685
|
+
*/
|
|
686
|
+
export function loadCoverageIndex(changedFiles, lcovPath, root = process.cwd()) {
|
|
687
|
+
const resolvedLcov = path.resolve(root, lcovPath);
|
|
688
|
+
if (!fs.existsSync(resolvedLcov)) {
|
|
689
|
+
const error = new Error('lcov.info not found. Make sure coverage ran correctly.');
|
|
690
|
+
error.code = 'LCOV_NOT_FOUND';
|
|
691
|
+
error.lcovPath = resolvedLcov;
|
|
692
|
+
throw error;
|
|
693
|
+
}
|
|
694
|
+
|
|
695
|
+
return {
|
|
696
|
+
lcovPath: resolvedLcov,
|
|
697
|
+
coverageByFile: parseLcov(resolvedLcov, root),
|
|
698
|
+
relevantFiles: getJsOnlyFiles(changedFiles)
|
|
699
|
+
};
|
|
700
|
+
}
|
|
701
|
+
|
|
702
|
+
/**
|
|
703
|
+
* Classifies one file's changed lines against an lcov index.
|
|
704
|
+
* Line numbers come from `git diff -U0 <base> -- <file>` (working tree vs the ref).
|
|
705
|
+
* @param {string} relPath
|
|
706
|
+
* @param {Record<string, {coverableLines: Set<number>, uncoveredLines: Set<number>}>} coverageByFile
|
|
707
|
+
* @param {string} baseBranch
|
|
708
|
+
* @param {string} [root]
|
|
709
|
+
*/
|
|
710
|
+
export function analyzeChangedFile(relPath, coverageByFile, baseBranch, root = process.cwd()) {
|
|
711
|
+
const absolutePath = path.resolve(root, relPath);
|
|
712
|
+
const changedLines = getChangedLines(relPath, baseBranch, root);
|
|
713
|
+
const fileCoverage = coverageByFile[absolutePath];
|
|
714
|
+
const { coveredLines, uncoveredLines } = classifyChangedLineCoverage(changedLines, fileCoverage);
|
|
715
|
+
const trackedChangedLines = coveredLines.length + uncoveredLines.length;
|
|
716
|
+
|
|
717
|
+
return {
|
|
718
|
+
filePath: relPath,
|
|
719
|
+
absolutePath,
|
|
720
|
+
changedLines,
|
|
721
|
+
coveredLines,
|
|
722
|
+
uncoveredLines,
|
|
723
|
+
trackedChangedLines,
|
|
724
|
+
hasCoverageInfo: Boolean(fileCoverage),
|
|
725
|
+
fileCoverage: trackedChangedLines > 0
|
|
726
|
+
? `${((coveredLines.length / trackedChangedLines) * 100).toFixed(2)}%`
|
|
727
|
+
: '-',
|
|
728
|
+
status: uncoveredLines.length > 0 ? '🚨' : trackedChangedLines > 0 ? '✅' : 'ℹ️'
|
|
729
|
+
};
|
|
730
|
+
}
|
|
731
|
+
|
|
732
|
+
/**
|
|
733
|
+
* Totals coverable changed lines the same way the CLI threshold does.
|
|
734
|
+
* Files with an empty diff are ignored. Lines absent from lcov are not counted.
|
|
735
|
+
* @param {ReturnType<typeof analyzeChangedFile>[]} fileResults
|
|
736
|
+
* @param {number} coverageLimit
|
|
737
|
+
*/
|
|
738
|
+
export function summarizeChangedLineResults(fileResults, coverageLimit) {
|
|
739
|
+
let totalChanged = 0;
|
|
740
|
+
let totalNotCovered = 0;
|
|
741
|
+
const uncoveredByFile = [];
|
|
742
|
+
const rows = [];
|
|
743
|
+
|
|
744
|
+
fileResults.forEach(result => {
|
|
745
|
+
if (result.changedLines.length === 0) return;
|
|
746
|
+
|
|
747
|
+
totalChanged += result.trackedChangedLines;
|
|
748
|
+
totalNotCovered += result.uncoveredLines.length;
|
|
749
|
+
|
|
750
|
+
if (result.uncoveredLines.length > 0) {
|
|
751
|
+
uncoveredByFile.push({
|
|
752
|
+
filePath: result.filePath,
|
|
753
|
+
lines: result.uncoveredLines
|
|
754
|
+
});
|
|
755
|
+
}
|
|
756
|
+
|
|
757
|
+
rows.push({
|
|
758
|
+
filePath: result.filePath,
|
|
759
|
+
covered: result.coveredLines.length,
|
|
760
|
+
uncovered: result.uncoveredLines.length,
|
|
761
|
+
trackedChangedLines: result.trackedChangedLines,
|
|
762
|
+
fileCoverage: result.fileCoverage,
|
|
763
|
+
status: result.status
|
|
764
|
+
});
|
|
765
|
+
});
|
|
766
|
+
|
|
767
|
+
const summary = totalChanged > 0
|
|
768
|
+
? summarizeCoverageResult(totalChanged, totalNotCovered, coverageLimit)
|
|
769
|
+
: { overallCoverage: null, passed: true, icon: '✅' };
|
|
770
|
+
|
|
771
|
+
return {
|
|
772
|
+
totalChanged,
|
|
773
|
+
totalNotCovered,
|
|
774
|
+
uncoveredByFile,
|
|
775
|
+
rows,
|
|
776
|
+
...summary
|
|
777
|
+
};
|
|
778
|
+
}
|
|
779
|
+
|
|
478
780
|
function reportUncoveredChangedLines(changedFiles, LCOV_PATH, BASE_BRANCH, COVERAGE_LIMIT, SHOW_COVERED, CI = false, CI_REPORT_PATH) {
|
|
479
781
|
if (!fs.existsSync(LCOV_PATH)) {
|
|
480
782
|
console.error('❌ lcov.info not found. Make sure coverage ran correctly.');
|
|
@@ -489,11 +791,9 @@ function reportUncoveredChangedLines(changedFiles, LCOV_PATH, BASE_BRANCH, COVER
|
|
|
489
791
|
console.log(`\n🔍 Checking coverage of changed lines vs branch: ${BASE_BRANCH}\n`);
|
|
490
792
|
}
|
|
491
793
|
|
|
492
|
-
const coverageByFile =
|
|
493
|
-
|
|
494
|
-
changedFiles = getJsOnlyFiles(changedFiles);
|
|
794
|
+
const { coverageByFile, relevantFiles } = loadCoverageIndex(changedFiles, LCOV_PATH);
|
|
495
795
|
|
|
496
|
-
if (
|
|
796
|
+
if (relevantFiles.length === 0) {
|
|
497
797
|
if (!CI) {
|
|
498
798
|
console.log('✅ No relevant files found for coverage check.');
|
|
499
799
|
}
|
|
@@ -501,70 +801,39 @@ function reportUncoveredChangedLines(changedFiles, LCOV_PATH, BASE_BRANCH, COVER
|
|
|
501
801
|
}
|
|
502
802
|
|
|
503
803
|
if (!CI) {
|
|
504
|
-
console.log('Files with changed lines:',
|
|
804
|
+
console.log('Files with changed lines:', relevantFiles.join('\n'));
|
|
505
805
|
}
|
|
506
806
|
|
|
507
|
-
|
|
508
|
-
let totalNotCovered = 0;
|
|
509
|
-
const uncoveredByFile = [];
|
|
510
|
-
const rows = [];
|
|
807
|
+
const fileResults = [];
|
|
511
808
|
|
|
512
|
-
|
|
513
|
-
const
|
|
514
|
-
|
|
809
|
+
relevantFiles.forEach(relPath => {
|
|
810
|
+
const result = analyzeChangedFile(relPath, coverageByFile, BASE_BRANCH);
|
|
811
|
+
fileResults.push(result);
|
|
515
812
|
|
|
516
|
-
if (
|
|
813
|
+
if (result.changedLines.length === 0) {
|
|
517
814
|
if (!CI) {
|
|
518
|
-
console.log(`ℹ️ ${
|
|
815
|
+
console.log(`ℹ️ ${result.absolutePath} - No changed lines detected.`);
|
|
519
816
|
}
|
|
520
817
|
return;
|
|
521
818
|
}
|
|
522
819
|
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
console.log(`⚠️ No coverage info for: ${absPath}`);
|
|
526
|
-
}
|
|
527
|
-
|
|
528
|
-
const {
|
|
529
|
-
coveredLines,
|
|
530
|
-
uncoveredLines
|
|
531
|
-
} = classifyChangedLineCoverage(addedLines, fileCoverage);
|
|
532
|
-
const trackedChangedLines = coveredLines.length + uncoveredLines.length;
|
|
533
|
-
|
|
534
|
-
totalChanged += trackedChangedLines;
|
|
535
|
-
totalNotCovered += uncoveredLines.length;
|
|
536
|
-
|
|
537
|
-
if (uncoveredLines.length > 0) {
|
|
538
|
-
uncoveredByFile.push({
|
|
539
|
-
filePath: relPath,
|
|
540
|
-
lines: uncoveredLines
|
|
541
|
-
});
|
|
820
|
+
if (!result.hasCoverageInfo && !CI) {
|
|
821
|
+
console.log(`⚠️ No coverage info for: ${result.absolutePath}`);
|
|
542
822
|
}
|
|
543
823
|
|
|
544
|
-
rows.push({
|
|
545
|
-
filePath: relPath,
|
|
546
|
-
covered: coveredLines.length,
|
|
547
|
-
uncovered: uncoveredLines.length,
|
|
548
|
-
trackedChangedLines,
|
|
549
|
-
fileCoverage: trackedChangedLines > 0
|
|
550
|
-
? `${((coveredLines.length / trackedChangedLines) * 100).toFixed(2)}%`
|
|
551
|
-
: '-',
|
|
552
|
-
status: uncoveredLines.length > 0 ? '🚨' : trackedChangedLines > 0 ? '✅' : 'ℹ️'
|
|
553
|
-
});
|
|
554
|
-
|
|
555
824
|
if (!CI) {
|
|
556
|
-
if (uncoveredLines.length > 0) {
|
|
557
|
-
console.log(`🚨 ${
|
|
558
|
-
} else if (trackedChangedLines > 0) {
|
|
559
|
-
console.log(`✅ ${
|
|
825
|
+
if (result.uncoveredLines.length > 0) {
|
|
826
|
+
console.log(`🚨 ${result.absolutePath} - Uncovered changed lines: [${result.uncoveredLines.join(', ')}]`);
|
|
827
|
+
} else if (result.trackedChangedLines > 0) {
|
|
828
|
+
console.log(`✅ ${result.absolutePath} - All changed lines are covered`);
|
|
560
829
|
}
|
|
561
830
|
|
|
562
|
-
console.log(` Total coverable changed lines: ${trackedChangedLines}, Covered: ${coveredLines.length}, Uncovered: ${uncoveredLines.length}`)
|
|
563
|
-
if (SHOW_COVERED && coveredLines.length > 0) {
|
|
564
|
-
console.log(` Covered lines: [${coveredLines.join(', ')}]`);
|
|
831
|
+
console.log(` Total coverable changed lines: ${result.trackedChangedLines}, Covered: ${result.coveredLines.length}, Uncovered: ${result.uncoveredLines.length}`)
|
|
832
|
+
if (SHOW_COVERED && result.coveredLines.length > 0) {
|
|
833
|
+
console.log(` Covered lines: [${result.coveredLines.join(', ')}]`);
|
|
565
834
|
}
|
|
566
|
-
if (trackedChangedLines > 0) {
|
|
567
|
-
console.log(` Coverage for changed lines: ${((coveredLines.length / trackedChangedLines) * 100).toFixed(2)}%`);
|
|
835
|
+
if (result.trackedChangedLines > 0) {
|
|
836
|
+
console.log(` Coverage for changed lines: ${((result.coveredLines.length / result.trackedChangedLines) * 100).toFixed(2)}%`);
|
|
568
837
|
} else {
|
|
569
838
|
console.log(` No coverable lines in this file's changed lines (e.g., imports, comments).`);
|
|
570
839
|
}
|
|
@@ -572,9 +841,15 @@ function reportUncoveredChangedLines(changedFiles, LCOV_PATH, BASE_BRANCH, COVER
|
|
|
572
841
|
});
|
|
573
842
|
|
|
574
843
|
// Cumulative coverage check
|
|
575
|
-
const {
|
|
576
|
-
|
|
577
|
-
|
|
844
|
+
const {
|
|
845
|
+
overallCoverage,
|
|
846
|
+
passed,
|
|
847
|
+
icon,
|
|
848
|
+
totalChanged,
|
|
849
|
+
totalNotCovered,
|
|
850
|
+
rows,
|
|
851
|
+
uncoveredByFile
|
|
852
|
+
} = summarizeChangedLineResults(fileResults, COVERAGE_LIMIT);
|
|
578
853
|
|
|
579
854
|
if (CI) {
|
|
580
855
|
const report = buildMarkdownCoverageReport(rows, {
|