-
Notifications
You must be signed in to change notification settings - Fork 12k
/
Copy pathwatcher.ts
121 lines (105 loc) · 2.85 KB
/
watcher.ts
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
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import { FSWatcher } from 'chokidar';
export class ChangedFiles {
readonly added = new Set<string>();
readonly modified = new Set<string>();
readonly removed = new Set<string>();
toDebugString(): string {
const content = {
added: Array.from(this.added),
modified: Array.from(this.modified),
removed: Array.from(this.removed),
};
return JSON.stringify(content, null, 2);
}
}
export interface BuildWatcher extends AsyncIterableIterator<ChangedFiles> {
add(paths: string | readonly string[]): void;
remove(paths: string | readonly string[]): void;
close(): Promise<void>;
}
export function createWatcher(options?: {
polling?: boolean;
interval?: number;
ignored?: string[];
}): BuildWatcher {
const watcher = new FSWatcher({
...options,
disableGlobbing: true,
ignoreInitial: true,
});
const nextQueue: ((value?: ChangedFiles) => void)[] = [];
let currentChanges: ChangedFiles | undefined;
let nextWaitTimeout: NodeJS.Timeout | undefined;
watcher.on('all', (event, path) => {
switch (event) {
case 'add':
currentChanges ??= new ChangedFiles();
currentChanges.added.add(path);
break;
case 'change':
currentChanges ??= new ChangedFiles();
currentChanges.modified.add(path);
break;
case 'unlink':
currentChanges ??= new ChangedFiles();
currentChanges.removed.add(path);
break;
default:
return;
}
// Wait 250ms from next change to better capture groups of file save operations.
if (!nextWaitTimeout) {
nextWaitTimeout = setTimeout(() => {
nextWaitTimeout = undefined;
const next = nextQueue.shift();
if (next) {
const value = currentChanges;
currentChanges = undefined;
next(value);
}
}, 250);
nextWaitTimeout?.unref();
}
});
return {
[Symbol.asyncIterator]() {
return this;
},
async next() {
if (currentChanges && nextQueue.length === 0) {
const result = { value: currentChanges };
currentChanges = undefined;
return result;
}
return new Promise((resolve) => {
nextQueue.push((value) => resolve(value ? { value } : { done: true, value }));
});
},
add(paths) {
watcher.add(paths);
},
remove(paths) {
watcher.unwatch(paths);
},
async close() {
try {
await watcher.close();
if (nextWaitTimeout) {
clearTimeout(nextWaitTimeout);
}
} finally {
let next;
while ((next = nextQueue.shift()) !== undefined) {
next();
}
}
},
};
}