1 | /*
|
---|
2 | MIT License http://www.opensource.org/licenses/mit-license.php
|
---|
3 | Author Tobias Koppers @sokra
|
---|
4 | */
|
---|
5 | "use strict";
|
---|
6 |
|
---|
7 | const path = require("path");
|
---|
8 | const DirectoryWatcher = require("./DirectoryWatcher");
|
---|
9 |
|
---|
10 | class WatcherManager {
|
---|
11 | constructor(options) {
|
---|
12 | this.options = options;
|
---|
13 | this.directoryWatchers = new Map();
|
---|
14 | }
|
---|
15 |
|
---|
16 | getDirectoryWatcher(directory) {
|
---|
17 | const watcher = this.directoryWatchers.get(directory);
|
---|
18 | if (watcher === undefined) {
|
---|
19 | const newWatcher = new DirectoryWatcher(this, directory, this.options);
|
---|
20 | this.directoryWatchers.set(directory, newWatcher);
|
---|
21 | newWatcher.on("closed", () => {
|
---|
22 | this.directoryWatchers.delete(directory);
|
---|
23 | });
|
---|
24 | return newWatcher;
|
---|
25 | }
|
---|
26 | return watcher;
|
---|
27 | }
|
---|
28 |
|
---|
29 | watchFile(p, startTime) {
|
---|
30 | const directory = path.dirname(p);
|
---|
31 | if (directory === p) return null;
|
---|
32 | return this.getDirectoryWatcher(directory).watch(p, startTime);
|
---|
33 | }
|
---|
34 |
|
---|
35 | watchDirectory(directory, startTime) {
|
---|
36 | return this.getDirectoryWatcher(directory).watch(directory, startTime);
|
---|
37 | }
|
---|
38 | }
|
---|
39 |
|
---|
40 | const watcherManagers = new WeakMap();
|
---|
41 | /**
|
---|
42 | * @param {object} options options
|
---|
43 | * @returns {WatcherManager} the watcher manager
|
---|
44 | */
|
---|
45 | module.exports = options => {
|
---|
46 | const watcherManager = watcherManagers.get(options);
|
---|
47 | if (watcherManager !== undefined) return watcherManager;
|
---|
48 | const newWatcherManager = new WatcherManager(options);
|
---|
49 | watcherManagers.set(options, newWatcherManager);
|
---|
50 | return newWatcherManager;
|
---|
51 | };
|
---|
52 | module.exports.WatcherManager = WatcherManager;
|
---|