WatchmanWatcher.js 9.2 KB

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