forked from graphprotocol/graph-tooling
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwatcher.js
85 lines (71 loc) · 2.15 KB
/
watcher.js
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
const chokidar = require('chokidar')
const path = require('path')
module.exports = class Watcher {
constructor(options) {
const { onReady, onTrigger, onCollectFiles, onError } = options
this.onReady = onReady
this.onTrigger = onTrigger
this.onCollectFiles = onCollectFiles
this.onError = onError
}
async watch() {
// Collect files to watch
let files = await this.onCollectFiles()
// Initialize watcher
this.watcher = chokidar.watch(files, {
persistent: true,
ignoreInitial: true,
atomic: 500,
})
// Bind variables locally
let watcher = this.watcher
let onTrigger = this.onTrigger
let onCollectFiles = this.onCollectFiles
let onError = this.onError
let onReady = this.onReady
watcher.on('ready', async () => {
// Notify listeners that we're watching
onReady()
// Trigger once when ready
await onTrigger(undefined)
})
watcher.on('error', error => {
onError(error)
})
watcher.on('all', async (eventType, file) => {
try {
// Collect watch all new files to watch
let newFiles = await onCollectFiles()
// Collect watched files, if there are any
let watchedFiles = []
let watched = watcher.getWatched()
watchedFiles = Object.keys(watched).reduce(
(files, dirname) =>
watched[dirname].reduce((files, filename) => {
files.push(path.resolve(path.join(dirname, filename)))
return files
}, files),
[]
)
let diff = (xs, ys) => ({
added: ys.filter(y => xs.indexOf(y) < 0),
removed: xs.filter(x => ys.indexOf(x) < 0),
})
// Diff previously watched files and new files; then remove and
// add files from/to the watcher accordingly
let filesDiff = diff(watchedFiles, newFiles)
watcher.unwatch(filesDiff.removed)
watcher.add(filesDiff.added)
// Run the trigger callback
await onTrigger(file)
} catch (e) {
onError(e)
}
})
}
close() {
if (this.watcher !== undefined) {
this.watcher.close()
}
}
}