Ei kuvausta

watching.js 8.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. Object.defineProperty(exports, "createWatcher", {
  6. enumerable: true,
  7. get: function() {
  8. return createWatcher;
  9. }
  10. });
  11. const _chokidar = /*#__PURE__*/ _interop_require_default(require("chokidar"));
  12. const _fs = /*#__PURE__*/ _interop_require_default(require("fs"));
  13. const _micromatch = /*#__PURE__*/ _interop_require_default(require("micromatch"));
  14. const _normalizepath = /*#__PURE__*/ _interop_require_default(require("normalize-path"));
  15. const _path = /*#__PURE__*/ _interop_require_default(require("path"));
  16. const _utils = require("./utils");
  17. function _interop_require_default(obj) {
  18. return obj && obj.__esModule ? obj : {
  19. default: obj
  20. };
  21. }
  22. function createWatcher(args, { state , rebuild }) {
  23. let shouldPoll = args["--poll"];
  24. let shouldCoalesceWriteEvents = shouldPoll || process.platform === "win32";
  25. // Polling interval in milliseconds
  26. // Used only when polling or coalescing add/change events on Windows
  27. let pollInterval = 10;
  28. let watcher = _chokidar.default.watch([], {
  29. // Force checking for atomic writes in all situations
  30. // This causes chokidar to wait up to 100ms for a file to re-added after it's been unlinked
  31. // This only works when watching directories though
  32. atomic: true,
  33. usePolling: shouldPoll,
  34. interval: shouldPoll ? pollInterval : undefined,
  35. ignoreInitial: true,
  36. awaitWriteFinish: shouldCoalesceWriteEvents ? {
  37. stabilityThreshold: 50,
  38. pollInterval: pollInterval
  39. } : false
  40. });
  41. // A queue of rebuilds, file reads, etc… to run
  42. let chain = Promise.resolve();
  43. /**
  44. * A list of files that have been changed since the last rebuild
  45. *
  46. * @type {{file: string, content: () => Promise<string>, extension: string}[]}
  47. */ let changedContent = [];
  48. /**
  49. * A list of files for which a rebuild has already been queued.
  50. * This is used to prevent duplicate rebuilds when multiple events are fired for the same file.
  51. * The rebuilt file is cleared from this list when it's associated rebuild has _started_
  52. * This is because if the file is changed during a rebuild it won't trigger a new rebuild which it should
  53. **/ let pendingRebuilds = new Set();
  54. let _timer;
  55. let _reject;
  56. /**
  57. * Rebuilds the changed files and resolves when the rebuild is
  58. * complete regardless of whether it was successful or not
  59. */ async function rebuildAndContinue() {
  60. let changes = changedContent.splice(0);
  61. // There are no changes to rebuild so we can just do nothing
  62. if (changes.length === 0) {
  63. return Promise.resolve();
  64. }
  65. // Clear all pending rebuilds for the about-to-be-built files
  66. changes.forEach((change)=>pendingRebuilds.delete(change.file));
  67. // Resolve the promise even when the rebuild fails
  68. return rebuild(changes).then(()=>{}, ()=>{});
  69. }
  70. /**
  71. *
  72. * @param {*} file
  73. * @param {(() => Promise<string>) | null} content
  74. * @param {boolean} skipPendingCheck
  75. * @returns {Promise<void>}
  76. */ function recordChangedFile(file, content = null, skipPendingCheck = false) {
  77. file = _path.default.resolve(file);
  78. // Applications like Vim/Neovim fire both rename and change events in succession for atomic writes
  79. // In that case rebuild has already been queued by rename, so can be skipped in change
  80. if (pendingRebuilds.has(file) && !skipPendingCheck) {
  81. return Promise.resolve();
  82. }
  83. // Mark that a rebuild of this file is going to happen
  84. // It MUST happen synchronously before the rebuild is queued for this to be effective
  85. pendingRebuilds.add(file);
  86. changedContent.push({
  87. file,
  88. content: content !== null && content !== void 0 ? content : ()=>_fs.default.promises.readFile(file, "utf8"),
  89. extension: _path.default.extname(file).slice(1)
  90. });
  91. if (_timer) {
  92. clearTimeout(_timer);
  93. _reject();
  94. }
  95. // If a rebuild is already in progress we don't want to start another one until the 10ms timer has expired
  96. chain = chain.then(()=>new Promise((resolve, reject)=>{
  97. _timer = setTimeout(resolve, 10);
  98. _reject = reject;
  99. }));
  100. // Resolves once this file has been rebuilt (or the rebuild for this file has failed)
  101. // This queues as many rebuilds as there are changed files
  102. // But those rebuilds happen after some delay
  103. // And will immediately resolve if there are no changes
  104. chain = chain.then(rebuildAndContinue, rebuildAndContinue);
  105. return chain;
  106. }
  107. watcher.on("change", (file)=>recordChangedFile(file));
  108. watcher.on("add", (file)=>recordChangedFile(file));
  109. // Restore watching any files that are "removed"
  110. // This can happen when a file is pseudo-atomically replaced (a copy is created, overwritten, the old one is unlinked, and the new one is renamed)
  111. // TODO: An an optimization we should allow removal when the config changes
  112. watcher.on("unlink", (file)=>{
  113. file = (0, _normalizepath.default)(file);
  114. // Only re-add the file if it's not covered by a dynamic pattern
  115. if (!_micromatch.default.some([
  116. file
  117. ], state.contentPatterns.dynamic)) {
  118. watcher.add(file);
  119. }
  120. });
  121. // Some applications such as Visual Studio (but not VS Code)
  122. // will only fire a rename event for atomic writes and not a change event
  123. // This is very likely a chokidar bug but it's one we need to work around
  124. // We treat this as a change event and rebuild the CSS
  125. watcher.on("raw", (evt, filePath, meta)=>{
  126. if (evt !== "rename") {
  127. return;
  128. }
  129. let watchedPath = meta.watchedPath;
  130. // Watched path might be the file itself
  131. // Or the directory it is in
  132. filePath = watchedPath.endsWith(filePath) ? watchedPath : _path.default.join(watchedPath, filePath);
  133. // Skip this event since the files it is for does not match any of the registered content globs
  134. if (!_micromatch.default.some([
  135. filePath
  136. ], state.contentPatterns.all)) {
  137. return;
  138. }
  139. // Skip since we've already queued a rebuild for this file that hasn't happened yet
  140. if (pendingRebuilds.has(filePath)) {
  141. return;
  142. }
  143. // We'll go ahead and add the file to the pending rebuilds list here
  144. // It'll be removed when the rebuild starts unless the read fails
  145. // which will be taken care of as well
  146. pendingRebuilds.add(filePath);
  147. async function enqueue() {
  148. try {
  149. // We need to read the file as early as possible outside of the chain
  150. // because it may be gone by the time we get to it. doing the read
  151. // immediately increases the chance that the file is still there
  152. let content = await (0, _utils.readFileWithRetries)(_path.default.resolve(filePath));
  153. if (content === undefined) {
  154. return;
  155. }
  156. // This will push the rebuild onto the chain
  157. // We MUST skip the rebuild check here otherwise the rebuild will never happen on Linux
  158. // This is because the order of events and timing is different on Linux
  159. // @ts-ignore: TypeScript isn't picking up that content is a string here
  160. await recordChangedFile(filePath, ()=>content, true);
  161. } catch {
  162. // If reading the file fails, it's was probably a deleted temporary file
  163. // So we can ignore it and no rebuild is needed
  164. }
  165. }
  166. enqueue().then(()=>{
  167. // If the file read fails we still need to make sure the file isn't stuck in the pending rebuilds list
  168. pendingRebuilds.delete(filePath);
  169. });
  170. });
  171. return {
  172. fswatcher: watcher,
  173. refreshWatchedFiles () {
  174. watcher.add(Array.from(state.contextDependencies));
  175. watcher.add(Array.from(state.configBag.dependencies));
  176. watcher.add(state.contentPatterns.all);
  177. }
  178. };
  179. }