1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
|
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as parcelWatcher from '@parcel/watcher';
import { existsSync, unlinkSync } from 'fs';
import { tmpdir } from 'os';
import { DeferredPromise, RunOnceScheduler, ThrottledWorker } from 'vs/base/common/async';
import { CancellationToken, CancellationTokenSource } from 'vs/base/common/cancellation';
import { toErrorMessage } from 'vs/base/common/errorMessage';
import { Emitter } from 'vs/base/common/event';
import { isEqualOrParent, randomPath } from 'vs/base/common/extpath';
import { parse, ParsedPattern } from 'vs/base/common/glob';
import { Disposable } from 'vs/base/common/lifecycle';
import { TernarySearchTree } from 'vs/base/common/map';
import { normalizeNFC } from 'vs/base/common/normalization';
import { dirname, isAbsolute, join, normalize, sep } from 'vs/base/common/path';
import { isLinux, isMacintosh, isWindows } from 'vs/base/common/platform';
import { rtrim } from 'vs/base/common/strings';
import { realcaseSync, realpathSync } from 'vs/base/node/extpath';
import { NodeJSFileWatcherLibrary } from 'vs/platform/files/node/watcher/nodejs/nodejsWatcherLib';
import { FileChangeType } from 'vs/platform/files/common/files';
import { IDiskFileChange, ILogMessage, coalesceEvents, IRecursiveWatchRequest, IRecursiveWatcher } from 'vs/platform/files/common/watcher';
import { equals } from 'vs/base/common/arrays';
export interface IParcelWatcherInstance {
/**
* Signals when the watcher is ready to watch.
*/
readonly ready: Promise<unknown>;
/**
* The watch request associated to the watcher.
*/
readonly request: IRecursiveWatchRequest;
/**
* How often this watcher has been restarted in case of an unexpected
* shutdown.
*/
readonly restarts: number;
/**
* The cancellation token associated with the lifecycle of the watcher.
*/
readonly token: CancellationToken;
/**
* Stops and disposes the watcher. This operation is async to await
* unsubscribe call in Parcel.
*/
stop(): Promise<void>;
}
export class ParcelWatcher extends Disposable implements IRecursiveWatcher {
private static readonly MAP_PARCEL_WATCHER_ACTION_TO_FILE_CHANGE = new Map<parcelWatcher.EventType, number>(
[
['create', FileChangeType.ADDED],
['update', FileChangeType.UPDATED],
['delete', FileChangeType.DELETED]
]
);
private static readonly GLOB_MARKERS = {
Star: '*',
GlobStar: '**',
GlobStarPosix: '**/**',
GlobStarWindows: '**\\**',
GlobStarPathStartPosix: '**/',
GlobStarPathEndPosix: '/**',
StarPathEndPosix: '/*',
GlobStarPathStartWindows: '**\\',
GlobStarPathEndWindows: '\\**'
};
private static readonly PARCEL_WATCHER_BACKEND = isWindows ? 'windows' : isLinux ? 'inotify' : 'fs-events';
private readonly _onDidChangeFile = this._register(new Emitter<IDiskFileChange[]>());
readonly onDidChangeFile = this._onDidChangeFile.event;
private readonly _onDidLogMessage = this._register(new Emitter<ILogMessage>());
readonly onDidLogMessage = this._onDidLogMessage.event;
private readonly _onDidError = this._register(new Emitter<string>());
readonly onDidError = this._onDidError.event;
protected readonly watchers = new Map<string, IParcelWatcherInstance>();
// Reduce likelyhood of spam from file events via throttling.
// (https://github.com/microsoft/vscode/issues/124723)
private readonly throttledFileChangesWorker = new ThrottledWorker<IDiskFileChange>(
{
maxWorkChunkSize: 500, // only process up to 500 changes at once before...
throttleDelay: 200, // ...resting for 200ms until we process events again...
maxBufferedWork: 30000 // ...but never buffering more than 30000 events in memory
},
events => this._onDidChangeFile.fire(events)
);
private verboseLogging = false;
private enospcErrorLogged = false;
constructor() {
super();
this.registerListeners();
}
private registerListeners(): void {
// Error handling on process
process.on('uncaughtException', error => this.onUnexpectedError(error));
process.on('unhandledRejection', error => this.onUnexpectedError(error));
}
async watch(requests: IRecursiveWatchRequest[]): Promise<void> {
// Figure out duplicates to remove from the requests
const normalizedRequests = this.normalizeRequests(requests);
// Gather paths that we should start watching
const requestsToStartWatching = normalizedRequests.filter(request => {
const watcher = this.watchers.get(request.path);
if (!watcher) {
return true; // not yet watching that path
}
// Re-watch path if excludes/includes have changed or polling interval
return !equals(watcher.request.excludes, request.excludes) || !equals(watcher.request.includes, request.includes) || watcher.request.pollingInterval !== request.pollingInterval;
});
// Gather paths that we should stop watching
const pathsToStopWatching = Array.from(this.watchers.values()).filter(({ request }) => {
return !normalizedRequests.find(normalizedRequest => {
return normalizedRequest.path === request.path &&
equals(normalizedRequest.excludes, request.excludes) &&
equals(normalizedRequest.includes, request.includes) &&
normalizedRequest.pollingInterval === request.pollingInterval;
});
}).map(({ request }) => request.path);
// Logging
if (requestsToStartWatching.length) {
this.trace(`Request to start watching: ${requestsToStartWatching.map(request => `${request.path} (excludes: ${request.excludes.length > 0 ? request.excludes : '<none>'}, includes: ${request.includes && request.includes.length > 0 ? request.includes : '<all>'})`).join(',')}`);
}
if (pathsToStopWatching.length) {
this.trace(`Request to stop watching: ${pathsToStopWatching.join(',')}`);
}
// Stop watching as instructed
for (const pathToStopWatching of pathsToStopWatching) {
await this.stopWatching(pathToStopWatching);
}
// Start watching as instructed
for (const request of requestsToStartWatching) {
if (request.pollingInterval) {
this.startPolling(request, request.pollingInterval);
} else {
this.startWatching(request);
}
}
}
protected toExcludePaths(path: string, excludes: string[] | undefined): string[] | undefined {
if (!Array.isArray(excludes)) {
return undefined;
}
const excludePaths = new Set<string>();
// Parcel watcher currently does not support glob patterns
// for native exclusions. As long as that is the case, try
// to convert exclude patterns into absolute paths that the
// watcher supports natively to reduce the overhead at the
// level of the file watcher as much as possible.
// Refs: https://github.com/parcel-bundler/watcher/issues/64
for (const exclude of excludes) {
const isGlob = exclude.includes(ParcelWatcher.GLOB_MARKERS.Star);
// Glob pattern: check for typical patterns and convert
let normalizedExclude: string | undefined = undefined;
if (isGlob) {
// Examples: **, **/**, **\**
if (
exclude === ParcelWatcher.GLOB_MARKERS.GlobStar ||
exclude === ParcelWatcher.GLOB_MARKERS.GlobStarPosix ||
exclude === ParcelWatcher.GLOB_MARKERS.GlobStarWindows
) {
normalizedExclude = path;
}
// Examples:
// - **/node_modules/**
// - **/.git/objects/**
// - **/build-folder
// - output/**
else {
const startsWithGlobStar = exclude.startsWith(ParcelWatcher.GLOB_MARKERS.GlobStarPathStartPosix) || exclude.startsWith(ParcelWatcher.GLOB_MARKERS.GlobStarPathStartWindows);
const endsWithGlobStar = exclude.endsWith(ParcelWatcher.GLOB_MARKERS.GlobStarPathEndPosix) || exclude.endsWith(ParcelWatcher.GLOB_MARKERS.GlobStarPathEndWindows);
if (startsWithGlobStar || endsWithGlobStar) {
if (startsWithGlobStar && endsWithGlobStar) {
normalizedExclude = exclude.substring(ParcelWatcher.GLOB_MARKERS.GlobStarPathStartPosix.length, exclude.length - ParcelWatcher.GLOB_MARKERS.GlobStarPathEndPosix.length);
} else if (startsWithGlobStar) {
normalizedExclude = exclude.substring(ParcelWatcher.GLOB_MARKERS.GlobStarPathStartPosix.length);
} else {
normalizedExclude = exclude.substring(0, exclude.length - ParcelWatcher.GLOB_MARKERS.GlobStarPathEndPosix.length);
}
}
// Support even more glob patterns on Linux where we know
// that each folder requires a file handle to watch.
// Examples:
// - node_modules/* (full form: **/node_modules/*/**)
if (isLinux && normalizedExclude) {
const endsWithStar = normalizedExclude?.endsWith(ParcelWatcher.GLOB_MARKERS.StarPathEndPosix);
if (endsWithStar) {
normalizedExclude = normalizedExclude.substring(0, normalizedExclude.length - ParcelWatcher.GLOB_MARKERS.StarPathEndPosix.length);
}
}
}
}
// Not a glob pattern, take as is
else {
normalizedExclude = exclude;
}
if (!normalizedExclude || normalizedExclude.includes(ParcelWatcher.GLOB_MARKERS.Star)) {
continue; // skip for parcel (will be applied later by our glob matching)
}
// Absolute path: normalize to watched path and
// exclude if not a parent of it otherwise.
if (isAbsolute(normalizedExclude)) {
if (!isEqualOrParent(normalizedExclude, path, !isLinux)) {
continue; // exclude points to path outside of watched folder, ignore
}
// convert to relative path to ensure we
// get the correct path casing going forward
normalizedExclude = normalizedExclude.substr(path.length);
}
// Finally take as relative path joined to watched path
excludePaths.add(rtrim(join(path, normalizedExclude), sep));
}
if (excludePaths.size > 0) {
return Array.from(excludePaths);
}
return undefined;
}
private startPolling(request: IRecursiveWatchRequest, pollingInterval: number, restarts = 0): void {
const cts = new CancellationTokenSource();
const instance = new DeferredPromise<void>();
const snapshotFile = randomPath(tmpdir(), 'vscode-watcher-snapshot');
// Remember as watcher instance
const watcher: IParcelWatcherInstance = {
request,
ready: instance.p,
restarts,
token: cts.token,
stop: async () => {
cts.dispose(true);
pollingWatcher.dispose();
unlinkSync(snapshotFile);
}
};
this.watchers.set(request.path, watcher);
// Path checks for symbolic links / wrong casing
const { realPath, realPathDiffers, realPathLength } = this.normalizePath(request);
// Warm up exclude/include patterns for usage
const excludePatterns = request.excludes.map(exclude => parse(exclude));
const includePatterns = request.includes?.map(include => parse(include));
const ignore = this.toExcludePaths(realPath, watcher.request.excludes);
this.trace(`Started watching: '${realPath}' with polling interval '${pollingInterval}' and native excludes '${ignore?.join(', ')}'`);
let counter = 0;
const pollingWatcher = new RunOnceScheduler(async () => {
counter++;
if (cts.token.isCancellationRequested) {
return;
}
// We already ran before, check for events since
if (counter > 1) {
const parcelEvents = await parcelWatcher.getEventsSince(realPath, snapshotFile, { ignore, backend: ParcelWatcher.PARCEL_WATCHER_BACKEND });
if (cts.token.isCancellationRequested) {
return;
}
// Handle & emit events
this.onParcelEvents(parcelEvents, watcher, excludePatterns, includePatterns, realPathDiffers, realPathLength);
}
// Store a snapshot of files to the snapshot file
await parcelWatcher.writeSnapshot(realPath, snapshotFile, { ignore, backend: ParcelWatcher.PARCEL_WATCHER_BACKEND });
// Signal we are ready now when the first snapshot was written
if (counter === 1) {
instance.complete();
}
if (cts.token.isCancellationRequested) {
return;
}
// Schedule again at the next interval
pollingWatcher.schedule();
}, pollingInterval);
pollingWatcher.schedule(0);
}
private startWatching(request: IRecursiveWatchRequest, restarts = 0): void {
const cts = new CancellationTokenSource();
const instance = new DeferredPromise<parcelWatcher.AsyncSubscription | undefined>();
// Remember as watcher instance
const watcher: IParcelWatcherInstance = {
request,
ready: instance.p,
restarts,
token: cts.token,
stop: async () => {
cts.dispose(true);
const watcherInstance = await instance.p;
await watcherInstance?.unsubscribe();
}
};
this.watchers.set(request.path, watcher);
// Path checks for symbolic links / wrong casing
const { realPath, realPathDiffers, realPathLength } = this.normalizePath(request);
// Warm up exclude/include patterns for usage
const excludePatterns = request.excludes.map(exclude => parse(exclude));
const includePatterns = request.includes?.map(include => parse(include));
const ignore = this.toExcludePaths(realPath, watcher.request.excludes);
parcelWatcher.subscribe(realPath, (error, parcelEvents) => {
if (watcher.token.isCancellationRequested) {
return; // return early when disposed
}
// In any case of an error, treat this like a unhandled exception
// that might require the watcher to restart. We do not really know
// the state of parcel at this point and as such will try to restart
// up to our maximum of restarts.
if (error) {
this.onUnexpectedError(error, watcher);
}
// Handle & emit events
this.onParcelEvents(parcelEvents, watcher, excludePatterns, includePatterns, realPathDiffers, realPathLength);
}, {
backend: ParcelWatcher.PARCEL_WATCHER_BACKEND,
ignore
}).then(parcelWatcher => {
this.trace(`Started watching: '${realPath}' with backend '${ParcelWatcher.PARCEL_WATCHER_BACKEND}' and native excludes '${ignore?.join(', ')}'`);
instance.complete(parcelWatcher);
}).catch(error => {
this.onUnexpectedError(error, watcher);
instance.complete(undefined);
});
}
private onParcelEvents(parcelEvents: parcelWatcher.Event[], watcher: IParcelWatcherInstance, excludes: ParsedPattern[], includes: ParsedPattern[] | undefined, realPathDiffers: boolean, realPathLength: number): void {
if (parcelEvents.length === 0) {
return;
}
// Check for excludes
const rawEvents = this.handleExcludeIncludes(parcelEvents, excludes, includes);
// Normalize events: handle NFC normalization and symlinks
const { events: normalizedEvents, rootDeleted } = this.normalizeEvents(rawEvents, watcher.request, realPathDiffers, realPathLength);
// Coalesce events: merge events of same kind
const coalescedEvents = coalesceEvents(normalizedEvents);
// Filter events: check for specific events we want to exclude
const filteredEvents = this.filterEvents(coalescedEvents, watcher.request, rootDeleted);
// Broadcast to clients
this.emitEvents(filteredEvents);
// Handle root path delete if confirmed from coalesced events
if (rootDeleted && coalescedEvents.some(event => event.path === watcher.request.path && event.type === FileChangeType.DELETED)) {
this.onWatchedPathDeleted(watcher);
}
}
private handleExcludeIncludes(parcelEvents: parcelWatcher.Event[], excludes: ParsedPattern[], includes: ParsedPattern[] | undefined): IDiskFileChange[] {
const events: IDiskFileChange[] = [];
for (const { path, type: parcelEventType } of parcelEvents) {
const type = ParcelWatcher.MAP_PARCEL_WATCHER_ACTION_TO_FILE_CHANGE.get(parcelEventType)!;
if (this.verboseLogging) {
this.trace(`${type === FileChangeType.ADDED ? '[ADDED]' : type === FileChangeType.DELETED ? '[DELETED]' : '[CHANGED]'} ${path}`);
}
// Add to buffer unless excluded or not included (not if explicitly disabled)
if (excludes.some(exclude => exclude(path))) {
if (this.verboseLogging) {
this.trace(` >> ignored (excluded) ${path}`);
}
} else if (includes && includes.length > 0 && !includes.some(include => include(path))) {
if (this.verboseLogging) {
this.trace(` >> ignored (not included) ${path}`);
}
} else {
events.push({ type, path });
}
}
return events;
}
private emitEvents(events: IDiskFileChange[]): void {
if (events.length === 0) {
return;
}
// Logging
if (this.verboseLogging) {
for (const event of events) {
this.trace(` >> normalized ${event.type === FileChangeType.ADDED ? '[ADDED]' : event.type === FileChangeType.DELETED ? '[DELETED]' : '[CHANGED]'} ${event.path}`);
}
}
// Broadcast to clients via throttler
const worked = this.throttledFileChangesWorker.work(events);
// Logging
if (!worked) {
this.warn(`started ignoring events due to too many file change events at once (incoming: ${events.length}, most recent change: ${events[0].path}). Use 'files.watcherExclude' setting to exclude folders with lots of changing files (e.g. compilation output).`);
} else {
if (this.throttledFileChangesWorker.pending > 0) {
this.trace(`started throttling events due to large amount of file change events at once (pending: ${this.throttledFileChangesWorker.pending}, most recent change: ${events[0].path}). Use 'files.watcherExclude' setting to exclude folders with lots of changing files (e.g. compilation output).`);
}
}
}
private normalizePath(request: IRecursiveWatchRequest): { realPath: string; realPathDiffers: boolean; realPathLength: number } {
let realPath = request.path;
let realPathDiffers = false;
let realPathLength = request.path.length;
try {
// First check for symbolic link
realPath = realpathSync(request.path);
// Second check for casing difference
// Note: this will be a no-op on Linux platforms
if (request.path === realPath) {
realPath = realcaseSync(request.path) ?? request.path;
}
// Correct watch path as needed
if (request.path !== realPath) {
realPathLength = realPath.length;
realPathDiffers = true;
this.warn(`correcting a path to watch that seems to be a symbolic link or wrong casing (original: ${request.path}, real: ${realPath})`);
}
} catch (error) {
// ignore
}
return { realPath, realPathDiffers, realPathLength };
}
private normalizeEvents(events: IDiskFileChange[], request: IRecursiveWatchRequest, realPathDiffers: boolean, realPathLength: number): { events: IDiskFileChange[]; rootDeleted: boolean } {
let rootDeleted = false;
for (const event of events) {
// Mac uses NFD unicode form on disk, but we want NFC
if (isMacintosh) {
event.path = normalizeNFC(event.path);
}
// Workaround for https://github.com/parcel-bundler/watcher/issues/68
// where watching root drive letter adds extra backslashes.
if (isWindows) {
if (request.path.length <= 3) { // for ex. c:, C:\
event.path = normalize(event.path);
}
}
// Convert paths back to original form in case it differs
if (realPathDiffers) {
event.path = request.path + event.path.substr(realPathLength);
}
// Check for root deleted
if (event.path === request.path && event.type === FileChangeType.DELETED) {
rootDeleted = true;
}
}
return { events, rootDeleted };
}
private filterEvents(events: IDiskFileChange[], request: IRecursiveWatchRequest, rootDeleted: boolean): IDiskFileChange[] {
if (!rootDeleted) {
return events;
}
return events.filter(event => {
if (event.path === request.path && event.type === FileChangeType.DELETED) {
// Explicitly exclude changes to root if we have any
// to avoid VS Code closing all opened editors which
// can happen e.g. in case of network connectivity
// issues
// (https://github.com/microsoft/vscode/issues/136673)
return false;
}
return true;
});
}
private onWatchedPathDeleted(watcher: IParcelWatcherInstance): void {
this.warn('Watcher shutdown because watched path got deleted', watcher);
const parentPath = dirname(watcher.request.path);
if (existsSync(parentPath)) {
const nodeWatcher = new NodeJSFileWatcherLibrary({ path: parentPath, excludes: [], recursive: false }, changes => {
if (watcher.token.isCancellationRequested) {
return; // return early when disposed
}
// Watcher path came back! Restart watching...
for (const { path, type } of changes) {
if (path === watcher.request.path && (type === FileChangeType.ADDED || type === FileChangeType.UPDATED)) {
this.warn('Watcher restarts because watched path got created again', watcher);
// Stop watching that parent folder
nodeWatcher.dispose();
// Restart the file watching
this.restartWatching(watcher);
break;
}
}
}, msg => this._onDidLogMessage.fire(msg), this.verboseLogging);
// Make sure to stop watching when the watcher is disposed
watcher.token.onCancellationRequested(() => nodeWatcher.dispose());
}
}
private onUnexpectedError(error: unknown, watcher?: IParcelWatcherInstance): void {
const msg = toErrorMessage(error);
// Specially handle ENOSPC errors that can happen when
// the watcher consumes so many file descriptors that
// we are running into a limit. We only want to warn
// once in this case to avoid log spam.
// See https://github.com/microsoft/vscode/issues/7950
if (msg.indexOf('No space left on device') !== -1) {
if (!this.enospcErrorLogged) {
this.error('Inotify limit reached (ENOSPC)', watcher);
this.enospcErrorLogged = true;
}
}
// Any other error is unexpected and we should try to
// restart the watcher as a result to get into healthy
// state again if possible and if not attempted too much
else {
this.error(`Unexpected error: ${msg} (EUNKNOWN)`, watcher);
this._onDidError.fire(msg);
}
}
async stop(): Promise<void> {
for (const [path] of this.watchers) {
await this.stopWatching(path);
}
this.watchers.clear();
}
protected restartWatching(watcher: IParcelWatcherInstance, delay = 800): void {
// Restart watcher delayed to accomodate for
// changes on disk that have triggered the
// need for a restart in the first place.
const scheduler = new RunOnceScheduler(async () => {
if (watcher.token.isCancellationRequested) {
return; // return early when disposed
}
// Await the watcher having stopped, as this is
// needed to properly re-watch the same path
await this.stopWatching(watcher.request.path);
// Start watcher again counting the restarts
if (watcher.request.pollingInterval) {
this.startPolling(watcher.request, watcher.request.pollingInterval, watcher.restarts + 1);
} else {
this.startWatching(watcher.request, watcher.restarts + 1);
}
}, delay);
scheduler.schedule();
watcher.token.onCancellationRequested(() => scheduler.dispose());
}
private async stopWatching(path: string): Promise<void> {
const watcher = this.watchers.get(path);
if (watcher) {
this.trace(`stopping file watcher on ${watcher.request.path}`);
this.watchers.delete(path);
try {
await watcher.stop();
} catch (error) {
this.error(`Unexpected error stopping watcher: ${toErrorMessage(error)}`, watcher);
}
}
}
protected normalizeRequests(requests: IRecursiveWatchRequest[]): IRecursiveWatchRequest[] {
const requestTrie = TernarySearchTree.forPaths<IRecursiveWatchRequest>(!isLinux);
// Sort requests by path length to have shortest first
// to have a way to prevent children to be watched if
// parents exist.
requests.sort((requestA, requestB) => requestA.path.length - requestB.path.length);
// Only consider requests for watching that are not
// a child of an existing request path to prevent
// duplication.
//
// However, allow explicit requests to watch folders
// that are symbolic links because the Parcel watcher
// does not allow to recursively watch symbolic links.
for (const request of requests) {
if (requestTrie.findSubstr(request.path)) {
try {
const realpath = realpathSync(request.path);
if (realpath === request.path) {
this.warn(`ignoring a path for watching who's parent is already watched: ${request.path}`);
continue; // path is not a symbolic link or similar
}
} catch (error) {
continue; // invalid path - ignore from watching
}
}
requestTrie.set(request.path, request);
}
return Array.from(requestTrie).map(([, request]) => request);
}
async setVerboseLogging(enabled: boolean): Promise<void> {
this.verboseLogging = enabled;
}
private trace(message: string) {
if (this.verboseLogging) {
this._onDidLogMessage.fire({ type: 'trace', message: this.toMessage(message) });
}
}
private warn(message: string, watcher?: IParcelWatcherInstance) {
this._onDidLogMessage.fire({ type: 'warn', message: this.toMessage(message, watcher) });
}
private error(message: string, watcher: IParcelWatcherInstance | undefined) {
this._onDidLogMessage.fire({ type: 'error', message: this.toMessage(message, watcher) });
}
private toMessage(message: string, watcher?: IParcelWatcherInstance): string {
return watcher ? `[File Watcher (parcel)] ${message} (path: ${watcher.request.path})` : `[File Watcher (parcel)] ${message}`;
}
}
|