-
-
Notifications
You must be signed in to change notification settings - Fork 6.4k
/
WatchmanWatcher.js
323 lines (274 loc) · 7.2 KB
/
WatchmanWatcher.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
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
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import assert from 'assert';
import {EventEmitter} from 'events';
import path from 'path';
import watchman from 'fb-watchman';
import * as fs from 'graceful-fs';
import common from 'sane/src/common';
import RecrawlWarning from 'sane/src/utils/recrawl-warning-dedupe';
const CHANGE_EVENT = common.CHANGE_EVENT;
const DELETE_EVENT = common.DELETE_EVENT;
const ADD_EVENT = common.ADD_EVENT;
const ALL_EVENT = common.ALL_EVENT;
const SUB_NAME = 'sane-sub';
/**
* Watches `dir`.
*
* @class PollWatcher
* @param String dir
* @param {Object} opts
* @public
*/
export default function WatchmanWatcher(dir, opts) {
common.assignOptions(this, opts);
this.root = path.resolve(dir);
this.init();
}
// eslint-disable-next-line no-proto
WatchmanWatcher.prototype.__proto__ = EventEmitter.prototype;
/**
* Run the watchman `watch` command on the root and subscribe to changes.
*
* @private
*/
WatchmanWatcher.prototype.init = function () {
if (this.client) {
this.client.removeAllListeners();
}
const self = this;
this.client = new watchman.Client();
this.client.on('error', error => {
self.emit('error', error);
});
this.client.on('subscription', this.handleChangeEvent.bind(this));
this.client.on('end', () => {
console.warn('[sane] Warning: Lost connection to watchman, reconnecting..');
self.init();
});
this.watchProjectInfo = null;
function getWatchRoot() {
return self.watchProjectInfo ? self.watchProjectInfo.root : self.root;
}
function onCapability(error, resp) {
if (handleError(self, error)) {
// The Watchman watcher is unusable on this system, we cannot continue
return;
}
handleWarning(resp);
self.capabilities = resp.capabilities;
if (self.capabilities.relative_root) {
self.client.command(['watch-project', getWatchRoot()], onWatchProject);
} else {
self.client.command(['watch', getWatchRoot()], onWatch);
}
}
function onWatchProject(error, resp) {
if (handleError(self, error)) {
return;
}
handleWarning(resp);
self.watchProjectInfo = {
relativePath: resp.relative_path ? resp.relative_path : '',
root: resp.watch,
};
self.client.command(['clock', getWatchRoot()], onClock);
}
function onWatch(error, resp) {
if (handleError(self, error)) {
return;
}
handleWarning(resp);
self.client.command(['clock', getWatchRoot()], onClock);
}
function onClock(error, resp) {
if (handleError(self, error)) {
return;
}
handleWarning(resp);
const options = {
fields: ['name', 'exists', 'new'],
since: resp.clock,
};
// If the server has the wildmatch capability available it supports
// the recursive **/*.foo style match and we can offload our globs
// to the watchman server. This saves both on data size to be
// communicated back to us and compute for evaluating the globs
// in our node process.
if (self.capabilities.wildmatch) {
if (self.globs.length === 0) {
if (!self.dot) {
// Make sure we honor the dot option if even we're not using globs.
options.expression = [
'match',
'**',
'wholename',
{
includedotfiles: false,
},
];
}
} else {
options.expression = ['anyof'];
for (const i in self.globs) {
options.expression.push([
'match',
self.globs[i],
'wholename',
{
includedotfiles: self.dot,
},
]);
}
}
}
if (self.capabilities.relative_root) {
options.relative_root = self.watchProjectInfo.relativePath;
}
self.client.command(
['subscribe', getWatchRoot(), SUB_NAME, options],
onSubscribe,
);
}
function onSubscribe(error, resp) {
if (handleError(self, error)) {
return;
}
handleWarning(resp);
self.emit('ready');
}
self.client.capabilityCheck(
{
optional: ['wildmatch', 'relative_root'],
},
onCapability,
);
};
/**
* Handles a change event coming from the subscription.
*
* @param {Object} resp
* @private
*/
WatchmanWatcher.prototype.handleChangeEvent = function (resp) {
assert.equal(resp.subscription, SUB_NAME, 'Invalid subscription event.');
if (resp.is_fresh_instance) {
this.emit('fresh_instance');
}
if (resp.is_fresh_instance) {
this.emit('fresh_instance');
}
if (Array.isArray(resp.files)) {
resp.files.forEach(this.handleFileChange, this);
}
};
/**
* Handles a single change event record.
*
* @param {Object} changeDescriptor
* @private
*/
WatchmanWatcher.prototype.handleFileChange = function (changeDescriptor) {
const self = this;
let absPath;
let relativePath;
if (this.capabilities.relative_root) {
relativePath = changeDescriptor.name;
absPath = path.join(
this.watchProjectInfo.root,
this.watchProjectInfo.relativePath,
relativePath,
);
} else {
absPath = path.join(this.root, changeDescriptor.name);
relativePath = changeDescriptor.name;
}
if (
!(self.capabilities.wildmatch && !this.hasIgnore) &&
!common.isFileIncluded(this.globs, this.dot, this.doIgnore, relativePath)
) {
return;
}
if (!changeDescriptor.exists) {
self.emitEvent(DELETE_EVENT, relativePath, self.root);
} else {
fs.lstat(absPath, (error, stat) => {
// Files can be deleted between the event and the lstat call
// the most reliable thing to do here is to ignore the event.
if (error && error.code === 'ENOENT') {
return;
}
if (handleError(self, error)) {
return;
}
const eventType = changeDescriptor.new ? ADD_EVENT : CHANGE_EVENT;
// Change event on dirs are mostly useless.
if (!(eventType === CHANGE_EVENT && stat.isDirectory())) {
self.emitEvent(eventType, relativePath, self.root, stat);
}
});
}
};
/**
* Dispatches the event.
*
* @param {string} eventType
* @param {string} filepath
* @param {string} root
* @param {fs.Stat} stat
* @private
*/
WatchmanWatcher.prototype.emitEvent = function (
eventType,
filepath,
root,
stat,
) {
this.emit(eventType, filepath, root, stat);
this.emit(ALL_EVENT, eventType, filepath, root, stat);
};
/**
* Closes the watcher.
*
*/
WatchmanWatcher.prototype.close = function () {
this.client.removeAllListeners();
this.client.end();
return Promise.resolve();
};
/**
* Handles an error and returns true if exists.
*
* @param {WatchmanWatcher} self
* @param {Error} error
* @private
*/
function handleError(self, error) {
if (error != null) {
self.emit('error', error);
return true;
} else {
return false;
}
}
/**
* Handles a warning in the watchman resp object.
*
* @param {object} resp
* @private
*/
function handleWarning(resp) {
if ('warning' in resp) {
if (RecrawlWarning.isRecrawlWarningDupe(resp.warning)) {
return true;
}
console.warn(resp.warning);
return true;
} else {
return false;
}
}