Upgrade Ava to v4

This commit is contained in:
Henry Mercer 2022-02-01 18:01:11 +00:00
parent 9a40cc5274
commit ce89f1b611
1153 changed files with 27264 additions and 95308 deletions

230
node_modules/ava/lib/cli.js generated vendored
View file

@ -1,89 +1,112 @@
'use strict';
const path = require('path');
const del = require('del');
const updateNotifier = require('update-notifier');
const figures = require('figures');
const arrify = require('arrify');
const yargs = require('yargs');
const readPkg = require('read-pkg');
const isCi = require('./is-ci');
const {loadConfig} = require('./load-config');
import fs from 'node:fs';
import path from 'node:path';
import process from 'node:process';
import arrify from 'arrify';
import ciParallelVars from 'ci-parallel-vars';
import del from 'del';
import figures from 'figures';
import yargs from 'yargs';
import {hideBin} from 'yargs/helpers'; // eslint-disable-line node/file-extension-in-import
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';
function exit(message) {
console.error(`\n ${require('./chalk').get().red(figures.cross)} ${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 coerceLastValue = value => 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'
type: 'number',
},
'fail-fast': {
coerce: coerceLastValue,
description: 'Stop after first test failure',
type: 'boolean'
type: 'boolean',
},
match: {
alias: 'm',
description: 'Only run tests with matching title (can be repeated)',
type: 'string'
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'
type: 'string',
},
serial: {
alias: 's',
coerce: coerceLastValue,
description: 'Run tests serially',
type: 'boolean'
type: 'boolean',
},
tap: {
alias: 't',
coerce: coerceLastValue,
description: 'Generate TAP output',
type: 'boolean'
type: 'boolean',
},
timeout: {
alias: 'T',
coerce: coerceLastValue,
description: 'Set global timeout (milliseconds or human-readable, e.g. 10s, 2m)',
type: 'string'
type: 'string',
},
'update-snapshots': {
alias: 'u',
coerce: coerceLastValue,
description: 'Update snapshots',
type: 'boolean'
type: 'boolean',
},
verbose: {
alias: 'v',
coerce: coerceLastValue,
description: 'Enable verbose output',
type: 'boolean'
description: 'Enable verbose output (default)',
type: 'boolean',
},
watch: {
alias: 'w',
coerce: coerceLastValue,
description: 'Re-run tests when files change',
type: 'boolean'
}
type: 'boolean',
},
};
exports.run = async () => { // eslint-disable-line complexity
let conf = {};
let confError = null;
export default async function loadCli() { // eslint-disable-line complexity
let conf;
let confError;
try {
const {argv: {config: configFile}} = yargs.help(false);
const {argv: {config: configFile}} = yargs(hideBin(process.argv)).help(false);
conf = await loadConfig({configFile});
if (conf.configFile && path.basename(conf.configFile) !== path.relative(conf.projectDir, conf.configFile)) {
console.log(chalk.magenta(` ${figures.warning} Using configuration from ${conf.configFile}`));
}
} catch (error) {
confError = error;
}
@ -91,18 +114,24 @@ exports.run = async () => { // eslint-disable-line complexity
// 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.
const activeInspector = require('inspector').url() !== undefined; // eslint-disable-line node/no-unsupported-features/node-builtins
let debug = activeInspector ?
{
let activeInspector = false;
try {
const {default: inspector} = await import('node:inspector'); // eslint-disable-line node/no-unsupported-features/es-syntax
activeInspector = inspector.url() !== undefined;
} catch {}
let debug = activeInspector
? {
active: true,
break: false,
files: [],
host: undefined,
port: undefined
port: undefined,
} : null;
let resetCache = false;
const {argv} = yargs
const {argv} = yargs(hideBin(process.argv))
.parserConfiguration({
'boolean-negation': true,
'camel-case-expansion': false,
@ -116,7 +145,7 @@ exports.run = async () => { // eslint-disable-line complexity
'set-placeholder-key': false,
'short-option-groups': true,
'strip-aliased': true,
'unknown-options-as-args': false
'unknown-options-as-args': false,
})
.usage('$0 [<pattern>...]')
.usage('$0 debug [<pattern>...]')
@ -124,16 +153,16 @@ exports.run = async () => { // eslint-disable-line complexity
.options({
color: {
description: 'Force color output',
type: 'boolean'
type: 'boolean',
},
config: {
description: 'Specific JavaScript file for AVA to read its config from, instead of using package.json or ava.config.* files'
}
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'
describe: 'Select which test files to run. Leave empty if you want AVA to run all test files as per your configuration. Accepts glob patterns, directories that (recursively) contain test files, and file paths. Add a colon and specify line numbers of specific tests to run',
type: 'string',
}), argv => {
if (activeInspector) {
debug.files = argv.pattern || [];
@ -145,22 +174,22 @@ exports.run = async () => { // eslint-disable-line complexity
yargs => yargs.options(FLAGS).options({
break: {
description: 'Break before the test file is loaded',
type: 'boolean'
type: 'boolean',
},
host: {
default: '127.0.0.1',
description: 'Address or hostname through which you can connect to the inspector',
type: 'string'
type: 'string',
},
port: {
default: 9229,
description: 'Port on which you can connect to the inspector',
type: 'number'
}
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'
type: 'string',
}),
argv => {
debug = {
@ -168,12 +197,12 @@ exports.run = async () => { // eslint-disable-line complexity
break: argv.break === true,
files: argv.pattern,
host: argv.host,
port: argv.port
port: argv.port,
};
})
.command(
'reset-cache',
'Reset AVAs compilation cache and exit',
'Delete any temporary files and state kept by AVA, then exit',
yargs => yargs,
() => {
resetCache = true;
@ -184,8 +213,14 @@ exports.run = async () => { // eslint-disable-line complexity
.help();
const combined = {...conf};
for (const flag of Object.keys(FLAGS)) {
if (Reflect.has(argv, flag)) {
if (flag === 'no-worker-threads' && Reflect.has(argv, 'worker-threads')) {
combined.workerThreads = argv['worker-threads'];
continue;
}
if (argv[flag] !== undefined) {
if (flag === 'fail-fast') {
combined.failFast = argv[flag];
} else if (flag === 'update-snapshots') {
@ -196,13 +231,15 @@ exports.run = async () => { // eslint-disable-line complexity
}
}
const chalkOptions = {level: combined.color === false ? 0 : require('chalk').level};
const chalk = require('./chalk').set(chalkOptions);
if (combined.updateSnapshots && combined.match) {
exit('Snapshots cannot be updated when matching specific tests.');
const chalkOptions = {level: 0};
if (combined.color !== false) {
const {supportsColor: {level}} = await import('chalk'); // eslint-disable-line node/no-unsupported-features/es-syntax, unicorn/import-style
chalkOptions.level = level;
}
const {set: setChalk} = await import('./chalk.js'); // eslint-disable-line node/no-unsupported-features/es-syntax
setChalk(chalkOptions);
if (confError) {
if (confError.parent) {
exit(`${confError.message}\n\n${chalk.gray((confError.parent && confError.parent.stack) || confError.parent)}`);
@ -211,23 +248,23 @@ exports.run = async () => { // eslint-disable-line complexity
}
}
updateNotifier({pkg: require('../package.json')}).notify();
const {nonSemVerExperiments: experiments, projectDir} = conf;
if (resetCache) {
const cacheDir = path.join(projectDir, 'node_modules', '.cache', 'ava');
try {
await del('*', {
cwd: cacheDir,
nodir: true
});
console.error(`\n${chalk.green(figures.tick)} Removed AVA cache files in ${cacheDir}`);
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)}`);
}
return;
}
if (argv.watch) {
@ -266,6 +303,10 @@ exports.run = async () => { // eslint-disable-line complexity
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, 'babel')) {
exit('Built-in Babel support has been removed.');
}
if (Reflect.has(conf, 'compileEnhancements')) {
exit('Enhancement compilation must be configured in AVAs Babel options.');
}
@ -278,22 +319,9 @@ exports.run = async () => { // eslint-disable-line complexity
exit('sources has been removed. Use ignoredByWatcher to provide glob patterns of files that the watcher should ignore.');
}
const ciParallelVars = require('ci-parallel-vars');
const Api = require('./api');
const DefaultReporter = require('./reporters/default');
const TapReporter = require('./reporters/tap');
const Watcher = require('./watcher');
const normalizeExtensions = require('./extensions');
const normalizeModuleTypes = require('./module-types');
const {normalizeGlobs, normalizePattern} = require('./globs');
const normalizeNodeArguments = require('./node-arguments');
const validateEnvironmentVariables = require('./environment-variables');
const {splitPatternAndLineNumbers} = require('./line-numbers');
const providerManager = require('./provider-manager');
let pkg;
try {
pkg = readPkg.sync({cwd: projectDir});
pkg = JSON.parse(fs.readFileSync(path.resolve(projectDir, 'package.json')));
} catch (error) {
if (error.code !== 'ENOENT') {
throw error;
@ -303,26 +331,13 @@ exports.run = async () => { // eslint-disable-line complexity
const {type: defaultModuleType = 'commonjs'} = pkg || {};
const providers = [];
if (Reflect.has(conf, 'babel')) {
try {
const {level, main} = 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} = providerManager.typescript(projectDir);
const {level, main} = await providerManager.typescript(projectDir);
providers.push({
level,
main: main({config: conf.typescript}),
type: 'typescript'
type: 'typescript',
});
} catch (error) {
exit(error.message);
@ -377,16 +392,14 @@ exports.run = async () => { // eslint-disable-line complexity
.map(pattern => splitPatternAndLineNumbers(pattern))
.map(({pattern, ...rest}) => ({
pattern: normalizePattern(path.relative(projectDir, path.resolve(process.cwd(), pattern))),
...rest
...rest,
}));
if (combined.updateSnapshots && filter.some(condition => condition.lineNumbers !== null)) {
exit('Snapshots cannot be updated when selecting specific tests by their line number.');
}
const api = new Api({
cacheEnabled: combined.cache !== false,
chalkOptions,
concurrency: combined.concurrency || 0,
workerThreads: combined.workerThreads !== false,
debug,
environmentVariables,
experiments,
@ -406,38 +419,31 @@ exports.run = async () => { // eslint-disable-line complexity
snapshotDir: combined.snapshotDir ? path.resolve(projectDir, combined.snapshotDir) : null,
timeout: combined.timeout || '10s',
updateSnapshots: combined.updateSnapshots,
workerArgv: argv['--']
workerArgv: argv['--'],
});
const reporter = combined.tap && !combined.watch && debug === null ? new TapReporter({
extensions: globs.extensions,
projectDir,
reportStream: process.stdout,
stdStream: process.stderr
stdStream: process.stderr,
}) : new DefaultReporter({
extensions: globs.extensions,
projectDir,
reportStream: process.stdout,
stdStream: process.stderr,
watching: combined.watch,
verbose: debug !== null || combined.verbose || isCi || !process.stdout.isTTY
});
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 {controlFlow} = require('./ipc-flow-control');
const bufferedSend = controlFlow(process);
if (process.versions.node >= '12.16.0') {
plan.status.on('stateChange', evt => {
bufferedSend(evt);
});
} else {
const v8 = require('v8');
plan.status.on('stateChange', evt => {
bufferedSend([...v8.serialize(evt)]);
});
}
plan.status.on('stateChange', evt => {
bufferedSend(evt);
});
}
plan.status.on('stateChange', evt => {
@ -455,7 +461,7 @@ exports.run = async () => { // eslint-disable-line complexity
globs,
projectDir,
providers,
reporter
reporter,
});
watcher.observeStdin(process.stdin);
} else {
@ -476,4 +482,4 @@ exports.run = async () => { // eslint-disable-line complexity
process.exitCode = runStatus.suggestExitCode({matching: match.length > 0});
reporter.endRun();
}
};
}