SearchSource.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490
  1. 'use strict';
  2. Object.defineProperty(exports, '__esModule', {
  3. value: true
  4. });
  5. exports.default = void 0;
  6. function os() {
  7. const data = _interopRequireWildcard(require('os'));
  8. os = function () {
  9. return data;
  10. };
  11. return data;
  12. }
  13. function path() {
  14. const data = _interopRequireWildcard(require('path'));
  15. path = function () {
  16. return data;
  17. };
  18. return data;
  19. }
  20. function _micromatch() {
  21. const data = _interopRequireDefault(require('micromatch'));
  22. _micromatch = function () {
  23. return data;
  24. };
  25. return data;
  26. }
  27. function _jestConfig() {
  28. const data = require('jest-config');
  29. _jestConfig = function () {
  30. return data;
  31. };
  32. return data;
  33. }
  34. function _jestRegexUtil() {
  35. const data = require('jest-regex-util');
  36. _jestRegexUtil = function () {
  37. return data;
  38. };
  39. return data;
  40. }
  41. function _jestResolveDependencies() {
  42. const data = require('jest-resolve-dependencies');
  43. _jestResolveDependencies = function () {
  44. return data;
  45. };
  46. return data;
  47. }
  48. function _jestSnapshot() {
  49. const data = require('jest-snapshot');
  50. _jestSnapshot = function () {
  51. return data;
  52. };
  53. return data;
  54. }
  55. function _jestUtil() {
  56. const data = require('jest-util');
  57. _jestUtil = function () {
  58. return data;
  59. };
  60. return data;
  61. }
  62. function _interopRequireDefault(obj) {
  63. return obj && obj.__esModule ? obj : {default: obj};
  64. }
  65. function _getRequireWildcardCache(nodeInterop) {
  66. if (typeof WeakMap !== 'function') return null;
  67. var cacheBabelInterop = new WeakMap();
  68. var cacheNodeInterop = new WeakMap();
  69. return (_getRequireWildcardCache = function (nodeInterop) {
  70. return nodeInterop ? cacheNodeInterop : cacheBabelInterop;
  71. })(nodeInterop);
  72. }
  73. function _interopRequireWildcard(obj, nodeInterop) {
  74. if (!nodeInterop && obj && obj.__esModule) {
  75. return obj;
  76. }
  77. if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) {
  78. return {default: obj};
  79. }
  80. var cache = _getRequireWildcardCache(nodeInterop);
  81. if (cache && cache.has(obj)) {
  82. return cache.get(obj);
  83. }
  84. var newObj = {};
  85. var hasPropertyDescriptor =
  86. Object.defineProperty && Object.getOwnPropertyDescriptor;
  87. for (var key in obj) {
  88. if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) {
  89. var desc = hasPropertyDescriptor
  90. ? Object.getOwnPropertyDescriptor(obj, key)
  91. : null;
  92. if (desc && (desc.get || desc.set)) {
  93. Object.defineProperty(newObj, key, desc);
  94. } else {
  95. newObj[key] = obj[key];
  96. }
  97. }
  98. }
  99. newObj.default = obj;
  100. if (cache) {
  101. cache.set(obj, newObj);
  102. }
  103. return newObj;
  104. }
  105. function _defineProperty(obj, key, value) {
  106. if (key in obj) {
  107. Object.defineProperty(obj, key, {
  108. value: value,
  109. enumerable: true,
  110. configurable: true,
  111. writable: true
  112. });
  113. } else {
  114. obj[key] = value;
  115. }
  116. return obj;
  117. }
  118. const regexToMatcher = testRegex => {
  119. const regexes = testRegex.map(testRegex => new RegExp(testRegex));
  120. return path =>
  121. regexes.some(regex => {
  122. const result = regex.test(path); // prevent stateful regexes from breaking, just in case
  123. regex.lastIndex = 0;
  124. return result;
  125. });
  126. };
  127. const toTests = (context, tests) =>
  128. tests.map(path => ({
  129. context,
  130. duration: undefined,
  131. path
  132. }));
  133. const hasSCM = changedFilesInfo => {
  134. const {repos} = changedFilesInfo; // no SCM (git/hg/...) is found in any of the roots.
  135. const noSCM = Object.values(repos).every(scm => scm.size === 0);
  136. return !noSCM;
  137. };
  138. class SearchSource {
  139. constructor(context) {
  140. _defineProperty(this, '_context', void 0);
  141. _defineProperty(this, '_dependencyResolver', void 0);
  142. _defineProperty(this, '_testPathCases', []);
  143. const {config} = context;
  144. this._context = context;
  145. this._dependencyResolver = null;
  146. const rootPattern = new RegExp(
  147. config.roots
  148. .map(dir => (0, _jestRegexUtil().escapePathForRegex)(dir + path().sep))
  149. .join('|')
  150. );
  151. this._testPathCases.push({
  152. isMatch: path => rootPattern.test(path),
  153. stat: 'roots'
  154. });
  155. if (config.testMatch.length) {
  156. this._testPathCases.push({
  157. isMatch: (0, _jestUtil().globsToMatcher)(config.testMatch),
  158. stat: 'testMatch'
  159. });
  160. }
  161. if (config.testPathIgnorePatterns.length) {
  162. const testIgnorePatternsRegex = new RegExp(
  163. config.testPathIgnorePatterns.join('|')
  164. );
  165. this._testPathCases.push({
  166. isMatch: path => !testIgnorePatternsRegex.test(path),
  167. stat: 'testPathIgnorePatterns'
  168. });
  169. }
  170. if (config.testRegex.length) {
  171. this._testPathCases.push({
  172. isMatch: regexToMatcher(config.testRegex),
  173. stat: 'testRegex'
  174. });
  175. }
  176. }
  177. async _getOrBuildDependencyResolver() {
  178. if (!this._dependencyResolver) {
  179. this._dependencyResolver =
  180. new (_jestResolveDependencies().DependencyResolver)(
  181. this._context.resolver,
  182. this._context.hasteFS,
  183. await (0, _jestSnapshot().buildSnapshotResolver)(this._context.config)
  184. );
  185. }
  186. return this._dependencyResolver;
  187. }
  188. _filterTestPathsWithStats(allPaths, testPathPattern) {
  189. const data = {
  190. stats: {
  191. roots: 0,
  192. testMatch: 0,
  193. testPathIgnorePatterns: 0,
  194. testRegex: 0
  195. },
  196. tests: [],
  197. total: allPaths.length
  198. };
  199. const testCases = Array.from(this._testPathCases); // clone
  200. if (testPathPattern) {
  201. const regex = (0, _jestUtil().testPathPatternToRegExp)(testPathPattern);
  202. testCases.push({
  203. isMatch: path => regex.test(path),
  204. stat: 'testPathPattern'
  205. });
  206. data.stats.testPathPattern = 0;
  207. }
  208. data.tests = allPaths.filter(test => {
  209. let filterResult = true;
  210. for (const {isMatch, stat} of testCases) {
  211. if (isMatch(test.path)) {
  212. data.stats[stat]++;
  213. } else {
  214. filterResult = false;
  215. }
  216. }
  217. return filterResult;
  218. });
  219. return data;
  220. }
  221. _getAllTestPaths(testPathPattern) {
  222. return this._filterTestPathsWithStats(
  223. toTests(this._context, this._context.hasteFS.getAllFiles()),
  224. testPathPattern
  225. );
  226. }
  227. isTestFilePath(path) {
  228. return this._testPathCases.every(testCase => testCase.isMatch(path));
  229. }
  230. findMatchingTests(testPathPattern) {
  231. return this._getAllTestPaths(testPathPattern);
  232. }
  233. async findRelatedTests(allPaths, collectCoverage) {
  234. const dependencyResolver = await this._getOrBuildDependencyResolver();
  235. if (!collectCoverage) {
  236. return {
  237. tests: toTests(
  238. this._context,
  239. dependencyResolver.resolveInverse(
  240. allPaths,
  241. this.isTestFilePath.bind(this),
  242. {
  243. skipNodeResolution: this._context.config.skipNodeResolution
  244. }
  245. )
  246. )
  247. };
  248. }
  249. const testModulesMap = dependencyResolver.resolveInverseModuleMap(
  250. allPaths,
  251. this.isTestFilePath.bind(this),
  252. {
  253. skipNodeResolution: this._context.config.skipNodeResolution
  254. }
  255. );
  256. const allPathsAbsolute = Array.from(allPaths).map(p => path().resolve(p));
  257. const collectCoverageFrom = new Set();
  258. testModulesMap.forEach(testModule => {
  259. if (!testModule.dependencies) {
  260. return;
  261. }
  262. testModule.dependencies.forEach(p => {
  263. if (!allPathsAbsolute.includes(p)) {
  264. return;
  265. }
  266. const filename = (0, _jestConfig().replaceRootDirInPath)(
  267. this._context.config.rootDir,
  268. p
  269. );
  270. collectCoverageFrom.add(
  271. path().isAbsolute(filename)
  272. ? path().relative(this._context.config.rootDir, filename)
  273. : filename
  274. );
  275. });
  276. });
  277. return {
  278. collectCoverageFrom,
  279. tests: toTests(
  280. this._context,
  281. testModulesMap.map(testModule => testModule.file)
  282. )
  283. };
  284. }
  285. findTestsByPaths(paths) {
  286. return {
  287. tests: toTests(
  288. this._context,
  289. paths
  290. .map(p => path().resolve(this._context.config.cwd, p))
  291. .filter(this.isTestFilePath.bind(this))
  292. )
  293. };
  294. }
  295. async findRelatedTestsFromPattern(paths, collectCoverage) {
  296. if (Array.isArray(paths) && paths.length) {
  297. const resolvedPaths = paths.map(p =>
  298. path().resolve(this._context.config.cwd, p)
  299. );
  300. return this.findRelatedTests(new Set(resolvedPaths), collectCoverage);
  301. }
  302. return {
  303. tests: []
  304. };
  305. }
  306. async findTestRelatedToChangedFiles(changedFilesInfo, collectCoverage) {
  307. if (!hasSCM(changedFilesInfo)) {
  308. return {
  309. noSCM: true,
  310. tests: []
  311. };
  312. }
  313. const {changedFiles} = changedFilesInfo;
  314. return this.findRelatedTests(changedFiles, collectCoverage);
  315. }
  316. async _getTestPaths(globalConfig, changedFiles) {
  317. if (globalConfig.onlyChanged) {
  318. if (!changedFiles) {
  319. throw new Error('Changed files must be set when running with -o.');
  320. }
  321. return this.findTestRelatedToChangedFiles(
  322. changedFiles,
  323. globalConfig.collectCoverage
  324. );
  325. }
  326. let paths = globalConfig.nonFlagArgs;
  327. if (globalConfig.findRelatedTests && 'win32' === os().platform()) {
  328. paths = this.filterPathsWin32(paths);
  329. }
  330. if (globalConfig.runTestsByPath && paths && paths.length) {
  331. return this.findTestsByPaths(paths);
  332. } else if (globalConfig.findRelatedTests && paths && paths.length) {
  333. return this.findRelatedTestsFromPattern(
  334. paths,
  335. globalConfig.collectCoverage
  336. );
  337. } else if (globalConfig.testPathPattern != null) {
  338. return this.findMatchingTests(globalConfig.testPathPattern);
  339. } else {
  340. return {
  341. tests: []
  342. };
  343. }
  344. }
  345. filterPathsWin32(paths) {
  346. const allFiles = this._context.hasteFS.getAllFiles();
  347. const options = {
  348. nocase: true,
  349. windows: false
  350. };
  351. function normalizePosix(filePath) {
  352. return filePath.replace(/\\/g, '/');
  353. }
  354. paths = paths
  355. .map(p => {
  356. // micromatch works with forward slashes: https://github.com/micromatch/micromatch#backslashes
  357. const normalizedPath = normalizePosix(
  358. path().resolve(this._context.config.cwd, p)
  359. );
  360. const match = (0, _micromatch().default)(
  361. allFiles.map(normalizePosix),
  362. normalizedPath,
  363. options
  364. );
  365. return match[0];
  366. })
  367. .filter(Boolean)
  368. .map(p => path().resolve(p));
  369. return paths;
  370. }
  371. async getTestPaths(globalConfig, changedFiles, filter) {
  372. const searchResult = await this._getTestPaths(globalConfig, changedFiles);
  373. const filterPath = globalConfig.filter;
  374. if (filter) {
  375. const tests = searchResult.tests;
  376. const filterResult = await filter(tests.map(test => test.path));
  377. if (!Array.isArray(filterResult.filtered)) {
  378. throw new Error(
  379. `Filter ${filterPath} did not return a valid test list`
  380. );
  381. }
  382. const filteredSet = new Set(
  383. filterResult.filtered.map(result => result.test)
  384. );
  385. return {
  386. ...searchResult,
  387. tests: tests.filter(test => filteredSet.has(test.path))
  388. };
  389. }
  390. return searchResult;
  391. }
  392. async findRelatedSourcesFromTestsInChangedFiles(changedFilesInfo) {
  393. if (!hasSCM(changedFilesInfo)) {
  394. return [];
  395. }
  396. const {changedFiles} = changedFilesInfo;
  397. const dependencyResolver = await this._getOrBuildDependencyResolver();
  398. const relatedSourcesSet = new Set();
  399. changedFiles.forEach(filePath => {
  400. if (this.isTestFilePath(filePath)) {
  401. const sourcePaths = dependencyResolver.resolve(filePath, {
  402. skipNodeResolution: this._context.config.skipNodeResolution
  403. });
  404. sourcePaths.forEach(sourcePath => relatedSourcesSet.add(sourcePath));
  405. }
  406. });
  407. return Array.from(relatedSourcesSet);
  408. }
  409. }
  410. exports.default = SearchSource;