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