targeted-mutation 0.2.3 → 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/src/vitest.mjs CHANGED
@@ -1,12 +1,13 @@
1
1
  import { spawn, spawnSync } from 'node:child_process';
2
- import { constants, cpSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, readlinkSync, realpathSync, rmSync, statSync, symlinkSync, unlinkSync } from 'node:fs';
2
+ import { constants, cpSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, readlinkSync, realpathSync, rmSync, statSync, symlinkSync, unlinkSync, writeFileSync } from 'node:fs';
3
3
  import { createRequire } from 'node:module';
4
4
  import { tmpdir } from 'node:os';
5
5
  import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
6
- import { fileURLToPath } from 'node:url';
6
+ import { fileURLToPath, pathToFileURL } from 'node:url';
7
7
 
8
8
  const reporter = fileURLToPath(new URL('./vitest-reporter.mjs', import.meta.url));
9
9
  const supervisor = fileURLToPath(new URL('./runner-process.mjs', import.meta.url));
10
+ const relatedWorker = fileURLToPath(new URL('./vitest-related-worker.mjs', import.meta.url));
10
11
  const toolDependencies = [
11
12
  { name: 'vitest', bin: 'vitest.mjs', command: 'vitest' },
12
13
  { name: '@playwright/test', bin: 'cli.js', command: 'playwright' },
@@ -170,15 +171,127 @@ function rebaseCopiedLinks(source, workspace) {
170
171
  }
171
172
  }
172
173
 
173
- 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
+ export function withCopy(project, action, {
268
+ exclude = [],
269
+ onProgress,
270
+ onLargeCopy,
271
+ largeCopyBytes = DEFAULT_LARGE_COPY_BYTES,
272
+ largeCopyFiles = DEFAULT_LARGE_COPY_FILES,
273
+ } = {}) {
174
274
  const source = realpathSync(project);
175
275
  const exclusions = resolveCopyExclusions(source, exclude);
176
276
  const temp = realpathSync(mkdtempSync(resolve(tmpdir(), 'tmt-')));
177
- const remove = () => rmSync(temp, { recursive: true, force: true });
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
+ };
178
285
  let pending = false;
