targeted-mutation 0.3.0 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/vitest.mjs CHANGED
@@ -171,15 +171,174 @@ function rebaseCopiedLinks(source, workspace) {
171
171
  }
172
172
  }
173
173
 
174
- export function withCopy(project, action, { exclude = [] } = {}) {
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
+ function snapshotWorkspaceTree(root) {
268
+ const entries = new Map();
269
+ const walk = (dir, insideNodeModules = false) => {
270
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
271
+ const full = resolve(dir, entry.name);
272
+ const rel = relative(root, full);
273
+ const st = lstatSync(full, { bigint: true });
274
+ const kind = st.isSymbolicLink() ? 'l' : st.isDirectory() ? 'd' : 'f';
275
+ entries.set(rel, kind === 'd' ? `d:${st.mode}` : `${kind}:${st.mode}:${st.size}:${st.mtimeNs}`);
276
+ if (kind === 'd') {
277
+ if (entry.name === 'node_modules') {
278
+ // Only inspect real (copied/synthesized) node_modules entries without following symlinks into shared installs.
279
+ walk(full, true);
280
+ } else if (!insideNodeModules || entry.name.startsWith('@') || entry.name === '.bin') {
281
+ walk(full, insideNodeModules);
282
+ }
283
+ }
284
+ }
285
+ };
286
+ walk(root);
287
+ return entries;
288
+ }
289
+
290
+ function workspaceTreeChanged(before, root) {
291
+ const after = snapshotWorkspaceTree(root);
292
+ if (after.size !== before.size) return true;
293
+ for (const [rel, sig] of before) {
294
+ if (after.get(rel) !== sig) return true;
295
+ }
296
+ return false;
297
+ }
298
+
299
+ export function createCopy(project, {
300
+ exclude = [],
301
+ onProgress,
302
+ onLargeCopy,
303
+ largeCopyBytes = DEFAULT_LARGE_COPY_BYTES,
304
+ largeCopyFiles = DEFAULT_LARGE_COPY_FILES,
305
+ } = {}) {
175
306
  const source = realpathSync(project);
176
307
  const exclusions = resolveCopyExclusions(source, exclude);
177
308
  const temp = realpathSync(mkdtempSync(resolve(tmpdir(), 'tmt-')));
178
- const remove = () => rmSync(temp, { recursive: true, force: true });
179
- let pending = false;
309
+ registerActiveCopy(temp);
310
+ let removed = false;
311
+ let claimed = false;
312
+ let busy = false;
313
+ const dispose = () => {
314
+ if (removed) return;
315
+ removed = true;
316
+ busy = false;
317
+ unregisterActiveCopy(temp);
318
+ rmSync(temp, { recursive: true, force: true });
319
+ };
320
+ const claim = () => {
321
+ if (claimed || removed || busy) return false;
322
+ claimed = true;
323
+ return true;
324
+ };
325
+ const beginUse = () => {
326
+ if (claimed || removed || busy) return false;
327
+ busy = true;
328
+ return true;
329
+ };
330
+ const endUse = () => {
331
+ busy = false;
332
+ };
180
333
  try {
181
334
  const root = resolve(temp, 'project');
182
335
  const moduleTrees = [];
336
+ let copiedFiles = 0;
337
+ let copiedBytes = 0;
338
+ let warnedLargeCopy = false;
339
+ const copyStarted = Date.now();
340
+ let lastProgressAt = copyStarted;
341
+ onProgress?.('Copying project to temporary workspace...');
183
342
  cpSync(source, root, {
184
343
  recursive: true,
185
344
  // Copy-on-write where the file system offers it (APFS, Btrfs, XFS); an ordinary copy elsewhere.
@@ -188,9 +347,34 @@ export function withCopy(project, action, { exclude = [] } = {}) {
188
347
  if (path !== source && basename(path) === 'node_modules' && !exclusions.includes(path) &&
189
348
  !copyPathIsExcluded(source, dirname(path), exclusions) &&
190
349
  statSync(path, { throwIfNoEntry: false })?.isDirectory()) moduleTrees.push(path);
191
- return !copyPathIsExcluded(source, path, exclusions);
350
+ const keep = !copyPathIsExcluded(source, path, exclusions);
351
+ if (keep && path !== source) {
352
+ const st = lstatSync(path, { throwIfNoEntry: false });
353
+ if (st?.isFile()) {
354
+ copiedFiles++;
355
+ copiedBytes += st.size;
356
+ if (!warnedLargeCopy && (copiedBytes >= largeCopyBytes || copiedFiles >= largeCopyFiles)) {
357
+ warnedLargeCopy = true;
358
+ const message = `Warning: Copying a large project (${formatBytes(copiedBytes)}, ${copiedFiles} files) into a temporary directory. ` +
359
+ 'Consider excluding large directories with --copy-exclude <PATH> or setting "copyExclude" in targeted-mutation.config.json.';
360
+ if (onLargeCopy) onLargeCopy({ bytes: copiedBytes, files: copiedFiles, message });
361
+ else process.stderr.write(message + '\n');
362
+ }
363
+ if (onProgress) {
364
+ const now = Date.now();
365
+ if (now - lastProgressAt >= 2_000) {
366
+ lastProgressAt = now;
367
+ onProgress(`Copying project (${copiedFiles} files, ${formatBytes(copiedBytes)})...`);
368
+ }
369
+ }
370
+ }
371
+ }
372
+ return keep;
192
373
  },
193
374
  });
375
+ if (onProgress && (Date.now() - copyStarted >= 500 || copiedFiles >= 1_000)) {
376
+ onProgress(`Copied ${copiedFiles} files (${formatBytes(copiedBytes)}).`);
377
+ }
194
378
  rebaseCopiedLinks(source, root);
195
379
  const projectModules = resolve(source, 'node_modules');
196
380
  const hasLocalModules = moduleTrees.includes(projectModules);
@@ -199,17 +383,37 @@ export function withCopy(project, action, { exclude = [] } = {}) {
199
383
  linkInstalledModules(source, root, modules, resolve(root, relative(source, modules)), modules === projectModules ? tools : []);
200
384
  }
201
385
  if (!hasLocalModules) linkModules(resolve(root, 'node_modules'), tools);
202
- const result = action(root, temp);
386
+ return { root, temp, dispose, claim, beginUse, endUse };
387
+ } catch (error) {
388
+ dispose();
389
+ throw error;
390
+ }
391
+ }
392
+
393
+ export function withCopy(project, action, {
394
+ reuseCopy,
395
+ exclude = [],
396
+ onProgress,
397
+ onLargeCopy,
398
+ largeCopyBytes = DEFAULT_LARGE_COPY_BYTES,
399
+ largeCopyFiles = DEFAULT_LARGE_COPY_FILES,
400
+ } = {}) {
401
+ const copy = reuseCopy?.claim?.()
402
+ ? reuseCopy
403
+ : createCopy(project, { exclude, onProgress, onLargeCopy, largeCopyBytes, largeCopyFiles });
404
+ let pending = false;
405
+ try {
406
+ const result = action(copy.root, copy.temp);
203
407
  // An action that is still running keeps its copy until it settles.
204
408
  pending = typeof result?.then === 'function';
205
- return pending ? result.finally(remove) : result;
409
+ return pending ? result.finally(copy.dispose) : result;
206
410
  } finally {
207
- if (!pending) remove();
411
+ if (!pending) copy.dispose();
208
412
  }
209
413
  }
