targeted-mutation 0.3.0 → 0.4.0
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 +22 -3
- package/bin/tmt.mjs +54 -10
- package/docs/how-it-works.svg +99 -180
- package/docs/why-targeted.svg +117 -0
- package/package.json +5 -5
- package/src/analysis.mjs +32 -13
- package/src/checkpoint.mjs +3 -0
- package/src/cli-output.mjs +66 -16
- package/src/conventional.mjs +40 -4
- package/src/operator-analysis.mjs +5 -0
- package/src/project-config.mjs +6 -0
- package/src/shard.mjs +6 -1
- package/src/standard-session.mjs +33 -19
- package/src/type-equivalence.mjs +193 -27
- package/src/vitest.mjs +179 -17
package/src/standard-session.mjs
CHANGED
|
@@ -9,7 +9,7 @@ import { inside } from './vitest.mjs';
|
|
|
9
9
|
// Vitest and Vite are loaded on every run. Node keeps their compiled code between runs when it can.
|
|
10
10
|
try { enableCompileCache?.(); } catch { /* The cache is an optimisation only. */ }
|
|
11
11
|
const input = JSON.parse(readFileSync(process.argv[2], 'utf8'));
|
|
12
|
-
const { workspace, config, files, selectedSpecs, mutants, setup, workerRunner, output, temporary, isolatedTrials, concurrency = 1, verifyTrials = 0, awaitsExtras = false, runTimeout = 60_000 } = input;
|
|
12
|
+
const { workspace, config, files, selectedSpecs, mutants, setup, workerRunner, output, temporary, isolatedTrials, concurrency = 1, verifyTrials = 0, awaitsExtras = false, runTimeout = 60_000, baselineTimeout = runTimeout, baselineWorkers } = input;
|
|
13
13
|
const destination = resolve(temporary, 'coverage.jsonl');
|
|
14
14
|
const record = event => appendFileSync(output, JSON.stringify(event) + '\n');
|
|
15
15
|
const lanes = [];
|
|
@@ -52,17 +52,17 @@ function follow(path) {
|
|
|
52
52
|
};
|
|
53
53
|
}
|
|
54
54
|
|
|
55
|
+
function filterSelectedSpecs(allSpecs) {
|
|
56
|
+
if (!selectedSpecs?.length) return allSpecs;
|
|
57
|
+
const allowed = new Set(selectedSpecs.map(({ project, file }) => JSON.stringify([project ?? '', file])));
|
|
58
|
+
return allSpecs.filter(spec => allowed.has(JSON.stringify([spec.project.name ?? '', inside(workspace, spec.moduleId)])));
|
|
59
|
+
}
|
|
60
|
+
|
|
55
61
|
// A lane is one Vitest instance with its own worker. The first lane also runs the baseline and the isolated trials.
|
|
56
|
-
async function openLane(index, serial = false) {
|
|
57
|
-
const lane = { snapshot: null, events: resolve(temporary, `trials-${index}.jsonl`), serial };
|
|
62
|
+
async function openLane(index, serial = false, workerOverride = undefined) {
|
|
63
|
+
const lane = { snapshot: null, events: resolve(temporary, `trials-${index}.jsonl`), serial, workerOverride };
|
|
58
64
|
lane.context = await createContext(lane);
|
|
59
|
-
|
|
60
|
-
if (selectedSpecs?.length) {
|
|
61
|
-
const allowed = new Set(selectedSpecs.map(({ project, file }) => JSON.stringify([project ?? '', file])));
|
|
62
|
-
lane.specs = allSpecs.filter(spec => allowed.has(JSON.stringify([spec.project.name ?? '', inside(workspace, spec.moduleId)])));
|
|
63
|
-
} else {
|
|
64
|
-
lane.specs = allSpecs;
|
|
65
|
-
}
|
|
65
|
+
lane.specs = filterSelectedSpecs(await lane.context.globTestSpecifications(files));
|
|
66
66
|
return lane;
|
|
67
67
|
}
|
|
68
68
|
|
|
@@ -115,21 +115,21 @@ async function runInThread(lane, plans, limit, deadline) {
|
|
|
115
115
|
.filter(([, list]) => list.length));
|
|
116
116
|
await Promise.race([lane.context.close(), new Promise(resolveClose => setTimeout(resolveClose, 5_000))]);
|
|
117
117
|
lane.context = await createContext(lane);
|
|
118
|
-
lane.specs = await lane.context.globTestSpecifications(files);
|
|
118
|
+
lane.specs = filterSelectedSpecs(await lane.context.globTestSpecifications(files));
|
|
119
119
|
}
|
|
120
120
|
return events;
|
|
121
121
|
}
|
|
122
122
|
|
|
123
|
-
async function run(specs, state, lane = lanes[0]) {
|
|
123
|
+
async function run(specs, state, lane = lanes[0], timeoutMs = runTimeout) {
|
|
124
124
|
lane.snapshot = null;
|
|
125
125
|
rmSync(destination, { force: true });
|
|
126
126
|
lane.context.provide('tmtSession', { ...state, destination });
|
|
127
127
|
const timeout = setTimeout(() => {
|
|
128
128
|
record(state.id === undefined
|
|
129
|
-
? { baseline: { status: 'timeout' } }
|
|
129
|
+
? { baseline: { status: 'timeout', timeoutSeconds: Math.round(timeoutMs / 1000) } }
|
|
130
130
|
: { id: state.id, status: 'timeout', statusReason: 'Vitest did not finish before its deadline' });
|
|
131
131
|
process.exit(124);
|
|
132
|
-
},
|
|
132
|
+
}, timeoutMs);
|
|
133
133
|
try {
|
|
134
134
|
await lane.context.runTestSpecifications(specs);
|
|
135
135
|
if (!lane.snapshot) throw new Error('Vitest did not report a completed run');
|
|
@@ -172,8 +172,14 @@ try {
|
|
|
172
172
|
// its mutations are kept per file.
|
|
173
173
|
const oneByOne = { maxWorkers: 1, fileParallelism: false };
|
|
174
174
|
const beside = concurrency === 1 || isolatedTrials ? oneByOne : { maxWorkers: concurrency };
|
|
175
|
+
const resolveWorkers = lane => {
|
|
176
|
+
if (lane.workerOverride !== undefined) {
|
|
177
|
+
return lane.workerOverride === 1 ? oneByOne : { maxWorkers: lane.workerOverride };
|
|
178
|
+
}
|
|
179
|
+
return lane.serial ? oneByOne : beside;
|
|
180
|
+
};
|
|
175
181
|
createContext = async lane => {
|
|
176
|
-
const workers = lane
|
|
182
|
+
const workers = resolveWorkers(lane);
|
|
177
183
|
const created = await createVitest('test', {
|
|
178
184
|
root: workspace, config, watch: false, api: false, ui: false, cache: false,
|
|
179
185
|
pool: 'threads', isolate: true, maxConcurrency: 1, ...workers,
|
|
@@ -194,17 +200,25 @@ try {
|
|
|
194
200
|
}
|
|
195
201
|
return created;
|
|
196
202
|
};
|
|
197
|
-
|
|
198
|
-
const
|
|
203
|
+
const trialWorkers = concurrency === 1 || isolatedTrials ? 1 : concurrency;
|
|
204
|
+
const distinctBaselineLane = baselineWorkers !== undefined && baselineWorkers !== trialWorkers;
|
|
205
|
+
const baselineLane = await openLane('baseline', false, distinctBaselineLane ? baselineWorkers : undefined);
|
|
206
|
+
lanes.push(baselineLane);
|
|
207
|
+
const { specs } = baselineLane;
|
|
199
208
|
const discovered = new Set(specs.map(spec => inside(workspace, spec.moduleId)));
|
|
200
209
|
if (files.length && (files.some(file => !discovered.has(file)) || discovered.size !== files.length)) {
|
|
201
210
|
throw new Error('Vitest test selection mismatch');
|
|
202
211
|
}
|
|
203
212
|
const baselineState = { phase: 'baseline' };
|
|
204
213
|
const baselineStarted = Date.now();
|
|
205
|
-
const baseline = await run(specs, baselineState);
|
|
206
|
-
const baselineTiming =
|
|
214
|
+
const baseline = await run(specs, baselineState, baselineLane, baselineTimeout);
|
|
215
|
+
const baselineTiming = baselineLane.timing;
|
|
207
216
|
const baselineTime = Date.now() - baselineStarted;
|
|
217
|
+
if (distinctBaselineLane) {
|
|
218
|
+
await Promise.race([baselineLane.context.close(), new Promise(resolveClose => setTimeout(resolveClose, 5_000))]);
|
|
219
|
+
lanes.length = 0;
|
|
220
|
+
lanes.push(await openLane(0));
|
|
221
|
+
}
|
|
208
222
|
const passed = baseline.snapshot.tests.filter(test => test.status === 'passed');
|
|
209
223
|
const tests = new Map(passed.map(test => [test.id, test]));
|
|
210
224
|
const coveredModules = new Set(baseline.records.flatMap(record => record.modules.map(([project, file]) =>
|
package/src/type-equivalence.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { existsSync, realpathSync } from 'node:fs';
|
|
2
|
-
import { dirname, resolve } from 'node:path';
|
|
1
|
+
import { existsSync, realpathSync, statSync } from 'node:fs';
|
|
2
|
+
import { dirname, isAbsolute, relative, resolve, sep } from 'node:path';
|
|
3
3
|
import { loadTypeScript } from './typescript-compiler.mjs';
|
|
4
4
|
|
|
5
5
|
const PRIMITIVE_PROTOTYPE_KEYS = new Set([
|
|
@@ -163,44 +163,124 @@ function indexExpressions(ts, sourceFile) {
|
|
|
163
163
|
return nodes;
|
|
164
164
|
}
|
|
165
165
|
|
|
166
|
-
|
|
167
|
-
const
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
166
|
+
function isWithinRoot(realRoot, candidate) {
|
|
167
|
+
const rel = relative(realRoot, candidate);
|
|
168
|
+
return rel === '' || (!isAbsolute(rel) && rel !== '..' && !rel.startsWith('..' + sep));
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
function normalizePath(filePath) {
|
|
172
|
+
return existsSync(filePath) ? realpathSync(filePath) : resolve(filePath);
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
function readParsedConfig(ts, configPath, cache) {
|
|
176
|
+
const key = normalizePath(configPath);
|
|
177
|
+
if (cache.has(key)) return cache.get(key);
|
|
178
|
+
if (!existsSync(key)) {
|
|
179
|
+
const missing = { configPath: key, missing: true, strictNullChecks: false };
|
|
180
|
+
cache.set(key, missing);
|
|
181
|
+
return missing;
|
|
173
182
|
}
|
|
174
|
-
const read = ts.readConfigFile(
|
|
183
|
+
const read = ts.readConfigFile(key, ts.sys.readFile);
|
|
175
184
|
if (read.error || !read.config) {
|
|
176
|
-
|
|
185
|
+
const failed = { configPath: key, error: true, strictNullChecks: false };
|
|
186
|
+
cache.set(key, failed);
|
|
187
|
+
return failed;
|
|
177
188
|
}
|
|
178
|
-
const parsed = ts.parseJsonConfigFileContent(read.config, ts.sys, dirname(
|
|
189
|
+
const parsed = ts.parseJsonConfigFileContent(read.config, ts.sys, dirname(key));
|
|
179
190
|
const compilerOptions = parsed.options ?? {};
|
|
180
191
|
const strictNullChecks = compilerOptions.strictNullChecks === true ||
|
|
181
192
|
(compilerOptions.strict === true && compilerOptions.strictNullChecks !== false);
|
|
182
|
-
|
|
183
|
-
|
|
193
|
+
const fileNames = new Set((parsed.fileNames ?? []).map(normalizePath));
|
|
194
|
+
const info = {
|
|
195
|
+
configPath: key,
|
|
196
|
+
parsed,
|
|
197
|
+
compilerOptions,
|
|
198
|
+
strictNullChecks,
|
|
199
|
+
noUncheckedIndexedAccess: compilerOptions.noUncheckedIndexedAccess === true,
|
|
200
|
+
projectReferences: parsed.projectReferences ?? [],
|
|
201
|
+
fileNames,
|
|
202
|
+
};
|
|
203
|
+
cache.set(key, info);
|
|
204
|
+
return info;
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
function resolveReferenceConfigPath(refPath) {
|
|
208
|
+
const resolved = resolve(refPath);
|
|
209
|
+
const st = statSync(resolved, { throwIfNoEntry: false });
|
|
210
|
+
if (st?.isDirectory()) return resolve(resolved, 'tsconfig.json');
|
|
211
|
+
return resolved;
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
function findConfigViaReferences(ts, configPath, absFile, cache, visited = new Set()) {
|
|
215
|
+
const key = normalizePath(configPath);
|
|
216
|
+
if (visited.has(key)) return null;
|
|
217
|
+
visited.add(key);
|
|
218
|
+
const info = readParsedConfig(ts, key, cache);
|
|
219
|
+
if (info.missing || info.error) return null;
|
|
220
|
+
for (const ref of info.projectReferences) {
|
|
221
|
+
const refConfigPath = resolveReferenceConfigPath(ref.path);
|
|
222
|
+
if (!existsSync(refConfigPath)) continue;
|
|
223
|
+
const refInfo = readParsedConfig(ts, refConfigPath, cache);
|
|
224
|
+
if (refInfo.missing || refInfo.error) continue;
|
|
225
|
+
if (refInfo.fileNames.has(absFile)) return refInfo.configPath;
|
|
226
|
+
if (refInfo.projectReferences.length) {
|
|
227
|
+
const nested = findConfigViaReferences(ts, refInfo.configPath, absFile, cache, visited);
|
|
228
|
+
if (nested) return nested;
|
|
229
|
+
}
|
|
184
230
|
}
|
|
185
|
-
|
|
231
|
+
return null;
|
|
232
|
+
}
|
|
186
233
|
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
234
|
+
function collectAncestorConfigsInRoot(ts, realRoot, startDir) {
|
|
235
|
+
const configs = [];
|
|
236
|
+
let dir = startDir;
|
|
237
|
+
while (isWithinRoot(realRoot, dir)) {
|
|
238
|
+
const candidate = resolve(dir, 'tsconfig.json');
|
|
239
|
+
if (ts.sys.fileExists(candidate)) configs.push(normalizePath(candidate));
|
|
240
|
+
const parent = dirname(dir);
|
|
241
|
+
if (parent === dir) break;
|
|
242
|
+
dir = parent;
|
|
243
|
+
}
|
|
244
|
+
return configs;
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
function resolveConfigForFile(ts, realRoot, absFile, explicitConfigPath, cache) {
|
|
248
|
+
if (explicitConfigPath) return explicitConfigPath;
|
|
249
|
+
const ancestors = collectAncestorConfigsInRoot(ts, realRoot, dirname(absFile));
|
|
250
|
+
if (!ancestors.length) {
|
|
251
|
+
const fallback = ts.findConfigFile(realRoot, ts.sys.fileExists, 'tsconfig.json');
|
|
252
|
+
if (fallback) ancestors.push(normalizePath(fallback));
|
|
253
|
+
}
|
|
254
|
+
if (!ancestors.length) return null;
|
|
255
|
+
|
|
256
|
+
// Walk from nearest ancestor upward: if a config has projectReferences, prefer an owning
|
|
257
|
+
// referenced config before falling back to an ancestor config that merely includes absFile.
|
|
258
|
+
for (const configPath of ancestors) {
|
|
259
|
+
const info = readParsedConfig(ts, configPath, cache);
|
|
260
|
+
if (info.missing || info.error) continue;
|
|
261
|
+
if (info.projectReferences.length) {
|
|
262
|
+
const fromRef = findConfigViaReferences(ts, configPath, absFile, cache);
|
|
263
|
+
if (fromRef) return fromRef;
|
|
264
|
+
}
|
|
265
|
+
if (info.fileNames.has(absFile)) {
|
|
266
|
+
return configPath;
|
|
267
|
+
}
|
|
195
268
|
}
|
|
196
269
|
|
|
270
|
+
// Fallback to the nearest ancestor tsconfig so warnings report the actual config checked.
|
|
271
|
+
return ancestors[0];
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
function buildGroupContext(ts, info, absTargets) {
|
|
275
|
+
const { compilerOptions, noUncheckedIndexedAccess, parsed } = info;
|
|
276
|
+
const ambientDts = (parsed.fileNames ?? []).filter(file => file.endsWith('.d.ts'));
|
|
277
|
+
const rootNames = [...new Set([...absTargets, ...ambientDts])];
|
|
278
|
+
if (!rootNames.length) return () => null;
|
|
197
279
|
const program = ts.createProgram(rootNames, { ...compilerOptions, noEmit: true });
|
|
198
280
|
const checker = program.getTypeChecker();
|
|
199
281
|
const fileCache = new Map();
|
|
200
282
|
|
|
201
|
-
|
|
202
|
-
const resolved = resolve(realRoot, file);
|
|
203
|
-
const absFile = existsSync(resolved) ? realpathSync(resolved) : resolved;
|
|
283
|
+
return (absFile, resolved) => {
|
|
204
284
|
if (fileCache.has(absFile)) return fileCache.get(absFile);
|
|
205
285
|
const sourceFile = program.getSourceFile(absFile) ?? program.getSourceFile(resolved);
|
|
206
286
|
if (!sourceFile) {
|
|
@@ -239,7 +319,93 @@ export function createTypeContext(root, targetFiles = [], { tsconfig, ts = loadT
|
|
|
239
319
|
};
|
|
240
320
|
fileCache.set(absFile, helper);
|
|
241
321
|
return helper;
|
|
322
|
+
};
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
export function createTypeContext(root, targetFiles = [], { tsconfig, onWarning, ts = loadTypeScript() } = {}) {
|
|
326
|
+
const realRoot = existsSync(root) ? realpathSync(root) : resolve(root);
|
|
327
|
+
const configCache = new Map();
|
|
328
|
+
const warnings = [];
|
|
329
|
+
const seenWarnings = new Set();
|
|
330
|
+
const warn = message => {
|
|
331
|
+
if (seenWarnings.has(message)) return;
|
|
332
|
+
seenWarnings.add(message);
|
|
333
|
+
warnings.push(message);
|
|
334
|
+
onWarning?.(message);
|
|
335
|
+
};
|
|
336
|
+
const labelConfig = configPath => {
|
|
337
|
+
const rel = relative(realRoot, configPath);
|
|
338
|
+
return rel && !isAbsolute(rel) && !rel.startsWith('..' + sep) ? rel : configPath;
|
|
339
|
+
};
|
|
340
|
+
const explicitConfigPath = tsconfig ? resolve(realRoot, tsconfig) : null;
|
|
341
|
+
|
|
342
|
+
if (!targetFiles.length) {
|
|
343
|
+
const configPath = explicitConfigPath ?? ts.findConfigFile(realRoot, ts.sys.fileExists, 'tsconfig.json');
|
|
344
|
+
if (!configPath || !existsSync(configPath)) {
|
|
345
|
+
warn(explicitConfigPath
|
|
346
|
+
? `--type-check: tsconfig file not found (${tsconfig}); skipping type-based suppression.`
|
|
347
|
+
: '--type-check: no tsconfig.json found; skipping type-based suppression.');
|
|
348
|
+
return { strictNullChecks: false, warnings, forFile: () => null };
|
|
349
|
+
}
|
|
350
|
+
const info = readParsedConfig(ts, configPath, configCache);
|
|
351
|
+
if (info.error) {
|
|
352
|
+
warn(`--type-check: failed to read ${labelConfig(configPath)}; skipping type-based suppression.`);
|
|
353
|
+
return { strictNullChecks: false, warnings, forFile: () => null };
|
|
354
|
+
}
|
|
355
|
+
if (!info.strictNullChecks) {
|
|
356
|
+
warn(`--type-check: strictNullChecks is not enabled in ${labelConfig(configPath)}; skipping type-based suppression.`);
|
|
357
|
+
}
|
|
358
|
+
return { strictNullChecks: info.strictNullChecks, warnings, forFile: () => null };
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
const grouped = new Map();
|
|
362
|
+
const fileToConfig = new Map();
|
|
363
|
+
for (const file of targetFiles) {
|
|
364
|
+
const resolved = resolve(realRoot, file);
|
|
365
|
+
const absFile = normalizePath(resolved);
|
|
366
|
+
const configPath = resolveConfigForFile(ts, realRoot, absFile, explicitConfigPath, configCache);
|
|
367
|
+
if (!configPath) {
|
|
368
|
+
warn(`--type-check: no tsconfig.json found for ${file}; skipping type-based suppression.`);
|
|
369
|
+
fileToConfig.set(absFile, null);
|
|
370
|
+
continue;
|
|
371
|
+
}
|
|
372
|
+
const key = normalizePath(configPath);
|
|
373
|
+
fileToConfig.set(absFile, key);
|
|
374
|
+
if (!grouped.has(key)) grouped.set(key, []);
|
|
375
|
+
grouped.get(key).push(absFile);
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
const groupLookups = new Map();
|
|
379
|
+
let anyStrictNullChecks = false;
|
|
380
|
+
for (const [configPath, absTargets] of grouped) {
|
|
381
|
+
const info = readParsedConfig(ts, configPath, configCache);
|
|
382
|
+
if (info.missing) {
|
|
383
|
+
warn(`--type-check: tsconfig file not found (${tsconfig ?? labelConfig(configPath)}); skipping type-based suppression.`);
|
|
384
|
+
groupLookups.set(configPath, () => null);
|
|
385
|
+
continue;
|
|
386
|
+
}
|
|
387
|
+
if (info.error) {
|
|
388
|
+
warn(`--type-check: failed to read ${labelConfig(configPath)}; skipping type-based suppression.`);
|
|
389
|
+
groupLookups.set(configPath, () => null);
|
|
390
|
+
continue;
|
|
391
|
+
}
|
|
392
|
+
if (!info.strictNullChecks) {
|
|
393
|
+
warn(`--type-check: strictNullChecks is not enabled in ${labelConfig(configPath)}; skipping type-based suppression.`);
|
|
394
|
+
groupLookups.set(configPath, () => null);
|
|
395
|
+
continue;
|
|
396
|
+
}
|
|
397
|
+
anyStrictNullChecks = true;
|
|
398
|
+
groupLookups.set(configPath, buildGroupContext(ts, info, absTargets));
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
function forFile(file) {
|
|
402
|
+
const resolved = resolve(realRoot, file);
|
|
403
|
+
const absFile = normalizePath(resolved);
|
|
404
|
+
const configKey = fileToConfig.get(absFile);
|
|
405
|
+
if (!configKey) return null;
|
|
406
|
+
const lookup = groupLookups.get(configKey);
|
|
407
|
+
return lookup ? lookup(absFile, resolved) : null;
|
|
242
408
|
}
|
|
243
409
|
|
|
244
|
-
return { strictNullChecks:
|
|
410
|
+
return { strictNullChecks: anyStrictNullChecks, warnings, forFile };
|
|
245
411
|
}
|
package/src/vitest.mjs
CHANGED
|
@@ -171,15 +171,127 @@ function rebaseCopiedLinks(source, workspace) {
|
|
|
171
171
|
}
|
|
172
172
|
}
|
|
173
173
|
|
|
174
|
-
|
|
174
|
+
const activeCopies = new Set();
|
|
175
|
+
let signalHandlersRegistered = false;
|
|
176
|
+
|
|
177
|
+
function stopCopyProcesses(dir) {
|
|
178
|
+
try {
|
|
179
|
+
for (const entry of readdirSync(dir)) {
|
|
180
|
+
if (!entry.endsWith('.pid')) continue;
|
|
181
|
+
const pid = Number(readFileSync(resolve(dir, entry), 'utf8').trim());
|
|
182
|
+
if (!Number.isSafeInteger(pid) || pid <= 0) continue;
|
|
183
|
+
for (const sig of ['SIGTERM', 'SIGKILL']) {
|
|
184
|
+
try {
|
|
185
|
+
if (process.platform === 'win32') process.kill(pid, sig);
|
|
186
|
+
else process.kill(-pid, sig);
|
|
187
|
+
} catch {
|
|
188
|
+
// Process already exited or unreachable.
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
} catch {
|
|
193
|
+
// Best-effort process stop during shutdown.
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
function cleanupActiveCopies() {
|
|
198
|
+
for (const dir of [...activeCopies]) {
|
|
199
|
+
activeCopies.delete(dir);
|
|
200
|
+
stopCopyProcesses(dir);
|
|
201
|
+
try {
|
|
202
|
+
rmSync(dir, { recursive: true, force: true, maxRetries: 3, retryDelay: 50 });
|
|
203
|
+
} catch {
|
|
204
|
+
// Best-effort cleanup during shutdown.
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
function handleSignal(signal, code) {
|
|
210
|
+
if (activeCopies.size === 0) {
|
|
211
|
+
process.off(signal, signal === 'SIGINT' ? handleSigint : handleSigterm);
|
|
212
|
+
try {
|
|
213
|
+
process.kill(process.pid, signal);
|
|
214
|
+
} catch {
|
|
215
|
+
process.exit(code);
|
|
216
|
+
}
|
|
217
|
+
return;
|
|
218
|
+
}
|
|
219
|
+
cleanupActiveCopies();
|
|
220
|
+
process.exit(code);
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
function handleSigint() {
|
|
224
|
+
handleSignal('SIGINT', 130);
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
function handleSigterm() {
|
|
228
|
+
handleSignal('SIGTERM', 143);
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
function registerActiveCopy(dir) {
|
|
232
|
+
activeCopies.add(dir);
|
|
233
|
+
if (!signalHandlersRegistered) {
|
|
234
|
+
signalHandlersRegistered = true;
|
|
235
|
+
process.on('exit', cleanupActiveCopies);
|
|
236
|
+
process.on('SIGINT', handleSigint);
|
|
237
|
+
process.on('SIGTERM', handleSigterm);
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
function unregisterActiveCopy(dir) {
|
|
242
|
+
activeCopies.delete(dir);
|
|
243
|
+
// Defer listener removal to the next turn so a signal queued during a synchronous
|
|
244
|
+
// `withCopy` call (e.g. `spawnSync`) is still delivered and exits with 130/143.
|
|
245
|
+
if (signalHandlersRegistered && activeCopies.size === 0) {
|
|
246
|
+
setImmediate(() => {
|
|
247
|
+
if (signalHandlersRegistered && activeCopies.size === 0) {
|
|
248
|
+
signalHandlersRegistered = false;
|
|
249
|
+
process.off('exit', cleanupActiveCopies);
|
|
250
|
+
process.off('SIGINT', handleSigint);
|
|
251
|
+
process.off('SIGTERM', handleSigterm);
|
|
252
|
+
}
|
|
253
|
+
}).unref?.();
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
function formatBytes(bytes) {
|
|
258
|
+
if (bytes >= 1024 * 1024 * 1024) return `${(bytes / (1024 * 1024 * 1024)).toFixed(1)}GB`;
|
|
259
|
+
if (bytes >= 1024 * 1024) return `${(bytes / (1024 * 1024)).toFixed(0)}MB`;
|
|
260
|
+
if (bytes >= 1024) return `${(bytes / 1024).toFixed(0)}KB`;
|
|
261
|
+
return `${bytes}B`;
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
export const DEFAULT_LARGE_COPY_BYTES = 500 * 1024 * 1024;
|
|
265
|
+
export const DEFAULT_LARGE_COPY_FILES = 10_000;
|
|
266
|
+
|
|
267
|
+
export function withCopy(project, action, {
|
|
268
|
+
exclude = [],
|
|
269
|
+
onProgress,
|
|
270
|
+
onLargeCopy,
|
|
271
|
+
largeCopyBytes = DEFAULT_LARGE_COPY_BYTES,
|
|
272
|
+
largeCopyFiles = DEFAULT_LARGE_COPY_FILES,
|
|
273
|
+
} = {}) {
|
|
175
274
|
const source = realpathSync(project);
|
|
176
275
|
const exclusions = resolveCopyExclusions(source, exclude);
|
|
177
276
|
const temp = realpathSync(mkdtempSync(resolve(tmpdir(), 'tmt-')));
|
|
178
|
-
|
|
277
|
+
registerActiveCopy(temp);
|
|
278
|
+
let removed = false;
|
|
279
|
+
const remove = () => {
|
|
280
|
+
if (removed) return;
|
|
281
|
+
removed = true;
|
|
282
|
+
unregisterActiveCopy(temp);
|
|
283
|
+
rmSync(temp, { recursive: true, force: true });
|
|
284
|
+
};
|
|
179
285
|
let pending = false;
|
|
180
286
|
try {
|
|
181
287
|
const root = resolve(temp, 'project');
|
|
182
288
|
const moduleTrees = [];
|
|
289
|
+
let copiedFiles = 0;
|
|
290
|
+
let copiedBytes = 0;
|
|
291
|
+
let warnedLargeCopy = false;
|
|
292
|
+
const copyStarted = Date.now();
|
|
293
|
+
let lastProgressAt = copyStarted;
|
|
294
|
+
onProgress?.('Copying project to temporary workspace...');
|
|
183
295
|
cpSync(source, root, {
|
|
184
296
|
recursive: true,
|
|
185
297
|
// Copy-on-write where the file system offers it (APFS, Btrfs, XFS); an ordinary copy elsewhere.
|
|
@@ -188,9 +300,34 @@ export function withCopy(project, action, { exclude = [] } = {}) {
|
|
|
188
300
|
if (path !== source && basename(path) === 'node_modules' && !exclusions.includes(path) &&
|
|
189
301
|
!copyPathIsExcluded(source, dirname(path), exclusions) &&
|
|
190
302
|
statSync(path, { throwIfNoEntry: false })?.isDirectory()) moduleTrees.push(path);
|
|
191
|
-
|
|
303
|
+
const keep = !copyPathIsExcluded(source, path, exclusions);
|
|
304
|
+
if (keep && path !== source) {
|
|
305
|
+
const st = lstatSync(path, { throwIfNoEntry: false });
|
|
306
|
+
if (st?.isFile()) {
|
|
307
|
+
copiedFiles++;
|
|
308
|
+
copiedBytes += st.size;
|
|
309
|
+
if (!warnedLargeCopy && (copiedBytes >= largeCopyBytes || copiedFiles >= largeCopyFiles)) {
|
|
310
|
+
warnedLargeCopy = true;
|
|
311
|
+
const message = `Warning: Copying a large project (${formatBytes(copiedBytes)}, ${copiedFiles} files) into a temporary directory. ` +
|
|
312
|
+
'Consider excluding large directories with --copy-exclude <PATH> or setting "copyExclude" in targeted-mutation.config.json.';
|
|
313
|
+
if (onLargeCopy) onLargeCopy({ bytes: copiedBytes, files: copiedFiles, message });
|
|
314
|
+
else process.stderr.write(message + '\n');
|
|
315
|
+
}
|
|
316
|
+
if (onProgress) {
|
|
317
|
+
const now = Date.now();
|
|
318
|
+
if (now - lastProgressAt >= 2_000) {
|
|
319
|
+
lastProgressAt = now;
|
|
320
|
+
onProgress(`Copying project (${copiedFiles} files, ${formatBytes(copiedBytes)})...`);
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
return keep;
|
|
192
326
|
},
|
|
193
327
|
});
|
|
328
|
+
if (onProgress && (Date.now() - copyStarted >= 500 || copiedFiles >= 1_000)) {
|
|
329
|
+
onProgress(`Copied ${copiedFiles} files (${formatBytes(copiedBytes)}).`);
|
|
330
|
+
}
|
|
194
331
|
rebaseCopiedLinks(source, root);
|
|
195
332
|
const projectModules = resolve(source, 'node_modules');
|
|
196
333
|
const hasLocalModules = moduleTrees.includes(projectModules);
|
|
@@ -209,7 +346,7 @@ export function withCopy(project, action, { exclude = [] } = {}) {
|
|
|
209
346
|
}
|
|
210
347
|
|
|
211
348
|
// How one Vitest run is started, shared by the blocking and the concurrent form.
|
|
212
|
-
function vitestCommand(root, temp, { trace, config, testFiles = [], testProjects = [], product = false, active, probePreload, synchronousTrace, timeout = 60_000 } = {}) {
|
|
349
|
+
function vitestCommand(root, temp, { trace, config, testFiles = [], testProjects = [], product = false, active, probePreload, synchronousTrace, timeout = 60_000, workers = 1 } = {}) {
|
|
213
350
|
const vitest = resolve(dirname(runnerPackage(root, 'vitest')), 'vitest.mjs');
|
|
214
351
|
const testsToRun = [...new Set(testFiles.map(file => inside(root, file)))];
|
|
215
352
|
const projectArgs = [...new Set(testProjects.filter(Boolean))].flatMap(name => ['--project', name]);
|
|
@@ -218,9 +355,12 @@ function vitestCommand(root, temp, { trace, config, testFiles = [], testProjects
|
|
|
218
355
|
rmSync(report, { force: true });
|
|
219
356
|
const cache = resolve(temp, 'vite-cache');
|
|
220
357
|
mkdirSync(cache, { recursive: true });
|
|
358
|
+
const workerArgs = workers > 1
|
|
359
|
+
? [`--maxWorkers=${workers}`, '--maxConcurrency=1']
|
|
360
|
+
: ['--maxWorkers=1', '--maxConcurrency=1', '--no-file-parallelism'];
|
|
221
361
|
return { report, testsToRun, product, args: [
|
|
222
362
|
supervisor, resolve(temp, 'vitest.pid'), String(timeout),
|
|
223
|
-
vitest, 'run',
|
|
363
|
+
vitest, 'run', ...workerArgs, '--no-cache',
|
|
224
364
|
...configuration, ...projectArgs, ...(product ? ['--reporter', reporter] : ['--reporter=json', '--outputFile', report]),
|
|
225
365
|
...testsToRun,
|
|
226
366
|
], options: {
|
|
@@ -276,13 +416,14 @@ function vitestOutcome(root, { report, testsToRun, product }, result) {
|
|
|
276
416
|
return { status, tests, output: result.stderr + result.stdout };
|
|
277
417
|
}
|
|
278
418
|
|
|
279
|
-
export async function resolveRelatedVitestSpecs(project, targetFiles = [], { config, copyExclude = [], timeout = 60_000 } = {}) {
|
|
419
|
+
export async function resolveRelatedVitestSpecs(project, targetFiles = [], { config, copyExclude = [], timeout = 60_000, onProgress, onLargeCopy } = {}) {
|
|
280
420
|
const root = realpathSync(project);
|
|
281
421
|
const relTargets = [...new Set(targetFiles.map(file => relative(root, inside(root, file))))];
|
|
282
422
|
if (!relTargets.length) return { tests: [], specs: [] };
|
|
283
423
|
// Validate Vitest availability up front before copying.
|
|
284
424
|
runnerPackage(root, 'vitest');
|
|
285
|
-
return withCopy(root, (workspace, temp) => {
|
|
425
|
+
return withCopy(root, async (workspace, temp) => {
|
|
426
|
+
onProgress?.('Resolving related Vitest test files...');
|
|
286
427
|
const cache = resolve(temp, 'vite-cache');
|
|
287
428
|
mkdirSync(cache, { recursive: true });
|
|
288
429
|
const manifestPath = resolve(temp, 'related-request.json');
|
|
@@ -293,15 +434,36 @@ export async function resolveRelatedVitestSpecs(project, targetFiles = [], { con
|
|
|
293
434
|
targets: relTargets,
|
|
294
435
|
output: outputPath,
|
|
295
436
|
}), 'utf8');
|
|
296
|
-
const
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
437
|
+
const maxBuffer = 4 * 1024 * 1024;
|
|
438
|
+
const run = await new Promise(settle => {
|
|
439
|
+
const child = spawn(process.execPath, [
|
|
440
|
+
supervisor, resolve(temp, 'related.pid'), String(timeout),
|
|
441
|
+
relatedWorker, manifestPath,
|
|
442
|
+
], {
|
|
443
|
+
cwd: workspace,
|
|
444
|
+
env: { ...process.env, CI: 'true', VITEST: '1', NODE_ENV: 'test', VITE_CACHE_DIR: cache },
|
|
445
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
446
|
+
});
|
|
447
|
+
const out = { stdout: '', stderr: '' };
|
|
448
|
+
for (const stream of ['stdout', 'stderr']) {
|
|
449
|
+
child[stream].setEncoding('utf8');
|
|
450
|
+
child[stream].on('data', chunk => { if (out[stream].length < maxBuffer) out[stream] += chunk; });
|
|
451
|
+
}
|
|
452
|
+
const killTimer = setTimeout(() => {
|
|
453
|
+
try { child.kill('SIGKILL'); } catch { /* ignore */ }
|
|
454
|
+
}, timeout + 5_000);
|
|
455
|
+
killTimer.unref?.();
|
|
456
|
+
let failure;
|
|
457
|
+
child.once('error', error => { failure = error; });
|
|
458
|
+
child.once('close', (status, signal) => {
|
|
459
|
+
clearTimeout(killTimer);
|
|
460
|
+
settle({
|
|
461
|
+
status,
|
|
462
|
+
signal,
|
|
463
|
+
...out,
|
|
464
|
+
error: failure ?? (signal && status === null ? Object.assign(new Error('Vitest related discovery did not finish in time'), { code: 'ETIMEDOUT' }) : undefined),
|
|
465
|
+
});
|
|
466
|
+
});
|
|
305
467
|
});
|
|
306
468
|
if (run.status === 124 || run.error?.code === 'ETIMEDOUT') {
|
|
307
469
|
throw new Error(`Vitest related test discovery timed out after ${Math.round(timeout / 1000)}s. Try increasing --timeout or specifying --test <FILE>.`);
|
|
@@ -317,7 +479,7 @@ export async function resolveRelatedVitestSpecs(project, targetFiles = [], { con
|
|
|
317
479
|
throw new Error(`No Vitest test files are related to ${shown}. Specify test files explicitly with --test <FILE>.`);
|
|
318
480
|
}
|
|
319
481
|
return { tests, specs };
|
|
320
|
-
}, { exclude: copyExclude });
|
|
482
|
+
}, { exclude: copyExclude, onProgress, onLargeCopy });
|
|
321
483
|
}
|
|
322
484
|
|
|
323
485
|
export async function resolveRelatedVitestTests(project, targetFiles = [], options = {}) {
|