-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPathWatchManager.ts
More file actions
258 lines (190 loc) · 8.92 KB
/
PathWatchManager.ts
File metadata and controls
258 lines (190 loc) · 8.92 KB
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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
import * as chokidar from 'chokidar';
import * as path from 'path';
import * as proc from 'child_process';
import * as makedir from 'make-dir';
import CommandTemplateProcessor from "./CommandTemplateProcessor";
import * as debugModule from 'debug';
import Configuration from "./Configuration/Configuration";
import PathWatchConfig from './Configuration/PathWatchConfig';
import WatchExecutionManager from "./WatchExecutionManager";
import ExitHandler from "./ExitHandler";
import WatchFileConfigManager from './Configuration/WatchFileConfigManager';
require('colors');
const debug = debugModule(path.basename(__filename));
export default class PathWatchManager {
private _watchers = new Array<chokidar.FSWatcher>();
private _createDirWatchers = new Array<chokidar.FSWatcher>();
private _reportCounter = 0;
public constructor(private _exitHandler: ExitHandler) {}
public createPathWatchers(watchConfigManager: WatchFileConfigManager, requiredWatchNames?: Array<string>) {
const config = watchConfigManager.configuration;
let baseRoot = config.baseRoot;
if (!config.watches || config.watches.length === 0)
{
console.log('Error: No watches defined, bailing out');
return;
}
const requiredWatches = this.filterWatches(watchConfigManager, requiredWatchNames);
if (requiredWatches.length === 0) {
console.log(`None of the specified watches is defined: ${requiredWatchNames!.join(', ')} (Maybe watches are missing the 'name' property?)`)
return;
}
console.log(`Start listening to watch(es): ${requiredWatchNames!.join(', ')}`);
for (let configWatch of requiredWatches) {
let watchedPath = path.join(baseRoot, configWatch.watchRoot);
let execManager = new WatchExecutionManager(configWatch.executeBeforeReady, baseRoot, configWatch.watchRoot);
debug(`Registering watch for [${configWatch.sources.join(', ')}] on ${watchedPath}`);
this.registerAutoDirCreator(execManager, configWatch);
this.registerConfiguredWatchEvents(execManager, configWatch);
}
this.printReportLegend();
}
private filterWatches(watchConfigManager: WatchFileConfigManager, requiredWatchNames?: Array<string>): Array<PathWatchConfig> {
const allWatches = watchConfigManager.configuration.watches;
if (!allWatches || allWatches.length === 0) {
debug('No watches configured');
return new Array<PathWatchConfig>();
}
if (!requiredWatchNames || requiredWatchNames.length === 0) {
debug('No specific watches required - using all watches');
return allWatches;
}
return allWatches.filter(watch => {
if (watchConfigManager.getWatchFolders(watch.name).length > 1) {
debug(`Configured watch name '${watch.name}' is used more than once - conflicting watches are ignored`);
if (requiredWatchNames.find(requiredWatchName => watch.name === requiredWatchName)) {
console.log(`Watch '${watch.name}' is defined more than once - therefore is not activated`.red);
}
return false;
}
return requiredWatchNames.find(requiredWatchName => watch.name === requiredWatchName);
});
}
private registerAutoDirCreator(execManager: WatchExecutionManager, configWatch: PathWatchConfig) {
if (!configWatch.autoCreateDir) {
return;
}
let newWatcher = chokidar.watch(
".",
{
cwd: execManager.absoluteWatchRoot,
ignored: configWatch.ignored || [],
persistent: true
});
let autoCreateDirTarget = configWatch.autoCreateDir.replace(/\"/g, ''); // 'make-dir' package considers double quotes as illegal chars
let processor = new CommandTemplateProcessor(execManager, autoCreateDirTarget, true);
newWatcher.on('addDir', (dirPath: string) => this.autoCreateDirExec(processor, dirPath));
debug(`- Registered auto folder creation listening on ${execManager.absoluteWatchRoot}`);
this._createDirWatchers.push(newWatcher);
}
private registerConfiguredWatchEvents(execManager: WatchExecutionManager, configWatch: PathWatchConfig) {
let newWatcher = chokidar.watch(
configWatch.sources,
{
cwd: execManager.absoluteWatchRoot,
ignored: configWatch.ignored || [],
persistent: true
});
for (let triggeredCommand of configWatch.triggeredCommands) {
let processor = new CommandTemplateProcessor(execManager, triggeredCommand.commands, triggeredCommand.showStdout);
for (let trigger of triggeredCommand.triggeringEvents) {
newWatcher.on(trigger, (path: string) => this.executeTriggeredCommand(processor, trigger, path));
debug(`- Registered ${trigger} event`);
}
}
newWatcher.on('ready', () => {
execManager.allowExecution();
if (configWatch.execAfterReady) {
let processor = new CommandTemplateProcessor(execManager, configWatch.execAfterReady, true);
debug(`Executing 'afterReady' command for watcher ${execManager.absoluteWatchRoot}..`);
this.executeCommand(processor.getDigestedCommand('N/A', execManager.absoluteWatchRoot), true);
}
console.log(`Watch '${configWatch.name}' for [${configWatch.sources.join(', ')}] on '${execManager.absoluteWatchRoot}' is ready`.green);
});
this._watchers.push(newWatcher);
}
private async autoCreateDirExec(processor: CommandTemplateProcessor, addedPath: string) {
if (!processor.isAllowedExecution) {
debug(`Triggered for execution but it is not (yet) allowed, ignoring triggered event (addDir '${addedPath}')`);
return;
}
let targetFolder = processor.getDigestedCommand('addDir', addedPath);
let path = await makedir(targetFolder).catch(error => {
console.error(`Error: Could not create target folder for ${addedPath}. Caught error: ${error}`);
return;
});
debug(`Created folder '${targetFolder}'`);
this.reportActivity('addDir');
}
private executeTriggeredCommand(processor: CommandTemplateProcessor, changeType: string, changedRelativePath: string) {
if (!processor.isAllowedExecution) {
debug(`Triggered for execution but it is not (yet) allowed, ignoring triggered event (${changeType} '${changedRelativePath}')`);
return;
}
changedRelativePath = changedRelativePath || '';
debug(`Digesting command: ${changeType} event for '${path.join(processor.watchRoot, changedRelativePath)}'`);
processor.getDigestedCommands(changeType, changedRelativePath).forEach(command => this.executeCommand(command, processor.showStdout));
this.reportActivity(changeType);
}
private executeCommand(processToExecute: string, showStdout: boolean) {
let childProc = proc.exec(processToExecute, (error, stdout, stderr) => {
if (error) {
console.log(`Error executing shell command [${processToExecute}]: ${error}`);
debug(`stderr: ${stderr}`);
this._exitHandler.unregisterProcess(childProc.pid);
return;
}
if (showStdout) {
console.log('\n' + stdout);
this._reportCounter = 0; // So the next report starts at a new line
}
this._exitHandler.unregisterProcess(childProc.pid);
});
this._exitHandler.registerProcess(childProc);
}
private printReportLegend() {
if (process.env.DEBUG) {
return;
}
console.log(`
Changes report legend:
a - Added file
f - Added folder
c - Changed file
d - Deleted file
e - Watcher error
. - Any other change event
`);
}
private reportActivity(changeType: string) {
if (process.env.DEBUG) {
return;
}
let report: string;
switch (changeType) {
case 'add':
report = 'a';
break;
case 'addDir':
report = 'f';
break;
case 'change':
report = 'c';
break;
case 'unlink':
report = 'd';
break;
case 'error':
report = 'e';
break;
default:
report = '.';
break;
}
if (this._reportCounter % 100 === 0) {
process.stdout.write(`\n[${new Date().toISOString()}] `);
}
process.stdout.write(report);
++this._reportCounter;
}
}