179
286
  try {
180
287
  const root = resolve(temp, 'project');
181
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...');
182
295
  cpSync(source, root, {
183
296
  recursive: true,
184
297
  // Copy-on-write where the file system offers it (APFS, Btrfs, XFS); an ordinary copy elsewhere.
@@ -187,9 +300,34 @@ export function withCopy(project, action, { exclude = [] } = {}) {
187
300
  if (path !== source && basename(path) === 'node_modules' && !exclusions.includes(path) &&
188
301
  !copyPathIsExcluded(source, dirname(path), exclusions) &&
189
302
  statSync(path, { throwIfNoEntry: false })?.isDirectory()) moduleTrees.push(path);
190
- return !copyPathIsExcluded(source, path, exclusions);
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;
191
326
  },
192
327
  });
328
+ if (onProgress && (Date.now() - copyStarted >= 500 || copiedFiles >= 1_000)) {
329
+ onProgress(`Copied ${copiedFiles} files (${formatBytes(copiedBytes)}).`);
330
+ }
193
331
  rebaseCopiedLinks(source, root);
194
332
  const projectModules = resolve(source, 'node_modules');
195
333
  const hasLocalModules = moduleTrees.includes(projectModules);
@@ -208,18 +346,22 @@ export function withCopy(project, action, { exclude = [] } = {}) {
208
346
  }
209
347
 
210
348
  // How one Vitest run is started, shared by the blocking and the concurrent form.
211
- function vitestCommand(root, temp, { trace, config, testFiles = [], 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 } = {}) {
212
350
  const vitest = resolve(dirname(runnerPackage(root, 'vitest')), 'vitest.mjs');
213
351
  const testsToRun = [...new Set(testFiles.map(file => inside(root, file)))];
352
+ const projectArgs = [...new Set(testProjects.filter(Boolean))].flatMap(name => ['--project', name]);
214
353
  const configuration = config === undefined ? [] : ['--config', inside(root, config)];
215
354
  const report = resolve(temp, 'vitest.json');
216
355
  rmSync(report, { force: true });
217
356
  const cache = resolve(temp, 'vite-cache');
218
357
  mkdirSync(cache, { recursive: true });
358
+ const workerArgs = workers > 1
359
+ ? [`--maxWorkers=${workers}`, '--maxConcurrency=1']
360
+ : ['--maxWorkers=1', '--maxConcurrency=1', '--no-file-parallelism'];
219
361
  return { report, testsToRun, product, args: [
220
362
  supervisor, resolve(temp, 'vitest.pid'), String(timeout),
221
- vitest, 'run', '--maxWorkers=1', '--maxConcurrency=1', '--no-file-parallelism', '--no-cache',
222
- ...configuration, ...(product ? ['--reporter', reporter] : ['--reporter=json', '--outputFile', report]),
363
+ vitest, 'run', ...workerArgs, '--no-cache',
364
+ ...configuration, ...projectArgs, ...(product ? ['--reporter', reporter] : ['--reporter=json', '--outputFile', report]),
223
365
  ...testsToRun,
224
366
  ], options: {
225
367
  cwd: root,
@@ -274,6 +416,77 @@ function vitestOutcome(root, { report, testsToRun, product }, result) {
274
416
  return { status, tests, output: result.stderr + result.stdout };
275
417
  }
276
418
 
419
+ export async function resolveRelatedVitestSpecs(project, targetFiles = [], { config, copyExclude = [], timeout = 60_000, onProgress, onLargeCopy } = {}) {
420
+ const root = realpathSync(project);
421
+ const relTargets = [...new Set(targetFiles.map(file => relative(root, inside(root, file))))];
422
+ if (!relTargets.length) return { tests: [], specs: [] };
423
+ // Validate Vitest availability up front before copying.
424
+ runnerPackage(root, 'vitest');
425
+ return withCopy(root, async (workspace, temp) => {
426
+ onProgress?.('Resolving related Vitest test files...');
427
+ const cache = resolve(temp, 'vite-cache');
428
+ mkdirSync(cache, { recursive: true });
429
+ const manifestPath = resolve(temp, 'related-request.json');
430
+ const outputPath = resolve(temp, 'related-output.json');
431
+ writeFileSync(manifestPath, JSON.stringify({
432
+ workspace,
433
+ config,
434
+ targets: relTargets,
435
+ output: outputPath,
436
+ }), 'utf8');
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
+ });
467
+ });
468
+ if (run.status === 124 || run.error?.code === 'ETIMEDOUT') {
469
+ throw new Error(`Vitest related test discovery timed out after ${Math.round(timeout / 1000)}s. Try increasing --timeout or specifying --test <FILE>.`);
470
+ }
471
+ if (run.status !== 0 || !existsSync(outputPath)) {
472
+ const detail = (run.stderr || run.stdout || run.error?.message || '').trim();
473
+ throw new Error(detail || 'Failed to resolve related Vitest tests');
474
+ }
475
+ const { specs = [] } = JSON.parse(readFileSync(outputPath, 'utf8'));
476
+ const tests = [...new Set(specs.map(spec => spec.file))].sort();
477
+ if (!tests.length) {
478
+ const shown = targetFiles.slice(0, 5).join(', ') + (targetFiles.length > 5 ? `, ... (${targetFiles.length} files)` : '');
479
+ throw new Error(`No Vitest test files are related to ${shown}. Specify test files explicitly with --test <FILE>.`);
480
+ }
481
+ return { tests, specs };
482
+ }, { exclude: copyExclude, onProgress, onLargeCopy });
483
+ }
484
+
485
+ export async function resolveRelatedVitestTests(project, targetFiles = [], options = {}) {
486
+ const { tests } = await resolveRelatedVitestSpecs(project, targetFiles, options);
487
+ return tests;
488
+ }
489
+
277
490
  export function runVitest(root, temp, settings) {
278
491
  const command = vitestCommand(root, temp, settings);
279
492
  return vitestOutcome(root, command, spawnSync(process.execPath, command.args, command.options));