-
Notifications
You must be signed in to change notification settings - Fork 345
/
Copy pathwatcher.js
78 lines (59 loc) · 2.25 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
/* @flow */
import Watchpack from 'watchpack';
import debounce from 'debounce';
import {createLogger} from './util/logger';
import {FileFilter} from './cmd/build';
const log = createLogger(__filename);
// onSourceChange types and implementation
export type ShouldWatchFn = (filePath: string) => boolean;
export type OnChangeFn = () => any;
export type OnSourceChangeParams = {|
sourceDir: string,
artifactsDir: string,
onChange: OnChangeFn,
shouldWatchFile?: ShouldWatchFn,
|};
// NOTE: this fix an issue with flow and default exports (which currently
// lose their type signatures) by explicitly declare the default export
// signature. Reference: https://github.com/facebook/flow/issues/449
declare function exports(params: OnSourceChangeParams): Watchpack;
export type OnSourceChangeFn = (params: OnSourceChangeParams) => Watchpack;
export default function onSourceChange(
{sourceDir, artifactsDir, onChange, shouldWatchFile}: OnSourceChangeParams
): Watchpack {
// TODO: For network disks, we would need to add {poll: true}.
const watcher = new Watchpack();
const executeImmediately = true;
onChange = debounce(onChange, 1000, executeImmediately);
watcher.on('change', (filePath) => {
proxyFileChanges({artifactsDir, onChange, filePath, shouldWatchFile});
});
log.debug(`Watching for file changes in ${sourceDir}`);
watcher.watch([], [sourceDir], Date.now());
// TODO: support interrupting the watcher on Windows.
// https://github.com/mozilla/web-ext/issues/225
process.on('SIGINT', () => watcher.close());
return watcher;
}
// proxyFileChanges types and implementation.
export type ProxyFileChangesParams = {|
artifactsDir: string,
onChange: OnChangeFn,
filePath: string,
shouldWatchFile?: ShouldWatchFn,
|};
export function proxyFileChanges(
{artifactsDir, onChange, filePath, shouldWatchFile}: ProxyFileChangesParams
): void {
if (!shouldWatchFile) {
const fileFilter = new FileFilter();
shouldWatchFile = (...args) => fileFilter.wantFile(...args);
}
if (filePath.indexOf(artifactsDir) === 0 || !shouldWatchFile(filePath)) {
log.debug(`Ignoring change to: ${filePath}`);
} else {
log.debug(`Changed: ${filePath}`);
log.debug(`Last change detection: ${(new Date()).toTimeString()}`);
onChange();
}
}