forked from broccolijs/broccoli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwatcher_adapter.ts
84 lines (75 loc) · 2.52 KB
/
watcher_adapter.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
import sane from 'sane';
import { EventEmitter } from 'events';
import SourceNode from './wrappers/source-node';
import SourceNodeWrapper from './wrappers/source-node';
import bindFileEvent from './utils/bind-file-event';
const logger = require('heimdalljs-logger')('broccoli:watcherAdapter');
interface WatcherAdapterOptions extends sane.Options {
filter?: (name: string) => boolean;
}
function defaultFilterFunction(name: string) {
return /^[^.]/.test(name);
}
class WatcherAdapter extends EventEmitter {
watchers: sane.Watcher[];
watchedNodes: SourceNodeWrapper[];
options: WatcherAdapterOptions;
constructor(watchedNodes: SourceNodeWrapper[], options: sane.Options = {}) {
super();
if (!Array.isArray(watchedNodes)) {
throw new TypeError(
`WatcherAdapter's first argument must be an array of SourceNodeWrapper nodes`
);
}
for (const node of watchedNodes) {
if (!(node instanceof SourceNode)) {
throw new Error(`${node} is not a SourceNode`);
}
if (node.nodeInfo.watched !== true) {
throw new Error(`'${node.nodeInfo.sourceDirectory}' is not watched`);
}
}
this.watchedNodes = watchedNodes;
this.options = options;
this.options.filter = this.options.filter || defaultFilterFunction;
this.watchers = [];
}
watch() {
let watchers = this.watchedNodes.map((node: SourceNodeWrapper) => {
const watchedPath = node.nodeInfo.sourceDirectory;
const watcher = sane(watchedPath, this.options);
this.watchers.push(watcher);
bindFileEvent(this, watcher, node, 'change');
bindFileEvent(this, watcher, node, 'add');
bindFileEvent(this, watcher, node, 'delete');
return new Promise((resolve, reject) => {
watcher.on('ready', resolve);
watcher.on('error', reject);
}).then(() => {
watcher.removeAllListeners('ready');
watcher.removeAllListeners('error');
watcher.on('error', (err: Error) => {
logger.debug('error', err);
this.emit('error', err);
});
logger.debug('ready', watchedPath);
});
});
return Promise.all(watchers).then(() => {});
}
quit() {
let closing = this.watchers.map(
(watcher: sane.Watcher) =>
new Promise((resolve, reject) =>
// @ts-ignore
watcher.close((err: any) => {
if (err) reject(err);
else resolve();
})
)
);
this.watchers.length = 0;
return Promise.all(closing).then(() => {});
}
};
export = WatcherAdapter;