-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
cli.js
487 lines (434 loc) · 12.9 KB
/
cli.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
import {createRequire} from 'module';
import path from 'path';
import arrify from 'arrify';
import ciParallelVars from 'ci-parallel-vars';
import del from 'del';
import figures from 'figures';
import readPkg from 'read-pkg';
import Api from './api.js';
import {chalk} from './chalk.js';
import validateEnvironmentVariables from './environment-variables.js';
import normalizeExtensions from './extensions.js';
import {normalizeGlobs, normalizePattern} from './globs.js';
import {controlFlow} from './ipc-flow-control.cjs';
import isCi from './is-ci.js';
import {splitPatternAndLineNumbers} from './line-numbers.js';
import {loadConfig} from './load-config.js';
import normalizeModuleTypes from './module-types.js';
import normalizeNodeArguments from './node-arguments.js';
import providerManager from './provider-manager.js';
import DefaultReporter from './reporters/default.js';
import TapReporter from './reporters/tap.js';
import Watcher from './watcher.js';
const yargs = createRequire(import.meta.url)('yargs'); // FIXME: Use ESM
function exit(message) {
console.error(`\n ${chalk.red(figures.cross)} ${message}`);
process.exit(1); // eslint-disable-line unicorn/no-process-exit
}
const coerceLastValue = value => {
return Array.isArray(value) ? value.pop() : value;
};
const FLAGS = {
concurrency: {
alias: 'c',
coerce: coerceLastValue,
description: 'Max number of test files running at the same time (default: CPU cores)',
type: 'number'
},
'fail-fast': {
coerce: coerceLastValue,
description: 'Stop after first test failure',
type: 'boolean'
},
match: {
alias: 'm',
description: 'Only run tests with matching title (can be repeated)',
type: 'string'
},
'no-worker-threads': {
coerce: coerceLastValue,
description: 'Don\'t use worker threads',
type: 'boolean'
},
'node-arguments': {
coerce: coerceLastValue,
description: 'Additional Node.js arguments for launching worker processes (specify as a single string)',
type: 'string'
},
serial: {
alias: 's',
coerce: coerceLastValue,
description: 'Run tests serially',
type: 'boolean'
},
tap: {
alias: 't',
coerce: coerceLastValue,
description: 'Generate TAP output',
type: 'boolean'
},
timeout: {
alias: 'T',
coerce: coerceLastValue,
description: 'Set global timeout (milliseconds or human-readable, e.g. 10s, 2m)',
type: 'string'
},
'update-snapshots': {
alias: 'u',
coerce: coerceLastValue,
description: 'Update snapshots',
type: 'boolean'
},
verbose: {
alias: 'v',
coerce: coerceLastValue,
description: 'Enable verbose output (no-op)',
type: 'boolean'
},
watch: {
alias: 'w',
coerce: coerceLastValue,
description: 'Re-run tests when files change',
type: 'boolean'
}
};
export default async () => { // eslint-disable-line complexity
let conf = {};
let confError = null;
try {
const {argv: {config: configFile}} = yargs.help(false);
conf = await loadConfig({configFile});
} catch (error) {
confError = error;
}
// Enter debug mode if the main process is being inspected. This assumes the
// worker processes are automatically inspected, too. It is not necessary to
// run AVA with the debug command, though it's allowed.
let activeInspector = false;
try {
const {default: inspector} = await import('inspector');
activeInspector = inspector.url() !== undefined;
} catch {}
let debug = activeInspector ?
{
active: true,
break: false,
files: [],
host: undefined,
port: undefined
} : null;
let resetCache = false;
const {argv} = yargs
.parserConfiguration({
'boolean-negation': true,
'camel-case-expansion': false,
'combine-arrays': false,
'dot-notation': false,
'duplicate-arguments-array': true,
'flatten-duplicate-arrays': true,
'negation-prefix': 'no-',
'parse-numbers': true,
'populate--': true,
'set-placeholder-key': false,
'short-option-groups': true,
'strip-aliased': true,
'unknown-options-as-args': false
})
.usage('$0 [<pattern>...]')
.usage('$0 debug [<pattern>...]')
.usage('$0 reset-cache')
.options({
color: {
description: 'Force color output',
type: 'boolean'
},
config: {
description: 'Specific JavaScript file for AVA to read its config from, instead of using package.json or ava.config.* files'
}
})
.command('* [<pattern>...]', 'Run tests', yargs => yargs.options(FLAGS).positional('pattern', {
array: true,
describe: 'Glob patterns to select what test files to run. Leave empty if you want AVA to run all test files instead. Add a colon and specify line numbers of specific tests to run',
type: 'string'
}), argv => {
if (activeInspector) {
debug.files = argv.pattern || [];
}
})
.command(
'debug [<pattern>...]',
'Activate Node.js inspector and run a single test file',
yargs => yargs.options(FLAGS).options({
break: {
description: 'Break before the test file is loaded',
type: 'boolean'
},
host: {
default: '127.0.0.1',
description: 'Address or hostname through which you can connect to the inspector',
type: 'string'
},
port: {
default: 9229,
description: 'Port on which you can connect to the inspector',
type: 'number'
}
}).positional('pattern', {
demand: true,
describe: 'Glob patterns to select a single test file to debug. Add a colon and specify line numbers of specific tests to run',
type: 'string'
}),
argv => {
debug = {
active: activeInspector,
break: argv.break === true,
files: argv.pattern,
host: argv.host,
port: argv.port
};
})
.command(
'reset-cache',
'Reset AVA’s compilation cache and exit',
yargs => yargs,
() => {
resetCache = true;
})
.example('$0')
.example('$0 test.js')
.example('$0 test.js:4,7-9')
.help();
const combined = {...conf};
for (const flag of Object.keys(FLAGS)) {
if (flag === 'no-worker-threads' && Reflect.has(argv, 'worker-threads')) {
combined.workerThreads = argv['worker-threads'];
continue;
}
if (Reflect.has(argv, flag)) {
if (flag === 'fail-fast') {
combined.failFast = argv[flag];
} else if (flag === 'update-snapshots') {
combined.updateSnapshots = argv[flag];
} else if (flag !== 'node-arguments') {
combined[flag] = argv[flag];
}
}
}
const chalkOptions = {level: combined.color === false ? 0 : (await import('chalk')).level};
const {set: setChalk} = await import('./chalk.js');
setChalk(chalkOptions);
if (confError) {
if (confError.parent) {
exit(`${confError.message}\n\n${chalk.gray((confError.parent && confError.parent.stack) || confError.parent)}`);
} else {
exit(confError.message);
}
}
const {nonSemVerExperiments: experiments, projectDir} = conf;
if (resetCache) {
const cacheDir = path.join(projectDir, 'node_modules', '.cache', 'ava');
try {
const deletedFilePaths = await del('*', {cwd: cacheDir});
if (deletedFilePaths.length === 0) {
console.log(`\n${chalk.green(figures.tick)} No cache files to remove`);
} else {
console.log(`\n${chalk.green(figures.tick)} Removed AVA cache files in ${cacheDir}`);
}
process.exit(0); // eslint-disable-line unicorn/no-process-exit
} catch (error) {
exit(`Error removing AVA cache files in ${cacheDir}\n\n${chalk.gray((error && error.stack) || error)}`);
}
}
if (argv.watch) {
if (argv.tap && !conf.tap) {
exit('The TAP reporter is not available when using watch mode.');
}
if (isCi) {
exit('Watch mode is not available in CI, as it prevents AVA from terminating.');
}
if (debug !== null) {
exit('Watch mode is not available when debugging.');
}
}
if (debug !== null) {
if (argv.tap && !conf.tap) {
exit('The TAP reporter is not available when debugging.');
}
if (isCi) {
exit('Debugging is not available in CI.');
}
if (combined.timeout) {
console.log(chalk.magenta(` ${figures.warning} The timeout option has been disabled to help with debugging.`));
}
}
if (Reflect.has(combined, 'concurrency') && (!Number.isInteger(combined.concurrency) || combined.concurrency < 0)) {
exit('The --concurrency or -c flag must be provided with a nonnegative integer.');
}
if (!combined.tap && Object.keys(experiments).length > 0) {
console.log(chalk.magenta(` ${figures.warning} Experiments are enabled. These are unsupported and may change or be removed at any time.`));
}
if (Reflect.has(conf, 'compileEnhancements')) {
exit('Enhancement compilation must be configured in AVA’s Babel options.');
}
if (Reflect.has(conf, 'helpers')) {
exit('AVA no longer compiles helpers. Add exclusion patterns to the ’files’ configuration and specify ’compileAsTests’ in the Babel options instead.');
}
if (Reflect.has(conf, 'sources')) {
exit('’sources’ has been removed. Use ’ignoredByWatcher’ to provide glob patterns of files that the watcher should ignore.');
}
let pkg;
try {
pkg = readPkg.sync({cwd: projectDir});
} catch (error) {
if (error.code !== 'ENOENT') {
throw error;
}
}
const {type: defaultModuleType = 'commonjs'} = pkg || {};
const providers = [];
if (Reflect.has(conf, 'babel')) {
try {
const {level, main} = await providerManager.babel(projectDir);
providers.push({
level,
main: main({config: conf.babel}),
type: 'babel'
});
} catch (error) {
exit(error.message);
}
}
if (Reflect.has(conf, 'typescript')) {
try {
const {level, main} = await providerManager.typescript(projectDir);
providers.push({
level,
main: main({config: conf.typescript}),
type: 'typescript'
});
} catch (error) {
exit(error.message);
}
}
let environmentVariables;
try {
environmentVariables = validateEnvironmentVariables(conf.environmentVariables);
} catch (error) {
exit(error.message);
}
let extensions;
try {
extensions = normalizeExtensions(conf.extensions, providers);
} catch (error) {
exit(error.message);
}
let moduleTypes;
try {
moduleTypes = normalizeModuleTypes(conf.extensions, defaultModuleType, experiments);
} catch (error) {
exit(error.message);
}
let globs;
try {
globs = normalizeGlobs({files: conf.files, ignoredByWatcher: conf.ignoredByWatcher, extensions, providers});
} catch (error) {
exit(error.message);
}
let nodeArguments;
try {
nodeArguments = normalizeNodeArguments(conf.nodeArguments, argv['node-arguments']);
} catch (error) {
exit(error.message);
}
let parallelRuns = null;
if (isCi && ciParallelVars) {
const {index: currentIndex, total: totalRuns} = ciParallelVars;
parallelRuns = {currentIndex, totalRuns};
}
const match = combined.match === '' ? [] : arrify(combined.match);
const input = debug ? debug.files : (argv.pattern || []);
const filter = input
.map(pattern => splitPatternAndLineNumbers(pattern))
.map(({pattern, ...rest}) => ({
pattern: normalizePattern(path.relative(projectDir, path.resolve(process.cwd(), pattern))),
...rest
}));
const api = new Api({
cacheEnabled: combined.cache !== false,
chalkOptions,
concurrency: combined.concurrency || 0,
workerThreads: combined.workerThreads !== false,
debug,
environmentVariables,
experiments,
extensions,
failFast: combined.failFast,
failWithoutAssertions: combined.failWithoutAssertions !== false,
globs,
match,
moduleTypes,
nodeArguments,
parallelRuns,
projectDir,
providers,
ranFromCli: true,
require: arrify(combined.require),
serial: combined.serial,
snapshotDir: combined.snapshotDir ? path.resolve(projectDir, combined.snapshotDir) : null,
timeout: combined.timeout || '10s',
updateSnapshots: combined.updateSnapshots,
workerArgv: argv['--']
});
const reporter = combined.tap && !combined.watch && debug === null ? new TapReporter({
extensions: globs.extensions,
projectDir,
reportStream: process.stdout,
stdStream: process.stderr
}) : new DefaultReporter({
extensions: globs.extensions,
projectDir,
reportStream: process.stdout,
stdStream: process.stderr,
watching: combined.watch
});
api.on('run', plan => {
reporter.startRun(plan);
if (process.env.AVA_EMIT_RUN_STATUS_OVER_IPC === 'I\'ll find a payphone baby / Take some time to talk to you') {
const bufferedSend = controlFlow(process);
plan.status.on('stateChange', evt => {
bufferedSend(evt);
});
}
plan.status.on('stateChange', evt => {
if (evt.type === 'interrupt') {
reporter.endRun();
process.exit(1); // eslint-disable-line unicorn/no-process-exit
}
});
});
if (combined.watch) {
const watcher = new Watcher({
api,
filter,
globs,
projectDir,
providers,
reporter
});
watcher.observeStdin(process.stdin);
} else {
let debugWithoutSpecificFile = false;
api.on('run', plan => {
if (debug !== null && plan.files.length !== 1) {
debugWithoutSpecificFile = true;
}
});
const runStatus = await api.run({filter});
if (debugWithoutSpecificFile && !debug.active) {
exit('Provide the path to the test file you wish to debug');
return;
}
process.exitCode = runStatus.suggestExitCode({matching: match.length > 0});
reporter.endRun();
}
};