210
414
 
211
415
  // 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 } = {}) {
416
+ function vitestCommand(root, temp, { trace, config, testFiles = [], testProjects = [], product = false, active, probePreload, synchronousTrace, timeout = 60_000, workers = 1 } = {}) {
213
417
  const vitest = resolve(dirname(runnerPackage(root, 'vitest')), 'vitest.mjs');
214
418
  const testsToRun = [...new Set(testFiles.map(file => inside(root, file)))];
215
419
  const projectArgs = [...new Set(testProjects.filter(Boolean))].flatMap(name => ['--project', name]);
@@ -218,9 +422,12 @@ function vitestCommand(root, temp, { trace, config, testFiles = [], testProjects
218
422
  rmSync(report, { force: true });
219
423
  const cache = resolve(temp, 'vite-cache');
220
424
  mkdirSync(cache, { recursive: true });
425
+ const workerArgs = workers > 1
426
+ ? [`--maxWorkers=${workers}`, '--maxConcurrency=1']
427
+ : ['--maxWorkers=1', '--maxConcurrency=1', '--no-file-parallelism'];
221
428
  return { report, testsToRun, product, args: [
222
429
  supervisor, resolve(temp, 'vitest.pid'), String(timeout),
223
- vitest, 'run', '--maxWorkers=1', '--maxConcurrency=1', '--no-file-parallelism', '--no-cache',
430
+ vitest, 'run', ...workerArgs, '--no-cache',
224
431
  ...configuration, ...projectArgs, ...(product ? ['--reporter', reporter] : ['--reporter=json', '--outputFile', report]),
225
432
  ...testsToRun,
226
433
  ], options: {
@@ -276,33 +483,62 @@ function vitestOutcome(root, { report, testsToRun, product }, result) {
276
483
  return { status, tests, output: result.stderr + result.stdout };
277
484
  }
278
485
 
279
- export async function resolveRelatedVitestSpecs(project, targetFiles = [], { config, copyExclude = [], timeout = 60_000 } = {}) {
486
+ export async function resolveRelatedVitestSpecs(project, targetFiles = [], { config, copyExclude = [], timeout = 60_000, onProgress, onLargeCopy, copy } = {}) {
280
487
  const root = realpathSync(project);
281
488
  const relTargets = [...new Set(targetFiles.map(file => relative(root, inside(root, file))))];
282
489
  if (!relTargets.length) return { tests: [], specs: [] };
283
490
  // Validate Vitest availability up front before copying.
284
491
  runnerPackage(root, 'vitest');
285
- return withCopy(root, (workspace, temp) => {
492
+ const resolveInWorkspace = async (workspace, temp) => {
493
+ onProgress?.('Resolving related Vitest test files...');
286
494
  const cache = resolve(temp, 'vite-cache');
287
495
  mkdirSync(cache, { recursive: true });
288
496
  const manifestPath = resolve(temp, 'related-request.json');
289
497
  const outputPath = resolve(temp, 'related-output.json');
498
+ const pidPath = resolve(temp, 'related.pid');
290
499
  writeFileSync(manifestPath, JSON.stringify({
291
500
  workspace,
292
501
  config,
293
502
  targets: relTargets,
294
503
  output: outputPath,
295
504
  }), 'utf8');
296
- const run = spawnSync(process.execPath, [
297
- supervisor, resolve(temp, 'related.pid'), String(timeout),
298
- relatedWorker, manifestPath,
299
- ], {
300
- cwd: workspace,
301
- env: { ...process.env, CI: 'true', VITEST: '1', NODE_ENV: 'test', VITE_CACHE_DIR: cache },
302
- encoding: 'utf8',
303
- timeout: timeout + 5_000,
304
- maxBuffer: 4 * 1024 * 1024,
305
- });
505
+ const maxBuffer = 4 * 1024 * 1024;
506
+ let run;
507
+ try {
508
+ run = await new Promise(settle => {
509
+ const child = spawn(process.execPath, [
510
+ supervisor, pidPath, String(timeout),
511
+ relatedWorker, manifestPath,
512
+ ], {
513
+ cwd: workspace,
514
+ env: { ...process.env, CI: 'true', VITEST: '1', NODE_ENV: 'test', VITE_CACHE_DIR: cache },
515
+ stdio: ['ignore', 'pipe', 'pipe'],
516
+ });
517
+ const out = { stdout: '', stderr: '' };
518
+ for (const stream of ['stdout', 'stderr']) {
519
+ child[stream].setEncoding('utf8');
520
+ child[stream].on('data', chunk => { if (out[stream].length < maxBuffer) out[stream] += chunk; });
521
+ }
522
+ const killTimer = setTimeout(() => {
523
+ try { child.kill('SIGKILL'); } catch { /* ignore */ }
524
+ }, timeout + 5_000);
525
+ killTimer.unref?.();
526
+ let failure;
527
+ child.once('error', error => { failure = error; });
528
+ child.once('close', (status, signal) => {
529
+ clearTimeout(killTimer);
530
+ settle({
531
+ status,
532
+ signal,
533
+ ...out,
534
+ error: failure ?? (signal && status === null ? Object.assign(new Error('Vitest related discovery did not finish in time'), { code: 'ETIMEDOUT' }) : undefined),
535
+ });
536
+ });
537
+ });
538
+ } finally {
539
+ // Remove the finished worker PID file so a reused copy's signal handler never targets a recycled PID.
540
+ rmSync(pidPath, { force: true });
541
+ }
306
542
  if (run.status === 124 || run.error?.code === 'ETIMEDOUT') {
307
543
  throw new Error(`Vitest related test discovery timed out after ${Math.round(timeout / 1000)}s. Try increasing --timeout or specifying --test <FILE>.`);
308
544
  }
@@ -317,7 +553,21 @@ export async function resolveRelatedVitestSpecs(project, targetFiles = [], { con
317
553
  throw new Error(`No Vitest test files are related to ${shown}. Specify test files explicitly with --test <FILE>.`);
318
554
  }
319
555
  return { tests, specs };
320
- }, { exclude: copyExclude });
556
+ };
557
+ if (copy?.beginUse?.()) {
558
+ try {
559
+ const before = snapshotWorkspaceTree(copy.root);
560
+ const result = await resolveInWorkspace(copy.root, copy.temp);
561
+ if (workspaceTreeChanged(before, copy.root)) {
562
+ // Vitest config or plugins modified the workspace during discovery; discard so analysis gets a clean copy.
563
+ copy.dispose();
564
+ }
565
+ return result;
566
+ } finally {
567
+ copy.endUse();
568
+ }
569
+ }
570
+ return withCopy(root, resolveInWorkspace, { exclude: copyExclude, onProgress, onLargeCopy });
321
571
  }
322
572
 
323
573
  export async function resolveRelatedVitestTests(project, targetFiles = [], options = {}) {