WatchmanWatcher.js 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  1. 'use strict';
  2. Object.defineProperty(exports, '__esModule', {
  3. value: true
  4. });
  5. exports.default = WatchmanWatcher;
  6. function _fs() {
  7. const data = _interopRequireDefault(require('fs'));
  8. _fs = function _fs() {
  9. return data;
  10. };
  11. return data;
  12. }
  13. function _path() {
  14. const data = _interopRequireDefault(require('path'));
  15. _path = function _path() {
  16. return data;
  17. };
  18. return data;
  19. }
  20. function _assert() {
  21. const data = _interopRequireDefault(require('assert'));
  22. _assert = function _assert() {
  23. return data;
  24. };
  25. return data;
  26. }
  27. function _events() {
  28. const data = require('events');
  29. _events = function _events() {
  30. return data;
  31. };
  32. return data;
  33. }
  34. function _fbWatchman() {
  35. const data = _interopRequireDefault(require('fb-watchman'));
  36. _fbWatchman = function _fbWatchman() {
  37. return data;
  38. };
  39. return data;
  40. }
  41. function _common() {
  42. const data = _interopRequireDefault(require('sane/src/common'));
  43. _common = function _common() {
  44. return data;
  45. };
  46. return data;
  47. }
  48. function _recrawlWarningDedupe() {
  49. const data = _interopRequireDefault(
  50. require('sane/src/utils/recrawl-warning-dedupe')
  51. );
  52. _recrawlWarningDedupe = function _recrawlWarningDedupe() {
  53. return data;
  54. };
  55. return data;
  56. }
  57. function _interopRequireDefault(obj) {
  58. return obj && obj.__esModule ? obj : {default: obj};
  59. }
  60. /**
  61. * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
  62. *
  63. * This source code is licensed under the MIT license found in the
  64. * LICENSE file in the root directory of this source tree.
  65. */
  66. const CHANGE_EVENT = _common().default.CHANGE_EVENT;
  67. const DELETE_EVENT = _common().default.DELETE_EVENT;
  68. const ADD_EVENT = _common().default.ADD_EVENT;
  69. const ALL_EVENT = _common().default.ALL_EVENT;
  70. const SUB_NAME = 'sane-sub';
  71. /**
  72. * Watches `dir`.
  73. *
  74. * @class PollWatcher
  75. * @param String dir
  76. * @param {Object} opts
  77. * @public
  78. */
  79. function WatchmanWatcher(dir, opts) {
  80. _common().default.assignOptions(this, opts);
  81. this.root = _path().default.resolve(dir);
  82. this.init();
  83. } // eslint-disable-next-line no-proto
  84. WatchmanWatcher.prototype.__proto__ = _events().EventEmitter.prototype;
  85. /**
  86. * Run the watchman `watch` command on the root and subscribe to changes.
  87. *
  88. * @private
  89. */
  90. WatchmanWatcher.prototype.init = function() {
  91. if (this.client) {
  92. this.client.removeAllListeners();
  93. }
  94. const self = this;
  95. this.client = new (_fbWatchman()).default.Client();
  96. this.client.on('error', error => {
  97. self.emit('error', error);
  98. });
  99. this.client.on('subscription', this.handleChangeEvent.bind(this));
  100. this.client.on('end', () => {
  101. console.warn('[sane] Warning: Lost connection to watchman, reconnecting..');
  102. self.init();
  103. });
  104. this.watchProjectInfo = null;
  105. function getWatchRoot() {
  106. return self.watchProjectInfo ? self.watchProjectInfo.root : self.root;
  107. }
  108. function onCapability(error, resp) {
  109. if (handleError(self, error)) {
  110. // The Watchman watcher is unusable on this system, we cannot continue
  111. return;
  112. }
  113. handleWarning(resp);
  114. self.capabilities = resp.capabilities;
  115. if (self.capabilities.relative_root) {
  116. self.client.command(['watch-project', getWatchRoot()], onWatchProject);
  117. } else {
  118. self.client.command(['watch', getWatchRoot()], onWatch);
  119. }
  120. }
  121. function onWatchProject(error, resp) {
  122. if (handleError(self, error)) {
  123. return;
  124. }
  125. handleWarning(resp);
  126. self.watchProjectInfo = {
  127. relativePath: resp.relative_path ? resp.relative_path : '',
  128. root: resp.watch
  129. };
  130. self.client.command(['clock', getWatchRoot()], onClock);
  131. }
  132. function onWatch(error, resp) {
  133. if (handleError(self, error)) {
  134. return;
  135. }
  136. handleWarning(resp);
  137. self.client.command(['clock', getWatchRoot()], onClock);
  138. }
  139. function onClock(error, resp) {
  140. if (handleError(self, error)) {
  141. return;
  142. }
  143. handleWarning(resp);
  144. const options = {
  145. fields: ['name', 'exists', 'new'],
  146. since: resp.clock
  147. }; // If the server has the wildmatch capability available it supports
  148. // the recursive **/*.foo style match and we can offload our globs
  149. // to the watchman server. This saves both on data size to be
  150. // communicated back to us and compute for evaluating the globs
  151. // in our node process.
  152. if (self.capabilities.wildmatch) {
  153. if (self.globs.length === 0) {
  154. if (!self.dot) {
  155. // Make sure we honor the dot option if even we're not using globs.
  156. options.expression = [
  157. 'match',
  158. '**',
  159. 'wholename',
  160. {
  161. includedotfiles: false
  162. }
  163. ];
  164. }
  165. } else {
  166. options.expression = ['anyof'];
  167. for (const i in self.globs) {
  168. options.expression.push([
  169. 'match',
  170. self.globs[i],
  171. 'wholename',
  172. {
  173. includedotfiles: self.dot
  174. }
  175. ]);
  176. }
  177. }
  178. }
  179. if (self.capabilities.relative_root) {
  180. options.relative_root = self.watchProjectInfo.relativePath;
  181. }
  182. self.client.command(
  183. ['subscribe', getWatchRoot(), SUB_NAME, options],
  184. onSubscribe
  185. );
  186. }
  187. function onSubscribe(error, resp) {
  188. if (handleError(self, error)) {
  189. return;
  190. }
  191. handleWarning(resp);
  192. self.emit('ready');
  193. }
  194. self.client.capabilityCheck(
  195. {
  196. optional: ['wildmatch', 'relative_root']
  197. },
  198. onCapability
  199. );
  200. };
  201. /**
  202. * Handles a change event coming from the subscription.
  203. *
  204. * @param {Object} resp
  205. * @private
  206. */
  207. WatchmanWatcher.prototype.handleChangeEvent = function(resp) {
  208. _assert().default.equal(
  209. resp.subscription,
  210. SUB_NAME,
  211. 'Invalid subscription event.'
  212. );
  213. if (resp.is_fresh_instance) {
  214. this.emit('fresh_instance');
  215. }
  216. if (resp.is_fresh_instance) {
  217. this.emit('fresh_instance');
  218. }
  219. if (Array.isArray(resp.files)) {
  220. resp.files.forEach(this.handleFileChange, this);
  221. }
  222. };
  223. /**
  224. * Handles a single change event record.
  225. *
  226. * @param {Object} changeDescriptor
  227. * @private
  228. */
  229. WatchmanWatcher.prototype.handleFileChange = function(changeDescriptor) {
  230. const self = this;
  231. let absPath;
  232. let relativePath;
  233. if (this.capabilities.relative_root) {
  234. relativePath = changeDescriptor.name;
  235. absPath = _path().default.join(
  236. this.watchProjectInfo.root,
  237. this.watchProjectInfo.relativePath,
  238. relativePath
  239. );
  240. } else {
  241. absPath = _path().default.join(this.root, changeDescriptor.name);
  242. relativePath = changeDescriptor.name;
  243. }
  244. if (
  245. !(self.capabilities.wildmatch && !this.hasIgnore) &&
  246. !_common().default.isFileIncluded(
  247. this.globs,
  248. this.dot,
  249. this.doIgnore,
  250. relativePath
  251. )
  252. ) {
  253. return;
  254. }
  255. if (!changeDescriptor.exists) {
  256. self.emitEvent(DELETE_EVENT, relativePath, self.root);
  257. } else {
  258. _fs().default.lstat(absPath, (error, stat) => {
  259. // Files can be deleted between the event and the lstat call
  260. // the most reliable thing to do here is to ignore the event.
  261. if (error && error.code === 'ENOENT') {
  262. return;
  263. }
  264. if (handleError(self, error)) {
  265. return;
  266. }
  267. const eventType = changeDescriptor.new ? ADD_EVENT : CHANGE_EVENT; // Change event on dirs are mostly useless.
  268. if (!(eventType === CHANGE_EVENT && stat.isDirectory())) {
  269. self.emitEvent(eventType, relativePath, self.root, stat);
  270. }
  271. });
  272. }
  273. };
  274. /**
  275. * Dispatches the event.
  276. *
  277. * @param {string} eventType
  278. * @param {string} filepath
  279. * @param {string} root
  280. * @param {fs.Stat} stat
  281. * @private
  282. */
  283. WatchmanWatcher.prototype.emitEvent = function(
  284. eventType,
  285. filepath,
  286. root,
  287. stat
  288. ) {
  289. this.emit(eventType, filepath, root, stat);
  290. this.emit(ALL_EVENT, eventType, filepath, root, stat);
  291. };
  292. /**
  293. * Closes the watcher.
  294. *
  295. * @param {function} callback
  296. * @private
  297. */
  298. WatchmanWatcher.prototype.close = function(callback) {
  299. this.client.removeAllListeners();
  300. this.client.end();
  301. callback && callback(null, true);
  302. };
  303. /**
  304. * Handles an error and returns true if exists.
  305. *
  306. * @param {WatchmanWatcher} self
  307. * @param {Error} error
  308. * @private
  309. */
  310. function handleError(self, error) {
  311. if (error != null) {
  312. self.emit('error', error);
  313. return true;
  314. } else {
  315. return false;
  316. }
  317. }
  318. /**
  319. * Handles a warning in the watchman resp object.
  320. *
  321. * @param {object} resp
  322. * @private
  323. */
  324. function handleWarning(resp) {
  325. if ('warning' in resp) {
  326. if (_recrawlWarningDedupe().default.isRecrawlWarningDupe(resp.warning)) {
  327. return true;
  328. }
  329. console.warn(resp.warning);
  330. return true;
  331. } else {
  332. return false;
  333. }
  334. }