You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

973 lines
28 KiB

2 years ago
  1. 'use strict';
  2. const { EventEmitter } = require('events');
  3. const fs = require('fs');
  4. const sysPath = require('path');
  5. const { promisify } = require('util');
  6. const readdirp = require('readdirp');
  7. const anymatch = require('anymatch').default;
  8. const globParent = require('glob-parent');
  9. const isGlob = require('is-glob');
  10. const braces = require('braces');
  11. const normalizePath = require('normalize-path');
  12. const NodeFsHandler = require('./lib/nodefs-handler');
  13. const FsEventsHandler = require('./lib/fsevents-handler');
  14. const {
  15. EV_ALL,
  16. EV_READY,
  17. EV_ADD,
  18. EV_CHANGE,
  19. EV_UNLINK,
  20. EV_ADD_DIR,
  21. EV_UNLINK_DIR,
  22. EV_RAW,
  23. EV_ERROR,
  24. STR_CLOSE,
  25. STR_END,
  26. BACK_SLASH_RE,
  27. DOUBLE_SLASH_RE,
  28. SLASH_OR_BACK_SLASH_RE,
  29. DOT_RE,
  30. REPLACER_RE,
  31. SLASH,
  32. SLASH_SLASH,
  33. BRACE_START,
  34. BANG,
  35. ONE_DOT,
  36. TWO_DOTS,
  37. GLOBSTAR,
  38. SLASH_GLOBSTAR,
  39. ANYMATCH_OPTS,
  40. STRING_TYPE,
  41. FUNCTION_TYPE,
  42. EMPTY_STR,
  43. EMPTY_FN,
  44. isWindows,
  45. isMacos,
  46. isIBMi
  47. } = require('./lib/constants');
  48. const stat = promisify(fs.stat);
  49. const readdir = promisify(fs.readdir);
  50. /**
  51. * @typedef {String} Path
  52. * @typedef {'all'|'add'|'addDir'|'change'|'unlink'|'unlinkDir'|'raw'|'error'|'ready'} EventName
  53. * @typedef {'readdir'|'watch'|'add'|'remove'|'change'} ThrottleType
  54. */
  55. /**
  56. *
  57. * @typedef {Object} WatchHelpers
  58. * @property {Boolean} followSymlinks
  59. * @property {'stat'|'lstat'} statMethod
  60. * @property {Path} path
  61. * @property {Path} watchPath
  62. * @property {Function} entryPath
  63. * @property {Boolean} hasGlob
  64. * @property {Object} globFilter
  65. * @property {Function} filterPath
  66. * @property {Function} filterDir
  67. */
  68. const arrify = (value = []) => Array.isArray(value) ? value : [value];
  69. const flatten = (list, result = []) => {
  70. list.forEach(item => {
  71. if (Array.isArray(item)) {
  72. flatten(item, result);
  73. } else {
  74. result.push(item);
  75. }
  76. });
  77. return result;
  78. };
  79. const unifyPaths = (paths_) => {
  80. /**
  81. * @type {Array<String>}
  82. */
  83. const paths = flatten(arrify(paths_));
  84. if (!paths.every(p => typeof p === STRING_TYPE)) {
  85. throw new TypeError(`Non-string provided as watch path: ${paths}`);
  86. }
  87. return paths.map(normalizePathToUnix);
  88. };
  89. // If SLASH_SLASH occurs at the beginning of path, it is not replaced
  90. // because "//StoragePC/DrivePool/Movies" is a valid network path
  91. const toUnix = (string) => {
  92. let str = string.replace(BACK_SLASH_RE, SLASH);
  93. let prepend = false;
  94. if (str.startsWith(SLASH_SLASH)) {
  95. prepend = true;
  96. }
  97. while (str.match(DOUBLE_SLASH_RE)) {
  98. str = str.replace(DOUBLE_SLASH_RE, SLASH);
  99. }
  100. if (prepend) {
  101. str = SLASH + str;
  102. }
  103. return str;
  104. };
  105. // Our version of upath.normalize
  106. // TODO: this is not equal to path-normalize module - investigate why
  107. const normalizePathToUnix = (path) => toUnix(sysPath.normalize(toUnix(path)));
  108. const normalizeIgnored = (cwd = EMPTY_STR) => (path) => {
  109. if (typeof path !== STRING_TYPE) return path;
  110. return normalizePathToUnix(sysPath.isAbsolute(path) ? path : sysPath.join(cwd, path));
  111. };
  112. const getAbsolutePath = (path, cwd) => {
  113. if (sysPath.isAbsolute(path)) {
  114. return path;
  115. }
  116. if (path.startsWith(BANG)) {
  117. return BANG + sysPath.join(cwd, path.slice(1));
  118. }
  119. return sysPath.join(cwd, path);
  120. };
  121. const undef = (opts, key) => opts[key] === undefined;
  122. /**
  123. * Directory entry.
  124. * @property {Path} path
  125. * @property {Set<Path>} items
  126. */
  127. class DirEntry {
  128. /**
  129. * @param {Path} dir
  130. * @param {Function} removeWatcher
  131. */
  132. constructor(dir, removeWatcher) {
  133. this.path = dir;
  134. this._removeWatcher = removeWatcher;
  135. /** @type {Set<Path>} */
  136. this.items = new Set();
  137. }
  138. add(item) {
  139. const {items} = this;
  140. if (!items) return;
  141. if (item !== ONE_DOT && item !== TWO_DOTS) items.add(item);
  142. }
  143. async remove(item) {
  144. const {items} = this;
  145. if (!items) return;
  146. items.delete(item);
  147. if (items.size > 0) return;
  148. const dir = this.path;
  149. try {
  150. await readdir(dir);
  151. } catch (err) {
  152. if (this._removeWatcher) {
  153. this._removeWatcher(sysPath.dirname(dir), sysPath.basename(dir));
  154. }
  155. }
  156. }
  157. has(item) {
  158. const {items} = this;
  159. if (!items) return;
  160. return items.has(item);
  161. }
  162. /**
  163. * @returns {Array<String>}
  164. */
  165. getChildren() {
  166. const {items} = this;
  167. if (!items) return;
  168. return [...items.values()];
  169. }
  170. dispose() {
  171. this.items.clear();
  172. delete this.path;
  173. delete this._removeWatcher;
  174. delete this.items;
  175. Object.freeze(this);
  176. }
  177. }
  178. const STAT_METHOD_F = 'stat';
  179. const STAT_METHOD_L = 'lstat';
  180. class WatchHelper {
  181. constructor(path, watchPath, follow, fsw) {
  182. this.fsw = fsw;
  183. this.path = path = path.replace(REPLACER_RE, EMPTY_STR);
  184. this.watchPath = watchPath;
  185. this.fullWatchPath = sysPath.resolve(watchPath);
  186. this.hasGlob = watchPath !== path;
  187. /** @type {object|boolean} */
  188. if (path === EMPTY_STR) this.hasGlob = false;
  189. this.globSymlink = this.hasGlob && follow ? undefined : false;
  190. this.globFilter = this.hasGlob ? anymatch(path, undefined, ANYMATCH_OPTS) : false;
  191. this.dirParts = this.getDirParts(path);
  192. this.dirParts.forEach((parts) => {
  193. if (parts.length > 1) parts.pop();
  194. });
  195. this.followSymlinks = follow;
  196. this.statMethod = follow ? STAT_METHOD_F : STAT_METHOD_L;
  197. }
  198. checkGlobSymlink(entry) {
  199. // only need to resolve once
  200. // first entry should always have entry.parentDir === EMPTY_STR
  201. if (this.globSymlink === undefined) {
  202. this.globSymlink = entry.fullParentDir === this.fullWatchPath ?
  203. false : {realPath: entry.fullParentDir, linkPath: this.fullWatchPath};
  204. }
  205. if (this.globSymlink) {
  206. return entry.fullPath.replace(this.globSymlink.realPath, this.globSymlink.linkPath);
  207. }
  208. return entry.fullPath;
  209. }
  210. entryPath(entry) {
  211. return sysPath.join(this.watchPath,
  212. sysPath.relative(this.watchPath, this.checkGlobSymlink(entry))
  213. );
  214. }
  215. filterPath(entry) {
  216. const {stats} = entry;
  217. if (stats && stats.isSymbolicLink()) return this.filterDir(entry);
  218. const resolvedPath = this.entryPath(entry);
  219. const matchesGlob = this.hasGlob && typeof this.globFilter === FUNCTION_TYPE ?
  220. this.globFilter(resolvedPath) : true;
  221. return matchesGlob &&
  222. this.fsw._isntIgnored(resolvedPath, stats) &&
  223. this.fsw._hasReadPermissions(stats);
  224. }
  225. getDirParts(path) {
  226. if (!this.hasGlob) return [];
  227. const parts = [];
  228. const expandedPath = path.includes(BRACE_START) ? braces.expand(path) : [path];
  229. expandedPath.forEach((path) => {
  230. parts.push(sysPath.relative(this.watchPath, path).split(SLASH_OR_BACK_SLASH_RE));
  231. });
  232. return parts;
  233. }
  234. filterDir(entry) {
  235. if (this.hasGlob) {
  236. const entryParts = this.getDirParts(this.checkGlobSymlink(entry));
  237. let globstar = false;
  238. this.unmatchedGlob = !this.dirParts.some((parts) => {
  239. return parts.every((part, i) => {
  240. if (part === GLOBSTAR) globstar = true;
  241. return globstar || !entryParts[0][i] || anymatch(part, entryParts[0][i], ANYMATCH_OPTS);
  242. });
  243. });
  244. }
  245. return !this.unmatchedGlob && this.fsw._isntIgnored(this.entryPath(entry), entry.stats);
  246. }
  247. }
  248. /**
  249. * Watches files & directories for changes. Emitted events:
  250. * `add`, `addDir`, `change`, `unlink`, `unlinkDir`, `all`, `error`
  251. *
  252. * new FSWatcher()
  253. * .add(directories)
  254. * .on('add', path => log('File', path, 'was added'))
  255. */
  256. class FSWatcher extends EventEmitter {
  257. // Not indenting methods for history sake; for now.
  258. constructor(_opts) {
  259. super();
  260. const opts = {};
  261. if (_opts) Object.assign(opts, _opts); // for frozen objects
  262. /** @type {Map<String, DirEntry>} */
  263. this._watched = new Map();
  264. /** @type {Map<String, Array>} */
  265. this._closers = new Map();
  266. /** @type {Set<String>} */
  267. this._ignoredPaths = new Set();
  268. /** @type {Map<ThrottleType, Map>} */
  269. this._throttled = new Map();
  270. /** @type {Map<Path, String|Boolean>} */
  271. this._symlinkPaths = new Map();
  272. this._streams = new Set();
  273. this.closed = false;
  274. // Set up default options.
  275. if (undef(opts, 'persistent')) opts.persistent = true;
  276. if (undef(opts, 'ignoreInitial')) opts.ignoreInitial = false;
  277. if (undef(opts, 'ignorePermissionErrors')) opts.ignorePermissionErrors = false;
  278. if (undef(opts, 'interval')) opts.interval = 100;
  279. if (undef(opts, 'binaryInterval')) opts.binaryInterval = 300;
  280. if (undef(opts, 'disableGlobbing')) opts.disableGlobbing = false;
  281. opts.enableBinaryInterval = opts.binaryInterval !== opts.interval;
  282. // Enable fsevents on OS X when polling isn't explicitly enabled.
  283. if (undef(opts, 'useFsEvents')) opts.useFsEvents = !opts.usePolling;
  284. // If we can't use fsevents, ensure the options reflect it's disabled.
  285. const canUseFsEvents = FsEventsHandler.canUse();
  286. if (!canUseFsEvents) opts.useFsEvents = false;
  287. // Use polling on Mac if not using fsevents.
  288. // Other platforms use non-polling fs_watch.
  289. if (undef(opts, 'usePolling') && !opts.useFsEvents) {
  290. opts.usePolling = isMacos;
  291. }
  292. // Always default to polling on IBM i because fs.watch() is not available on IBM i.
  293. if(isIBMi) {
  294. opts.usePolling = true;
  295. }
  296. // Global override (useful for end-developers that need to force polling for all
  297. // instances of chokidar, regardless of usage/dependency depth)
  298. const envPoll = process.env.CHOKIDAR_USEPOLLING;
  299. if (envPoll !== undefined) {
  300. const envLower = envPoll.toLowerCase();
  301. if (envLower === 'false' || envLower === '0') {
  302. opts.usePolling = false;
  303. } else if (envLower === 'true' || envLower === '1') {
  304. opts.usePolling = true;
  305. } else {
  306. opts.usePolling = !!envLower;
  307. }
  308. }
  309. const envInterval = process.env.CHOKIDAR_INTERVAL;
  310. if (envInterval) {
  311. opts.interval = Number.parseInt(envInterval, 10);
  312. }
  313. // Editor atomic write normalization enabled by default with fs.watch
  314. if (undef(opts, 'atomic')) opts.atomic = !opts.usePolling && !opts.useFsEvents;
  315. if (opts.atomic) this._pendingUnlinks = new Map();
  316. if (undef(opts, 'followSymlinks')) opts.followSymlinks = true;
  317. if (undef(opts, 'awaitWriteFinish')) opts.awaitWriteFinish = false;
  318. if (opts.awaitWriteFinish === true) opts.awaitWriteFinish = {};
  319. const awf = opts.awaitWriteFinish;
  320. if (awf) {
  321. if (!awf.stabilityThreshold) awf.stabilityThreshold = 2000;
  322. if (!awf.pollInterval) awf.pollInterval = 100;
  323. this._pendingWrites = new Map();
  324. }
  325. if (opts.ignored) opts.ignored = arrify(opts.ignored);
  326. let readyCalls = 0;
  327. this._emitReady = () => {
  328. readyCalls++;
  329. if (readyCalls >= this._readyCount) {
  330. this._emitReady = EMPTY_FN;
  331. this._readyEmitted = true;
  332. // use process.nextTick to allow time for listener to be bound
  333. process.nextTick(() => this.emit(EV_READY));
  334. }
  335. };
  336. this._emitRaw = (...args) => this.emit(EV_RAW, ...args);
  337. this._readyEmitted = false;
  338. this.options = opts;
  339. // Initialize with proper watcher.
  340. if (opts.useFsEvents) {
  341. this._fsEventsHandler = new FsEventsHandler(this);
  342. } else {
  343. this._nodeFsHandler = new NodeFsHandler(this);
  344. }
  345. // You’re frozen when your heart’s not open.
  346. Object.freeze(opts);
  347. }
  348. // Public methods
  349. /**
  350. * Adds paths to be watched on an existing FSWatcher instance
  351. * @param {Path|Array<Path>} paths_
  352. * @param {String=} _origAdd private; for handling non-existent paths to be watched
  353. * @param {Boolean=} _internal private; indicates a non-user add
  354. * @returns {FSWatcher} for chaining
  355. */
  356. add(paths_, _origAdd, _internal) {
  357. const {cwd, disableGlobbing} = this.options;
  358. this.closed = false;
  359. let paths = unifyPaths(paths_);
  360. if (cwd) {
  361. paths = paths.map((path) => {
  362. const absPath = getAbsolutePath(path, cwd);
  363. // Check `path` instead of `absPath` because the cwd portion can't be a glob
  364. if (disableGlobbing || !isGlob(path)) {
  365. return absPath;
  366. }
  367. return normalizePath(absPath);
  368. });
  369. }
  370. // set aside negated glob strings
  371. paths = paths.filter((path) => {
  372. if (path.startsWith(BANG)) {
  373. this._ignoredPaths.add(path.slice(1));
  374. return false;
  375. }
  376. // if a path is being added that was previously ignored, stop ignoring it
  377. this._ignoredPaths.delete(path);
  378. this._ignoredPaths.delete(path + SLASH_GLOBSTAR);
  379. // reset the cached userIgnored anymatch fn
  380. // to make ignoredPaths changes effective
  381. this._userIgnored = undefined;
  382. return true;
  383. });
  384. if (this.options.useFsEvents && this._fsEventsHandler) {
  385. if (!this._readyCount) this._readyCount = paths.length;
  386. if (this.options.persistent) this._readyCount *= 2;
  387. paths.forEach((path) => this._fsEventsHandler._addToFsEvents(path));
  388. } else {
  389. if (!this._readyCount) this._readyCount = 0;
  390. this._readyCount += paths.length;
  391. Promise.all(
  392. paths.map(async path => {
  393. const res = await this._nodeFsHandler._addToNodeFs(path, !_internal, 0, 0, _origAdd);
  394. if (res) this._emitReady();
  395. return res;
  396. })
  397. ).then(results => {
  398. if (this.closed) return;
  399. results.filter(item => item).forEach(item => {
  400. this.add(sysPath.dirname(item), sysPath.basename(_origAdd || item));
  401. });
  402. });
  403. }
  404. return this;
  405. }
  406. /**
  407. * Close watchers or start ignoring events from specified paths.
  408. * @param {Path|Array<Path>} paths_ - string or array of strings, file/directory paths and/or globs
  409. * @returns {FSWatcher} for chaining
  410. */
  411. unwatch(paths_) {
  412. if (this.closed) return this;
  413. const paths = unifyPaths(paths_);
  414. const {cwd} = this.options;
  415. paths.forEach((path) => {
  416. // convert to absolute path unless relative path already matches
  417. if (!sysPath.isAbsolute(path) && !this._closers.has(path)) {
  418. if (cwd) path = sysPath.join(cwd, path);
  419. path = sysPath.resolve(path);
  420. }
  421. this._closePath(path);
  422. this._ignoredPaths.add(path);
  423. if (this._watched.has(path)) {
  424. this._ignoredPaths.add(path + SLASH_GLOBSTAR);
  425. }
  426. // reset the cached userIgnored anymatch fn
  427. // to make ignoredPaths changes effective
  428. this._userIgnored = undefined;
  429. });
  430. return this;
  431. }
  432. /**
  433. * Close watchers and remove all listeners from watched paths.
  434. * @returns {Promise<void>}.
  435. */
  436. close() {
  437. if (this.closed) return this._closePromise;
  438. this.closed = true;
  439. // Memory management.
  440. this.removeAllListeners();
  441. const closers = [];
  442. this._closers.forEach(closerList => closerList.forEach(closer => {
  443. const promise = closer();
  444. if (promise instanceof Promise) closers.push(promise);
  445. }));
  446. this._streams.forEach(stream => stream.destroy());
  447. this._userIgnored = undefined;
  448. this._readyCount = 0;
  449. this._readyEmitted = false;
  450. this._watched.forEach(dirent => dirent.dispose());
  451. ['closers', 'watched', 'streams', 'symlinkPaths', 'throttled'].forEach(key => {
  452. this[`_${key}`].clear();
  453. });
  454. this._closePromise = closers.length ? Promise.all(closers).then(() => undefined) : Promise.resolve();
  455. return this._closePromise;
  456. }
  457. /**
  458. * Expose list of watched paths
  459. * @returns {Object} for chaining
  460. */
  461. getWatched() {
  462. const watchList = {};
  463. this._watched.forEach((entry, dir) => {
  464. const key = this.options.cwd ? sysPath.relative(this.options.cwd, dir) : dir;
  465. watchList[key || ONE_DOT] = entry.getChildren().sort();
  466. });
  467. return watchList;
  468. }
  469. emitWithAll(event, args) {
  470. this.emit(...args);
  471. if (event !== EV_ERROR) this.emit(EV_ALL, ...args);
  472. }
  473. // Common helpers
  474. // --------------
  475. /**
  476. * Normalize and emit events.
  477. * Calling _emit DOES NOT MEAN emit() would be called!
  478. * @param {EventName} event Type of event
  479. * @param {Path} path File or directory path
  480. * @param {*=} val1 arguments to be passed with event
  481. * @param {*=} val2
  482. * @param {*=} val3
  483. * @returns the error if defined, otherwise the value of the FSWatcher instance's `closed` flag
  484. */
  485. async _emit(event, path, val1, val2, val3) {
  486. if (this.closed) return;
  487. const opts = this.options;
  488. if (isWindows) path = sysPath.normalize(path);
  489. if (opts.cwd) path = sysPath.relative(opts.cwd, path);
  490. /** @type Array<any> */
  491. const args = [event, path];
  492. if (val3 !== undefined) args.push(val1, val2, val3);
  493. else if (val2 !== undefined) args.push(val1, val2);
  494. else if (val1 !== undefined) args.push(val1);
  495. const awf = opts.awaitWriteFinish;
  496. let pw;
  497. if (awf && (pw = this._pendingWrites.get(path))) {
  498. pw.lastChange = new Date();
  499. return this;
  500. }
  501. if (opts.atomic) {
  502. if (event === EV_UNLINK) {
  503. this._pendingUnlinks.set(path, args);
  504. setTimeout(() => {
  505. this._pendingUnlinks.forEach((entry, path) => {
  506. this.emit(...entry);
  507. this.emit(EV_ALL, ...entry);
  508. this._pendingUnlinks.delete(path);
  509. });
  510. }, typeof opts.atomic === 'number' ? opts.atomic : 100);
  511. return this;
  512. }
  513. if (event === EV_ADD && this._pendingUnlinks.has(path)) {
  514. event = args[0] = EV_CHANGE;
  515. this._pendingUnlinks.delete(path);
  516. }
  517. }
  518. if (awf && (event === EV_ADD || event === EV_CHANGE) && this._readyEmitted) {
  519. const awfEmit = (err, stats) => {
  520. if (err) {
  521. event = args[0] = EV_ERROR;
  522. args[1] = err;
  523. this.emitWithAll(event, args);
  524. } else if (stats) {
  525. // if stats doesn't exist the file must have been deleted
  526. if (args.length > 2) {
  527. args[2] = stats;
  528. } else {
  529. args.push(stats);
  530. }
  531. this.emitWithAll(event, args);
  532. }
  533. };
  534. this._awaitWriteFinish(path, awf.stabilityThreshold, event, awfEmit);
  535. return this;
  536. }
  537. if (event === EV_CHANGE) {
  538. const isThrottled = !this._throttle(EV_CHANGE, path, 50);
  539. if (isThrottled) return this;
  540. }
  541. if (opts.alwaysStat && val1 === undefined &&
  542. (event === EV_ADD || event === EV_ADD_DIR || event === EV_CHANGE)
  543. ) {
  544. const fullPath = opts.cwd ? sysPath.join(opts.cwd, path) : path;
  545. let stats;
  546. try {
  547. stats = await stat(fullPath);
  548. } catch (err) {}
  549. // Suppress event when fs_stat fails, to avoid sending undefined 'stat'
  550. if (!stats || this.closed) return;
  551. args.push(stats);
  552. }
  553. this.emitWithAll(event, args);
  554. return this;
  555. }
  556. /**
  557. * Common handler for errors
  558. * @param {Error} error
  559. * @returns {Error|Boolean} The error if defined, otherwise the value of the FSWatcher instance's `closed` flag
  560. */
  561. _handleError(error) {
  562. const code = error && error.code;
  563. if (error && code !== 'ENOENT' && code !== 'ENOTDIR' &&
  564. (!this.options.ignorePermissionErrors || (code !== 'EPERM' && code !== 'EACCES'))
  565. ) {
  566. this.emit(EV_ERROR, error);
  567. }
  568. return error || this.closed;
  569. }
  570. /**
  571. * Helper utility for throttling
  572. * @param {ThrottleType} actionType type being throttled
  573. * @param {Path} path being acted upon
  574. * @param {Number} timeout duration of time to suppress duplicate actions
  575. * @returns {Object|false} tracking object or false if action should be suppressed
  576. */
  577. _throttle(actionType, path, timeout) {
  578. if (!this._throttled.has(actionType)) {
  579. this._throttled.set(actionType, new Map());
  580. }
  581. /** @type {Map<Path, Object>} */
  582. const action = this._throttled.get(actionType);
  583. /** @type {Object} */
  584. const actionPath = action.get(path);
  585. if (actionPath) {
  586. actionPath.count++;
  587. return false;
  588. }
  589. let timeoutObject;
  590. const clear = () => {
  591. const item = action.get(path);
  592. const count = item ? item.count : 0;
  593. action.delete(path);
  594. clearTimeout(timeoutObject);
  595. if (item) clearTimeout(item.timeoutObject);
  596. return count;
  597. };
  598. timeoutObject = setTimeout(clear, timeout);
  599. const thr = {timeoutObject, clear, count: 0};
  600. action.set(path, thr);
  601. return thr;
  602. }
  603. _incrReadyCount() {
  604. return this._readyCount++;
  605. }
  606. /**
  607. * Awaits write operation to finish.
  608. * Polls a newly created file for size variations. When files size does not change for 'threshold' milliseconds calls callback.
  609. * @param {Path} path being acted upon
  610. * @param {Number} threshold Time in milliseconds a file size must be fixed before acknowledging write OP is finished
  611. * @param {EventName} event
  612. * @param {Function} awfEmit Callback to be called when ready for event to be emitted.
  613. */
  614. _awaitWriteFinish(path, threshold, event, awfEmit) {
  615. let timeoutHandler;
  616. let fullPath = path;
  617. if (this.options.cwd && !sysPath.isAbsolute(path)) {
  618. fullPath = sysPath.join(this.options.cwd, path);
  619. }
  620. const now = new Date();
  621. const awaitWriteFinish = (prevStat) => {
  622. fs.stat(fullPath, (err, curStat) => {
  623. if (err || !this._pendingWrites.has(path)) {
  624. if (err && err.code !== 'ENOENT') awfEmit(err);
  625. return;
  626. }
  627. const now = Number(new Date());
  628. if (prevStat && curStat.size !== prevStat.size) {
  629. this._pendingWrites.get(path).lastChange = now;
  630. }
  631. const pw = this._pendingWrites.get(path);
  632. const df = now - pw.lastChange;
  633. if (df >= threshold) {
  634. this._pendingWrites.delete(path);
  635. awfEmit(undefined, curStat);
  636. } else {
  637. timeoutHandler = setTimeout(
  638. awaitWriteFinish,
  639. this.options.awaitWriteFinish.pollInterval,
  640. curStat
  641. );
  642. }
  643. });
  644. };
  645. if (!this._pendingWrites.has(path)) {
  646. this._pendingWrites.set(path, {
  647. lastChange: now,
  648. cancelWait: () => {
  649. this._pendingWrites.delete(path);
  650. clearTimeout(timeoutHandler);
  651. return event;
  652. }
  653. });
  654. timeoutHandler = setTimeout(
  655. awaitWriteFinish,
  656. this.options.awaitWriteFinish.pollInterval
  657. );
  658. }
  659. }
  660. _getGlobIgnored() {
  661. return [...this._ignoredPaths.values()];
  662. }
  663. /**
  664. * Determines whether user has asked to ignore this path.
  665. * @param {Path} path filepath or dir
  666. * @param {fs.Stats=} stats result of fs.stat
  667. * @returns {Boolean}
  668. */
  669. _isIgnored(path, stats) {
  670. if (this.options.atomic && DOT_RE.test(path)) return true;
  671. if (!this._userIgnored) {
  672. const {cwd} = this.options;
  673. const ign = this.options.ignored;
  674. const ignored = ign && ign.map(normalizeIgnored(cwd));
  675. const paths = arrify(ignored)
  676. .filter((path) => typeof path === STRING_TYPE && !isGlob(path))
  677. .map((path) => path + SLASH_GLOBSTAR);
  678. const list = this._getGlobIgnored().map(normalizeIgnored(cwd)).concat(ignored, paths);
  679. this._userIgnored = anymatch(list, undefined, ANYMATCH_OPTS);
  680. }
  681. return this._userIgnored([path, stats]);
  682. }
  683. _isntIgnored(path, stat) {
  684. return !this._isIgnored(path, stat);
  685. }
  686. /**
  687. * Provides a set of common helpers and properties relating to symlink and glob handling.
  688. * @param {Path} path file, directory, or glob pattern being watched
  689. * @param {Number=} depth at any depth > 0, this isn't a glob
  690. * @returns {WatchHelper} object containing helpers for this path
  691. */
  692. _getWatchHelpers(path, depth) {
  693. const watchPath = depth || this.options.disableGlobbing || !isGlob(path) ? path : globParent(path);
  694. const follow = this.options.followSymlinks;
  695. return new WatchHelper(path, watchPath, follow, this);
  696. }
  697. // Directory helpers
  698. // -----------------
  699. /**
  700. * Provides directory tracking objects
  701. * @param {String} directory path of the directory
  702. * @returns {DirEntry} the directory's tracking object
  703. */
  704. _getWatchedDir(directory) {
  705. if (!this._boundRemove) this._boundRemove = this._remove.bind(this);
  706. const dir = sysPath.resolve(directory);
  707. if (!this._watched.has(dir)) this._watched.set(dir, new DirEntry(dir, this._boundRemove));
  708. return this._watched.get(dir);
  709. }
  710. // File helpers
  711. // ------------
  712. /**
  713. * Check for read permissions.
  714. * Based on this answer on SO: https://stackoverflow.com/a/11781404/1358405
  715. * @param {fs.Stats} stats - object, result of fs_stat
  716. * @returns {Boolean} indicates whether the file can be read
  717. */
  718. _hasReadPermissions(stats) {
  719. if (this.options.ignorePermissionErrors) return true;
  720. // stats.mode may be bigint
  721. const md = stats && Number.parseInt(stats.mode, 10);
  722. const st = md & 0o777;
  723. const it = Number.parseInt(st.toString(8)[0], 10);
  724. return Boolean(4 & it);
  725. }
  726. /**
  727. * Handles emitting unlink events for
  728. * files and directories, and via recursion, for
  729. * files and directories within directories that are unlinked
  730. * @param {String} directory within which the following item is located
  731. * @param {String} item base path of item/directory
  732. * @returns {void}
  733. */
  734. _remove(directory, item, isDirectory) {
  735. // if what is being deleted is a directory, get that directory's paths
  736. // for recursive deleting and cleaning of watched object
  737. // if it is not a directory, nestedDirectoryChildren will be empty array
  738. const path = sysPath.join(directory, item);
  739. const fullPath = sysPath.resolve(path);
  740. isDirectory = isDirectory != null
  741. ? isDirectory
  742. : this._watched.has(path) || this._watched.has(fullPath);
  743. // prevent duplicate handling in case of arriving here nearly simultaneously
  744. // via multiple paths (such as _handleFile and _handleDir)
  745. if (!this._throttle('remove', path, 100)) return;
  746. // if the only watched file is removed, watch for its return
  747. if (!isDirectory && !this.options.useFsEvents && this._watched.size === 1) {
  748. this.add(directory, item, true);
  749. }
  750. // This will create a new entry in the watched object in either case
  751. // so we got to do the directory check beforehand
  752. const wp = this._getWatchedDir(path);
  753. const nestedDirectoryChildren = wp.getChildren();
  754. // Recursively remove children directories / files.
  755. nestedDirectoryChildren.forEach(nested => this._remove(path, nested));
  756. // Check if item was on the watched list and remove it
  757. const parent = this._getWatchedDir(directory);
  758. const wasTracked = parent.has(item);
  759. parent.remove(item);
  760. // Fixes issue #1042 -> Relative paths were detected and added as symlinks
  761. // (https://github.com/paulmillr/chokidar/blob/e1753ddbc9571bdc33b4a4af172d52cb6e611c10/lib/nodefs-handler.js#L612),
  762. // but never removed from the map in case the path was deleted.
  763. // This leads to an incorrect state if the path was recreated:
  764. // https://github.com/paulmillr/chokidar/blob/e1753ddbc9571bdc33b4a4af172d52cb6e611c10/lib/nodefs-handler.js#L553
  765. if (this._symlinkPaths.has(fullPath)) {
  766. this._symlinkPaths.delete(fullPath);
  767. }
  768. // If we wait for this file to be fully written, cancel the wait.
  769. let relPath = path;
  770. if (this.options.cwd) relPath = sysPath.relative(this.options.cwd, path);
  771. if (this.options.awaitWriteFinish && this._pendingWrites.has(relPath)) {
  772. const event = this._pendingWrites.get(relPath).cancelWait();
  773. if (event === EV_ADD) return;
  774. }
  775. // The Entry will either be a directory that just got removed
  776. // or a bogus entry to a file, in either case we have to remove it
  777. this._watched.delete(path);
  778. this._watched.delete(fullPath);
  779. const eventName = isDirectory ? EV_UNLINK_DIR : EV_UNLINK;
  780. if (wasTracked && !this._isIgnored(path)) this._emit(eventName, path);
  781. // Avoid conflicts if we later create another file with the same name
  782. if (!this.options.useFsEvents) {
  783. this._closePath(path);
  784. }
  785. }
  786. /**
  787. * Closes all watchers for a path
  788. * @param {Path} path
  789. */
  790. _closePath(path) {
  791. this._closeFile(path)
  792. const dir = sysPath.dirname(path);
  793. this._getWatchedDir(dir).remove(sysPath.basename(path));
  794. }
  795. /**
  796. * Closes only file-specific watchers
  797. * @param {Path} path
  798. */
  799. _closeFile(path) {
  800. const closers = this._closers.get(path);
  801. if (!closers) return;
  802. closers.forEach(closer => closer());
  803. this._closers.delete(path);
  804. }
  805. /**
  806. *
  807. * @param {Path} path
  808. * @param {Function} closer
  809. */
  810. _addPathCloser(path, closer) {
  811. if (!closer) return;
  812. let list = this._closers.get(path);
  813. if (!list) {
  814. list = [];
  815. this._closers.set(path, list);
  816. }
  817. list.push(closer);
  818. }
  819. _readdirp(root, opts) {
  820. if (this.closed) return;
  821. const options = {type: EV_ALL, alwaysStat: true, lstat: true, ...opts};
  822. let stream = readdirp(root, options);
  823. this._streams.add(stream);
  824. stream.once(STR_CLOSE, () => {
  825. stream = undefined;
  826. });
  827. stream.once(STR_END, () => {
  828. if (stream) {
  829. this._streams.delete(stream);
  830. stream = undefined;
  831. }
  832. });
  833. return stream;
  834. }
  835. }
  836. // Export FSWatcher class
  837. exports.FSWatcher = FSWatcher;
  838. /**
  839. * Instantiates watcher with paths to be tracked.
  840. * @param {String|Array<String>} paths file/directory paths and/or globs
  841. * @param {Object=} options chokidar opts
  842. * @returns an instance of FSWatcher for chaining.
  843. */
  844. const watch = (paths, options) => {
  845. const watcher = new FSWatcher(options);
  846. watcher.add(paths);
  847. return watcher;
  848. };
  849. exports.watch = watch;