-
-
Notifications
You must be signed in to change notification settings - Fork 6.5k
/
Copy pathindex.js
395 lines (344 loc) · 10.4 KB
/
index.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
/**
* Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
import type {AggregatedResult} from 'types/TestResult';
import type {Argv} from 'types/Argv';
import type {GlobalConfig, Path, ProjectConfig} from 'types/Config';
import {Console, clearLine, createDirectory} from 'jest-util';
import {validateCLIOptions} from 'jest-validate';
import {readConfig} from 'jest-config';
import {version as VERSION} from '../../package.json';
import * as args from './args';
import chalk from 'chalk';
import createContext from '../lib/create_context';
import exit from 'exit';
import getChangedFilesPromise from '../get_changed_files_promise';
import fs from 'fs';
import handleDeprecationWarnings from '../lib/handle_deprecation_warnings';
import logDebugMessages from '../lib/log_debug_messages';
import {print as preRunMessagePrint} from '../pre_run_message';
import runJest from '../run_jest';
import Runtime from 'jest-runtime';
import TestWatcher from '../test_watcher';
import watch from '../watch';
import yargs from 'yargs';
import rimraf from 'rimraf';
import {sync as realpath} from 'realpath-native';
export async function run(maybeArgv?: Argv, project?: Path) {
try {
const argv: Argv = buildArgv(maybeArgv, project);
const projects = getProjectListFromCLIArgs(argv, project);
const {results, globalConfig} = await runCLI(argv, projects);
readResultsAndExit(results, globalConfig);
} catch (error) {
clearLine(process.stderr);
clearLine(process.stdout);
console.error(chalk.red(error.stack));
exit(1);
throw error;
}
}
export const runCLI = async (
argv: Argv,
projects: Array<Path>,
): Promise<{results: AggregatedResult, globalConfig: GlobalConfig}> => {
const realFs = require('fs');
const fs = require('graceful-fs');
fs.gracefulify(realFs);
let results;
// If we output a JSON object, we can't write anything to stdout, since
// it'll break the JSON structure and it won't be valid.
const outputStream =
argv.json || argv.useStderr ? process.stderr : process.stdout;
argv.version && printVersionAndExit(outputStream);
const {globalConfig, configs, hasDeprecationWarnings} = getConfigs(
projects,
argv,
outputStream,
);
if (argv.clearCache) {
configs.forEach(config => {
rimraf.sync(config.cacheDirectory);
process.stdout.write(`Cleared ${config.cacheDirectory}\n`);
});
exit(0);
}
await _run(
globalConfig,
configs,
hasDeprecationWarnings,
outputStream,
(r: AggregatedResult) => (results = r),
);
if (argv.watch || argv.watchAll) {
// If in watch mode, return the promise that will never resolve.
// If the watch mode is interrupted, watch should handle the process
// shutdown.
return new Promise(() => {});
}
if (!results) {
throw new Error(
'AggregatedResult must be present after test run is complete',
);
}
return Promise.resolve({globalConfig, results});
};
const readResultsAndExit = (
result: ?AggregatedResult,
globalConfig: GlobalConfig,
) => {
const code = !result || result.success ? 0 : globalConfig.testFailureExitCode;
process.on('exit', () => (process.exitCode = code));
if (globalConfig.forceExit) {
exit(code);
}
};
const buildArgv = (maybeArgv: ?Argv, project: ?Path) => {
const argv: Argv = yargs(maybeArgv || process.argv.slice(2))
.usage(args.usage)
.alias('help', 'h')
.options(args.options)
.epilogue(args.docs)
.check(args.check)
.version(false).argv;
validateCLIOptions(argv, args.options);
return argv;
};
const getProjectListFromCLIArgs = (argv, project: ?Path) => {
const projects = argv.projects ? argv.projects : [];
if (project) {
projects.push(project);
}
if (!projects.length && process.platform === 'win32') {
try {
projects.push(realpath(process.cwd()));
} catch (err) {
// do nothing, just catch error
// process.binding('fs').realpath can throw, e.g. on mapped drives
}
}
if (!projects.length) {
projects.push(process.cwd());
}
return projects;
};
const printDebugInfoAndExitIfNeeded = (
argv,
globalConfig,
configs,
outputStream,
) => {
if (argv.debug || argv.showConfig) {
logDebugMessages(globalConfig, configs, outputStream);
}
if (argv.showConfig) {
exit(0);
}
};
const printVersionAndExit = outputStream => {
outputStream.write(`v${VERSION}\n`);
exit(0);
};
const ensureNoDuplicateConfigs = (parsedConfigs, projects, rootConfigPath) => {
const configPathMap = new Map();
for (const config of parsedConfigs) {
const {configPath} = config;
if (configPathMap.has(configPath)) {
const message = `Whoops! Two projects resolved to the same config path: ${chalk.bold(
String(configPath),
)}:
Project 1: ${chalk.bold(projects[parsedConfigs.findIndex(x => x === config)])}
Project 2: ${chalk.bold(
projects[parsedConfigs.findIndex(x => x === configPathMap.get(configPath))],
)}
This usually means that your ${chalk.bold(
'"projects"',
)} config includes a directory that doesn't have any configuration recognizable by Jest. Please fix it.
`;
throw new Error(message);
}
if (configPath !== null) {
configPathMap.set(configPath, config);
}
}
};
// Possible scenarios:
// 1. jest --config config.json
// 2. jest --projects p1 p2
// 3. jest --projects p1 p2 --config config.json
// 4. jest --projects p1
// 5. jest
//
// If no projects are specified, process.cwd() will be used as the default
// (and only) project.
const getConfigs = (
projectsFromCLIArgs: Array<Path>,
argv: Argv,
outputStream,
): {
globalConfig: GlobalConfig,
configs: Array<ProjectConfig>,
hasDeprecationWarnings: boolean,
} => {
let globalConfig;
let hasDeprecationWarnings;
let configs: Array<ProjectConfig> = [];
let projects = projectsFromCLIArgs;
let configPath: ?Path;
if (projectsFromCLIArgs.length === 1) {
const parsedConfig = readConfig(argv, projects[0]);
configPath = parsedConfig.configPath;
if (parsedConfig.globalConfig.projects) {
// If this was a single project, and its config has `projects`
// settings, use that value instead.
projects = parsedConfig.globalConfig.projects;
}
hasDeprecationWarnings = parsedConfig.hasDeprecationWarnings;
globalConfig = parsedConfig.globalConfig;
configs = [parsedConfig.projectConfig];
if (globalConfig.projects && globalConfig.projects.length) {
// Even though we had one project in CLI args, there might be more
// projects defined in the config.
projects = globalConfig.projects;
}
}
if (projects.length > 1) {
const parsedConfigs = projects
.filter(root => {
// Ignore globbed files that cannot be `require`d.
if (
fs.existsSync(root) &&
!fs.lstatSync(root).isDirectory() &&
!root.endsWith('.js') &&
!root.endsWith('.json')
) {
return false;
}
return true;
})
.map(root => readConfig(argv, root, true, configPath));
ensureNoDuplicateConfigs(parsedConfigs, projects, configPath);
configs = parsedConfigs.map(({projectConfig}) => projectConfig);
if (!hasDeprecationWarnings) {
hasDeprecationWarnings = parsedConfigs.some(
({hasDeprecationWarnings}) => !!hasDeprecationWarnings,
);
}
// If no config was passed initially, use the one from the first project
if (!globalConfig) {
globalConfig = parsedConfigs[0].globalConfig;
}
}
if (!globalConfig || !configs.length) {
throw new Error('jest: No configuration found for any project.');
}
printDebugInfoAndExitIfNeeded(argv, globalConfig, configs, outputStream);
return {
configs,
globalConfig,
hasDeprecationWarnings: !!hasDeprecationWarnings,
};
};
const buildContextsAndHasteMaps = async (
configs,
globalConfig,
outputStream,
) => {
const hasteMapInstances = Array(configs.length);
const contexts = await Promise.all(
configs.map(async (config, index) => {
createDirectory(config.cacheDirectory);
const hasteMapInstance = Runtime.createHasteMap(config, {
console: new Console(outputStream, outputStream),
maxWorkers: globalConfig.maxWorkers,
resetCache: !config.cache,
watch: globalConfig.watch || globalConfig.watchAll,
watchman: globalConfig.watchman,
});
hasteMapInstances[index] = hasteMapInstance;
return createContext(config, await hasteMapInstance.build());
}),
);
return {contexts, hasteMapInstances};
};
const _run = async (
globalConfig,
configs,
hasDeprecationWarnings,
outputStream,
onComplete,
) => {
// Queries to hg/git can take a while, so we need to start the process
// as soon as possible, so by the time we need the result it's already there.
const changedFilesPromise = getChangedFilesPromise(globalConfig, configs);
const {contexts, hasteMapInstances} = await buildContextsAndHasteMaps(
configs,
globalConfig,
outputStream,
);
globalConfig.watch || globalConfig.watchAll
? await runWatch(
contexts,
configs,
hasDeprecationWarnings,
globalConfig,
outputStream,
hasteMapInstances,
changedFilesPromise,
)
: await runWithoutWatch(
globalConfig,
contexts,
outputStream,
onComplete,
changedFilesPromise,
);
};
const runWatch = async (
contexts,
configs,
hasDeprecationWarnings,
globalConfig,
outputStream,
hasteMapInstances,
changedFilesPromise,
) => {
if (hasDeprecationWarnings) {
try {
await handleDeprecationWarnings(outputStream, process.stdin);
return watch(globalConfig, contexts, outputStream, hasteMapInstances);
} catch (e) {
exit(0);
}
}
return watch(globalConfig, contexts, outputStream, hasteMapInstances);
};
const runWithoutWatch = async (
globalConfig,
contexts,
outputStream,
onComplete,
changedFilesPromise,
) => {
const startRun = async () => {
if (!globalConfig.listTests) {
preRunMessagePrint(outputStream);
}
return await runJest({
changedFilesPromise,
contexts,
failedTestsCache: null,
globalConfig,
onComplete,
outputStream,
startRun,
testWatcher: new TestWatcher({isWatchMode: false}),
});
};
return await startRun();
};