watcher.js 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  1. 'use strict';
  2. const nodePath = require('path');
  3. const debug = require('debug')('ava:watcher');
  4. const diff = require('lodash.difference');
  5. const chokidar = require('chokidar');
  6. const flatten = require('arr-flatten');
  7. const union = require('array-union');
  8. const uniq = require('array-uniq');
  9. const AvaFiles = require('./ava-files');
  10. function rethrowAsync(err) {
  11. // Don't swallow exceptions. Note that any
  12. // expected error should already have been logged
  13. setImmediate(() => {
  14. throw err;
  15. });
  16. }
  17. const MIN_DEBOUNCE_DELAY = 10;
  18. const INITIAL_DEBOUNCE_DELAY = 100;
  19. class Debouncer {
  20. constructor(watcher) {
  21. this.watcher = watcher;
  22. this.timer = null;
  23. this.repeat = false;
  24. }
  25. debounce(delay) {
  26. if (this.timer) {
  27. this.again = true;
  28. return;
  29. }
  30. delay = delay ? Math.max(delay, MIN_DEBOUNCE_DELAY) : INITIAL_DEBOUNCE_DELAY;
  31. const timer = setTimeout(() => {
  32. this.watcher.busy.then(() => {
  33. // Do nothing if debouncing was canceled while waiting for the busy
  34. // promise to fulfil
  35. if (this.timer !== timer) {
  36. return;
  37. }
  38. if (this.again) {
  39. this.timer = null;
  40. this.again = false;
  41. this.debounce(delay / 2);
  42. } else {
  43. this.watcher.runAfterChanges();
  44. this.timer = null;
  45. this.again = false;
  46. }
  47. });
  48. }, delay);
  49. this.timer = timer;
  50. }
  51. cancel() {
  52. if (this.timer) {
  53. clearTimeout(this.timer);
  54. this.timer = null;
  55. this.again = false;
  56. }
  57. }
  58. }
  59. class TestDependency {
  60. constructor(file, sources) {
  61. this.file = file;
  62. this.sources = sources;
  63. }
  64. contains(source) {
  65. return this.sources.indexOf(source) !== -1;
  66. }
  67. }
  68. class Watcher {
  69. constructor(reporter, api, files, sources) {
  70. this.debouncer = new Debouncer(this);
  71. this.avaFiles = new AvaFiles({
  72. files,
  73. sources
  74. });
  75. this.clearLogOnNextRun = true;
  76. this.runVector = 0;
  77. this.previousFiles = files;
  78. this.run = (specificFiles, updateSnapshots) => {
  79. const clearLogOnNextRun = this.clearLogOnNextRun && this.runVector > 0;
  80. if (this.runVector > 0) {
  81. this.clearLogOnNextRun = true;
  82. }
  83. this.runVector++;
  84. let runOnlyExclusive = false;
  85. if (specificFiles) {
  86. const exclusiveFiles = specificFiles.filter(file => this.filesWithExclusiveTests.indexOf(file) !== -1);
  87. runOnlyExclusive = exclusiveFiles.length !== this.filesWithExclusiveTests.length;
  88. if (runOnlyExclusive) {
  89. // The test files that previously contained exclusive tests are always
  90. // run, together with the remaining specific files.
  91. const remainingFiles = diff(specificFiles, exclusiveFiles);
  92. specificFiles = this.filesWithExclusiveTests.concat(remainingFiles);
  93. }
  94. this.pruneFailures(specificFiles);
  95. }
  96. this.touchedFiles.clear();
  97. this.previousFiles = specificFiles || files;
  98. this.busy = api.run(this.previousFiles, {
  99. clearLogOnNextRun,
  100. previousFailures: this.sumPreviousFailures(this.runVector),
  101. runOnlyExclusive,
  102. runVector: this.runVector,
  103. updateSnapshots: updateSnapshots === true
  104. })
  105. .then(runStatus => {
  106. reporter.endRun();
  107. if (this.clearLogOnNextRun && (
  108. runStatus.stats.failedHooks > 0 ||
  109. runStatus.stats.failedTests > 0 ||
  110. runStatus.stats.failedWorkers > 0 ||
  111. runStatus.stats.internalErrors > 0 ||
  112. runStatus.stats.timeouts > 0 ||
  113. runStatus.stats.uncaughtExceptions > 0 ||
  114. runStatus.stats.unhandledRejections > 0
  115. )) {
  116. this.clearLogOnNextRun = false;
  117. }
  118. })
  119. .catch(rethrowAsync);
  120. };
  121. this.testDependencies = [];
  122. this.trackTestDependencies(api, sources);
  123. this.touchedFiles = new Set();
  124. this.trackTouchedFiles(api);
  125. this.filesWithExclusiveTests = [];
  126. this.trackExclusivity(api);
  127. this.filesWithFailures = [];
  128. this.trackFailures(api);
  129. this.dirtyStates = {};
  130. this.watchFiles();
  131. this.rerunAll();
  132. }
  133. watchFiles() {
  134. const patterns = this.avaFiles.getChokidarPatterns();
  135. chokidar.watch(patterns.paths, {
  136. ignored: patterns.ignored,
  137. ignoreInitial: true
  138. }).on('all', (event, path) => {
  139. if (event === 'add' || event === 'change' || event === 'unlink') {
  140. debug('Detected %s of %s', event, path);
  141. this.dirtyStates[path] = event;
  142. this.debouncer.debounce();
  143. }
  144. });
  145. }
  146. trackTestDependencies(api) {
  147. const relative = absPath => nodePath.relative(process.cwd(), absPath);
  148. api.on('run', plan => {
  149. plan.status.on('stateChange', evt => {
  150. if (evt.type !== 'dependencies') {
  151. return;
  152. }
  153. const sourceDeps = evt.dependencies.map(x => relative(x)).filter(this.avaFiles.isSource);
  154. this.updateTestDependencies(evt.testFile, sourceDeps);
  155. });
  156. });
  157. }
  158. updateTestDependencies(file, sources) {
  159. if (sources.length === 0) {
  160. this.testDependencies = this.testDependencies.filter(dep => dep.file !== file);
  161. return;
  162. }
  163. const isUpdate = this.testDependencies.some(dep => {
  164. if (dep.file !== file) {
  165. return false;
  166. }
  167. dep.sources = sources;
  168. return true;
  169. });
  170. if (!isUpdate) {
  171. this.testDependencies.push(new TestDependency(file, sources));
  172. }
  173. }
  174. trackTouchedFiles(api) {
  175. api.on('run', plan => {
  176. plan.status.on('stateChange', evt => {
  177. if (evt.type !== 'touched-files') {
  178. return;
  179. }
  180. for (const file of evt.files) {
  181. this.touchedFiles.add(nodePath.relative(process.cwd(), file));
  182. }
  183. });
  184. });
  185. }
  186. trackExclusivity(api) {
  187. api.on('run', plan => {
  188. plan.status.on('stateChange', evt => {
  189. if (evt.type !== 'worker-finished') {
  190. return;
  191. }
  192. const fileStats = plan.status.stats.byFile.get(evt.testFile);
  193. this.updateExclusivity(evt.testFile, fileStats.declaredTests > fileStats.selectedTests);
  194. });
  195. });
  196. }
  197. updateExclusivity(file, hasExclusiveTests) {
  198. const index = this.filesWithExclusiveTests.indexOf(file);
  199. if (hasExclusiveTests && index === -1) {
  200. this.filesWithExclusiveTests.push(file);
  201. } else if (!hasExclusiveTests && index !== -1) {
  202. this.filesWithExclusiveTests.splice(index, 1);
  203. }
  204. }
  205. trackFailures(api) {
  206. api.on('run', plan => {
  207. this.pruneFailures(plan.files);
  208. const currentVector = this.runVector;
  209. plan.status.on('stateChange', evt => {
  210. if (!evt.testFile) {
  211. return;
  212. }
  213. switch (evt.type) {
  214. case 'hook-failed':
  215. case 'internal-error':
  216. case 'test-failed':
  217. case 'uncaught-exception':
  218. case 'unhandled-rejection':
  219. case 'worker-failed':
  220. this.countFailure(evt.testFile, currentVector);
  221. break;
  222. default:
  223. break;
  224. }
  225. });
  226. });
  227. }
  228. pruneFailures(files) {
  229. const toPrune = new Set(files);
  230. this.filesWithFailures = this.filesWithFailures.filter(state => !toPrune.has(state.file));
  231. }
  232. countFailure(file, vector) {
  233. const isUpdate = this.filesWithFailures.some(state => {
  234. if (state.file !== file) {
  235. return false;
  236. }
  237. state.count++;
  238. return true;
  239. });
  240. if (!isUpdate) {
  241. this.filesWithFailures.push({
  242. file,
  243. vector,
  244. count: 1
  245. });
  246. }
  247. }
  248. sumPreviousFailures(beforeVector) {
  249. let total = 0;
  250. this.filesWithFailures.forEach(state => {
  251. if (state.vector < beforeVector) {
  252. total += state.count;
  253. }
  254. });
  255. return total;
  256. }
  257. cleanUnlinkedTests(unlinkedTests) {
  258. unlinkedTests.forEach(testFile => {
  259. this.updateTestDependencies(testFile, []);
  260. this.updateExclusivity(testFile, false);
  261. this.pruneFailures([testFile]);
  262. });
  263. }
  264. observeStdin(stdin) {
  265. stdin.resume();
  266. stdin.setEncoding('utf8');
  267. stdin.on('data', data => {
  268. data = data.trim().toLowerCase();
  269. if (data !== 'r' && data !== 'rs' && data !== 'u') {
  270. return;
  271. }
  272. // Cancel the debouncer, it might rerun specific tests whereas *all* tests
  273. // need to be rerun
  274. this.debouncer.cancel();
  275. this.busy.then(() => {
  276. // Cancel the debouncer again, it might have restarted while waiting for
  277. // the busy promise to fulfil
  278. this.debouncer.cancel();
  279. this.clearLogOnNextRun = false;
  280. if (data === 'u') {
  281. this.updatePreviousSnapshots();
  282. } else {
  283. this.rerunAll();
  284. }
  285. });
  286. });
  287. }
  288. rerunAll() {
  289. this.dirtyStates = {};
  290. this.run();
  291. }
  292. updatePreviousSnapshots() {
  293. this.dirtyStates = {};
  294. this.run(this.previousFiles, true);
  295. }
  296. runAfterChanges() {
  297. const dirtyStates = this.dirtyStates;
  298. this.dirtyStates = {};
  299. const dirtyPaths = Object.keys(dirtyStates).filter(path => {
  300. if (this.touchedFiles.has(path)) {
  301. debug('Ignoring known touched file %s', path);
  302. this.touchedFiles.delete(path);
  303. return false;
  304. }
  305. return true;
  306. });
  307. const dirtyTests = dirtyPaths.filter(this.avaFiles.isTest);
  308. const dirtySources = diff(dirtyPaths, dirtyTests);
  309. const addedOrChangedTests = dirtyTests.filter(path => dirtyStates[path] !== 'unlink');
  310. const unlinkedTests = diff(dirtyTests, addedOrChangedTests);
  311. this.cleanUnlinkedTests(unlinkedTests);
  312. // No need to rerun tests if the only change is that tests were deleted
  313. if (unlinkedTests.length === dirtyPaths.length) {
  314. return;
  315. }
  316. if (dirtySources.length === 0) {
  317. // Run any new or changed tests
  318. this.run(addedOrChangedTests);
  319. return;
  320. }
  321. // Try to find tests that depend on the changed source files
  322. const testsBySource = dirtySources.map(path => {
  323. return this.testDependencies.filter(dep => dep.contains(path)).map(dep => {
  324. debug('%s is a dependency of %s', path, dep.file);
  325. return dep.file;
  326. });
  327. }, this).filter(tests => tests.length > 0);
  328. // Rerun all tests if source files were changed that could not be traced to
  329. // specific tests
  330. if (testsBySource.length !== dirtySources.length) {
  331. debug('Sources remain that cannot be traced to specific tests: %O', dirtySources);
  332. debug('Rerunning all tests');
  333. this.run();
  334. return;
  335. }
  336. // Run all affected tests
  337. this.run(union(addedOrChangedTests, uniq(flatten(testsBySource))));
  338. }
  339. }
  340. module.exports = Watcher;