watchman_watcher.js 8.5 KB

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