index.js 28 KB

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