-
-
Notifications
You must be signed in to change notification settings - Fork 6.6k
Expand file tree
/
Copy pathwatch.js
More file actions
337 lines (300 loc) · 9.99 KB
/
watch.js
File metadata and controls
337 lines (300 loc) · 9.99 KB
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
/**
* 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 {GlobalConfig} from 'types/Config';
import type {Context} from 'types/Context';
import ansiEscapes from 'ansi-escapes';
import chalk from 'chalk';
import getChangedFilesPromise from './get_changed_files_promise';
import {replacePathSepForRegex} from 'jest-regex-util';
import HasteMap from 'jest-haste-map';
import isCI from 'is-ci';
import isValidPath from './lib/is_valid_path';
import {print as preRunMessagePrint} from './pre_run_message';
import createContext from './lib/create_context';
import runJest from './run_jest';
import updateGlobalConfig from './lib/update_global_config';
import SearchSource from './search_source';
import TestWatcher from './test_watcher';
import Prompt from './lib/Prompt';
import TestPathPatternPrompt from './test_path_pattern_prompt';
import TestNamePatternPrompt from './test_name_pattern_prompt';
import {KEYS, CLEAR} from './constants';
const isInteractive = process.stdout.isTTY && !isCI;
let hasExitListener = false;
export default function watch(
initialGlobalConfig: GlobalConfig,
contexts: Array<Context>,
outputStream: stream$Writable | tty$WriteStream,
hasteMapInstances: Array<HasteMap>,
stdin?: stream$Readable | tty$ReadStream = process.stdin,
) {
// `globalConfig` will be consantly updated and reassigned as a result of
// watch mode interactions.
let globalConfig = initialGlobalConfig;
globalConfig = updateGlobalConfig(globalConfig, {
mode: globalConfig.watch ? 'watch' : 'watchAll',
});
const prompt = new Prompt();
const testPathPatternPrompt = new TestPathPatternPrompt(outputStream, prompt);
const testNamePatternPrompt = new TestNamePatternPrompt(outputStream, prompt);
let searchSources = contexts.map(context => ({
context,
searchSource: new SearchSource(context),
}));
let hasSnapshotFailure = false;
let isRunning = false;
let testWatcher;
let shouldDisplayWatchUsage = true;
let isWatchUsageDisplayed = false;
testPathPatternPrompt.updateSearchSources(searchSources);
hasteMapInstances.forEach((hasteMapInstance, index) => {
hasteMapInstance.on('change', ({eventsQueue, hasteFS, moduleMap}) => {
const validPaths = eventsQueue.filter(({filePath}) => {
return isValidPath(globalConfig, contexts[index].config, filePath);
});
if (validPaths.length) {
const context = (contexts[index] = createContext(
contexts[index].config,
{
hasteFS,
moduleMap,
},
));
prompt.abort();
searchSources = searchSources.slice();
searchSources[index] = {
context,
searchSource: new SearchSource(context),
};
testPathPatternPrompt.updateSearchSources(searchSources);
startRun(globalConfig);
}
});
});
if (!hasExitListener) {
hasExitListener = true;
process.on('exit', () => {
if (prompt.isEntering()) {
outputStream.write(ansiEscapes.cursorDown());
outputStream.write(ansiEscapes.eraseDown);
}
});
}
const startRun = (globalConfig: GlobalConfig) => {
if (isRunning) {
return null;
}
testWatcher = new TestWatcher({isWatchMode: true});
isInteractive && outputStream.write(CLEAR);
preRunMessagePrint(outputStream);
isRunning = true;
const configs = contexts.map(context => context.config);
const changedFilesPromise = getChangedFilesPromise(globalConfig, configs);
return runJest({
changedFilesPromise,
contexts,
globalConfig,
onComplete: results => {
isRunning = false;
hasSnapshotFailure = !!results.snapshot.failure;
// Create a new testWatcher instance so that re-runs won't be blocked.
// The old instance that was passed to Jest will still be interrupted
// and prevent test runs from the previous run.
testWatcher = new TestWatcher({isWatchMode: true});
if (shouldDisplayWatchUsage) {
outputStream.write(usage(globalConfig, hasSnapshotFailure));
shouldDisplayWatchUsage = false; // hide Watch Usage after first run
isWatchUsageDisplayed = true;
} else {
outputStream.write(showToggleUsagePrompt());
shouldDisplayWatchUsage = false;
isWatchUsageDisplayed = false;
}
testNamePatternPrompt.updateCachedTestResults(results.testResults);
},
outputStream,
startRun,
testWatcher,
}).catch(error => console.error(chalk.red(error.stack)));
};
const onKeypress = (key: string) => {
if (key === KEYS.CONTROL_C || key === KEYS.CONTROL_D) {
process.exit(0);
return;
}
if (prompt.isEntering()) {
prompt.put(key);
return;
}
// Abort test run
if (
isRunning &&
testWatcher &&
[KEYS.Q, KEYS.ENTER, KEYS.A, KEYS.O, KEYS.P, KEYS.T].indexOf(key) !== -1
) {
testWatcher.setState({interrupted: true});
return;
}
switch (key) {
case KEYS.Q:
process.exit(0);
return;
case KEYS.ENTER:
startRun(globalConfig);
break;
case KEYS.U:
globalConfig = updateGlobalConfig(globalConfig, {
updateSnapshot: 'all',
});
startRun(globalConfig);
globalConfig = updateGlobalConfig(globalConfig, {
// updateSnapshot is not sticky after a run.
updateSnapshot: 'none',
});
break;
case KEYS.A:
globalConfig = updateGlobalConfig(globalConfig, {
mode: 'watchAll',
testNamePattern: '',
testPathPattern: '',
});
startRun(globalConfig);
break;
case KEYS.C:
globalConfig = updateGlobalConfig(globalConfig, {
mode: 'watch',
testNamePattern: '',
testPathPattern: '',
});
startRun(globalConfig);
break;
case KEYS.O:
globalConfig = updateGlobalConfig(globalConfig, {
mode: 'watch',
testNamePattern: '',
testPathPattern: '',
});
startRun(globalConfig);
break;
case KEYS.P:
testPathPatternPrompt.run(
testPathPattern => {
globalConfig = updateGlobalConfig(globalConfig, {
mode: 'watch',
testNamePattern: '',
testPathPattern: replacePathSepForRegex(testPathPattern),
});
startRun(globalConfig);
},
onCancelPatternPrompt,
{header: activeFilters(globalConfig)},
);
break;
case KEYS.T:
testNamePatternPrompt.run(
testNamePattern => {
globalConfig = updateGlobalConfig(globalConfig, {
mode: 'watch',
testNamePattern,
testPathPattern: globalConfig.testPathPattern,
});
startRun(globalConfig);
},
onCancelPatternPrompt,
{header: activeFilters(globalConfig)},
);
break;
case KEYS.QUESTION_MARK:
break;
case KEYS.W:
if (!shouldDisplayWatchUsage && !isWatchUsageDisplayed) {
outputStream.write(ansiEscapes.cursorUp());
outputStream.write(ansiEscapes.eraseDown);
outputStream.write(usage(globalConfig, hasSnapshotFailure));
isWatchUsageDisplayed = true;
shouldDisplayWatchUsage = false;
}
break;
}
};
const onCancelPatternPrompt = () => {
outputStream.write(ansiEscapes.cursorHide);
outputStream.write(ansiEscapes.clearScreen);
outputStream.write(usage(globalConfig, hasSnapshotFailure));
outputStream.write(ansiEscapes.cursorShow);
};
if (typeof stdin.setRawMode === 'function') {
stdin.setRawMode(true);
stdin.resume();
stdin.setEncoding('hex');
stdin.on('data', onKeypress);
}
startRun(globalConfig);
return Promise.resolve();
}
const activeFilters = (globalConfig: GlobalConfig, delimiter = '\n') => {
const {testNamePattern, testPathPattern} = globalConfig;
if (testNamePattern || testPathPattern) {
const filters = [
testPathPattern
? chalk.dim('filename ') + chalk.yellow('/' + testPathPattern + '/')
: null,
testNamePattern
? chalk.dim('test name ') + chalk.yellow('/' + testNamePattern + '/')
: null,
]
.filter(f => !!f)
.join(', ');
const messages = ['\n' + chalk.bold('Active Filters: ') + filters];
return messages.filter(message => !!message).join(delimiter);
}
return '';
};
const usage = (globalConfig, snapshotFailure, delimiter = '\n') => {
const messages = [
activeFilters(globalConfig),
globalConfig.testPathPattern || globalConfig.testNamePattern
? chalk.dim(' \u203A Press ') + 'c' + chalk.dim(' to clear filters.')
: null,
'\n' + chalk.bold('Watch Usage'),
globalConfig.watch
? chalk.dim(' \u203A Press ') + 'a' + chalk.dim(' to run all tests.')
: null,
(globalConfig.watchAll ||
globalConfig.testPathPattern ||
globalConfig.testNamePattern) &&
!globalConfig.noSCM
? chalk.dim(' \u203A Press ') +
'o' +
chalk.dim(' to only run tests related to changed files.')
: null,
snapshotFailure
? chalk.dim(' \u203A Press ') +
'u' +
chalk.dim(' to update failing snapshots.')
: null,
chalk.dim(' \u203A Press ') +
'p' +
chalk.dim(' to filter by a filename regex pattern.'),
chalk.dim(' \u203A Press ') +
't' +
chalk.dim(' to filter by a test name regex pattern.'),
chalk.dim(' \u203A Press ') + 'q' + chalk.dim(' to quit watch mode.'),
chalk.dim(' \u203A Press ') +
'Enter' +
chalk.dim(' to trigger a test run.'),
];
return messages.filter(message => !!message).join(delimiter) + '\n';
};
const showToggleUsagePrompt = () =>
'\n' +
chalk.bold('Watch Usage: ') +
chalk.dim('Press ') +
'w' +
chalk.dim(' to show more.');