-
-
Notifications
You must be signed in to change notification settings - Fork 6.5k
/
search_source.js
248 lines (216 loc) · 6.99 KB
/
search_source.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
/**
* 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 {Context} from 'types/Context';
import type {Glob, GlobalConfig, Path} from 'types/Config';
import type {Test} from 'types/TestRunner';
import type {ChangedFilesPromise} from 'types/ChangedFiles';
import fs from 'fs';
import path from 'path';
import micromatch from 'micromatch';
import DependencyResolver from 'jest-resolve-dependencies';
import testPathPatternToRegExp from './test_path_pattern_to_regexp';
import {escapePathForRegex, replacePathSepForRegex} from 'jest-regex-util';
type SearchResult = {|
noSCM?: boolean,
stats?: {[key: string]: number},
tests: Array<Test>,
total?: number,
|};
export type TestSelectionConfig = {|
input?: string,
findRelatedTests?: boolean,
onlyChanged?: boolean,
paths?: Array<Path>,
shouldTreatInputAsPattern?: boolean,
testPathPattern?: string,
watch?: boolean,
|};
const pathToRegex = p => replacePathSepForRegex(p);
const globsToMatcher = (globs: ?Array<Glob>) => {
if (globs == null || globs.length === 0) {
return () => true;
}
const matchers = globs.map(each => micromatch.matcher(each, {dot: true}));
return path => matchers.some(each => each(path));
};
const regexToMatcher = (testRegex: string) => {
if (!testRegex) {
return () => true;
}
const regex = new RegExp(pathToRegex(testRegex));
return path => regex.test(path);
};
const toTests = (context, tests) =>
tests.map(path => ({
context,
duration: undefined,
path,
}));
export default class SearchSource {
_context: Context;
_rootPattern: RegExp;
_testIgnorePattern: ?RegExp;
_testPathCases: {
roots: (path: Path) => boolean,
testMatch: (path: Path) => boolean,
testRegex: (path: Path) => boolean,
testPathIgnorePatterns: (path: Path) => boolean,
};
constructor(context: Context) {
const {config} = context;
this._context = context;
this._rootPattern = new RegExp(
config.roots.map(dir => escapePathForRegex(dir + path.sep)).join('|'),
);
const ignorePattern = config.testPathIgnorePatterns;
this._testIgnorePattern = ignorePattern.length
? new RegExp(ignorePattern.join('|'))
: null;
this._testPathCases = {
roots: path => this._rootPattern.test(path),
testMatch: globsToMatcher(config.testMatch),
testPathIgnorePatterns: path =>
!this._testIgnorePattern || !this._testIgnorePattern.test(path),
testRegex: regexToMatcher(config.testRegex),
};
}
_filterTestPathsWithStats(
allPaths: Array<Test>,
testPathPattern?: string,
): SearchResult {
const data = {
stats: {},
tests: [],
total: allPaths.length,
};
const testCases = Object.assign({}, this._testPathCases);
if (testPathPattern) {
const regex = testPathPatternToRegExp(testPathPattern);
testCases.testPathPattern = path => regex.test(path);
}
const testCasesKeys = Object.keys(testCases);
data.tests = allPaths.filter(test => {
return testCasesKeys.reduce((flag, key) => {
if (testCases[key](test.path)) {
data.stats[key] = ++data.stats[key] || 1;
return flag && true;
}
data.stats[key] = data.stats[key] || 0;
return false;
}, true);
});
return data;
}
_getAllTestPaths(testPathPattern: string): SearchResult {
return this._filterTestPathsWithStats(
toTests(this._context, this._context.hasteFS.getAllFiles()),
testPathPattern,
);
}
isTestFilePath(path: Path): boolean {
return Object.keys(this._testPathCases).every(key =>
this._testPathCases[key](path),
);
}
findMatchingTests(testPathPattern: string): SearchResult {
return this._getAllTestPaths(testPathPattern);
}
findRelatedTests(allPaths: Set<Path>): SearchResult {
const dependencyResolver = new DependencyResolver(
this._context.resolver,
this._context.hasteFS,
);
return {
tests: toTests(
this._context,
dependencyResolver.resolveInverse(
allPaths,
this.isTestFilePath.bind(this),
{
skipNodeResolution: this._context.config.skipNodeResolution,
},
),
),
};
}
findTestsByPaths(paths: Array<Path>): SearchResult {
return {
tests: toTests(
this._context,
paths
.map(p => path.resolve(process.cwd(), p))
.filter(this.isTestFilePath.bind(this)),
),
};
}
findRelatedTestsFromPattern(paths: Array<Path>): SearchResult {
if (Array.isArray(paths) && paths.length) {
const resolvedPaths = paths.map(p => path.resolve(process.cwd(), p));
return this.findRelatedTests(new Set(resolvedPaths));
}
return {tests: []};
}
async findTestRelatedToChangedFiles(
changedFilesPromise: ChangedFilesPromise,
) {
const {repos, changedFiles} = await changedFilesPromise;
// no SCM (git/hg/...) is found in any of the roots.
const noSCM = Object.keys(repos).every(scm => repos[scm].size === 0);
return noSCM
? {noSCM: true, tests: []}
: this.findRelatedTests(changedFiles);
}
async getTestPaths(
globalConfig: GlobalConfig,
changedFilesPromise: ?ChangedFilesPromise,
): Promise<SearchResult> {
const paths = globalConfig.nonFlagArgs;
if (globalConfig.onlyChanged) {
if (!changedFilesPromise) {
throw new Error('This promise must be present when running with -o.');
}
return this.findTestRelatedToChangedFiles(changedFilesPromise);
} else if (globalConfig.runTestsByPath && paths && paths.length) {
return Promise.resolve(this.findTestsByPaths(paths));
} else if (globalConfig.findRelatedTests && paths && paths.length) {
return Promise.resolve(this.findRelatedTestsFromPattern(paths));
} else {
const allFiles = new Set(this._context.hasteFS.getAllFiles());
const validTestPaths =
paths &&
paths.filter(name => {
const fullName = path.resolve(name);
try {
if (!fs.lstatSync(fullName).isFile()) {
// It exists, but it is not a file.
return false;
}
} catch (e) {
// It does not exist.
return false;
}
// The file exists, but it is explicitly blacklisted.
if (!this._testPathCases.testPathIgnorePatterns(fullName)) {
return false;
}
// It exists and it is a file; return true if it's in the project.
return allFiles.has(fullName);
});
if (validTestPaths && validTestPaths.length) {
return Promise.resolve({tests: toTests(this._context, validTestPaths)});
} else if (globalConfig.testPathPattern != null) {
return Promise.resolve(
this.findMatchingTests(globalConfig.testPathPattern),
);
} else {
return Promise.resolve({tests: []});
}
}
}
}