Debian Codegraph @

hgext/fsmonitor/__init__.py

raw
1 # __init__.py - fsmonitor initialization and overrides
2 #
3 # Copyright 2013-2016 Facebook, Inc.
4 #
5 # This software may be used and distributed according to the terms of the
6 # GNU General Public License version 2 or any later version.
7
8 '''Faster status operations with the Watchman file monitor (EXPERIMENTAL)
9
10 Integrates the file-watching program Watchman with Mercurial to produce faster
11 status results.
12
13 On a particular Linux system, for a real-world repository with over 400,000
14 files hosted on ext4, vanilla `hg status` takes 1.3 seconds. On the same
15 system, with fsmonitor it takes about 0.3 seconds.
16
17 fsmonitor requires no configuration -- it will tell Watchman about your
18 repository as necessary. You'll need to install Watchman from
19 https://facebook.github.io/watchman/ and make sure it is in your PATH.
20
21 fsmonitor is incompatible with the largefiles and eol extensions, and
22 will disable itself if any of those are active.
23
24 The following configuration options exist:
25
26 ::
27
28 [fsmonitor]
29 mode = {off, on, paranoid}
30
31 When `mode = off`, fsmonitor will disable itself (similar to not loading the
32 extension at all). When `mode = on`, fsmonitor will be enabled (the default).
33 When `mode = paranoid`, fsmonitor will query both Watchman and the filesystem,
34 and ensure that the results are consistent.
35
36 ::
37
38 [fsmonitor]
39 timeout = (float)
40
41 A value, in seconds, that determines how long fsmonitor will wait for Watchman
42 to return results. Defaults to `2.0`.
43
44 ::
45
46 [fsmonitor]
47 blacklistusers = (list of userids)
48
49 A list of usernames for which fsmonitor will disable itself altogether.
50
51 ::
52
53 [fsmonitor]
54 walk_on_invalidate = (boolean)
55
56 Whether or not to walk the whole repo ourselves when our cached state has been
57 invalidated, for example when Watchman has been restarted or .hgignore rules
58 have been changed. Walking the repo in that case can result in competing for
59 I/O with Watchman. For large repos it is recommended to set this value to
60 false. You may wish to set this to true if you have a very fast filesystem
61 that can outpace the IPC overhead of getting the result data for the full repo
62 from Watchman. Defaults to false.
63
64 ::
65
66 [fsmonitor]
67 warn_when_unused = (boolean)
68
69 Whether to print a warning during certain operations when fsmonitor would be
70 beneficial to performance but isn't enabled.
71
72 ::
73
74 [fsmonitor]
75 warn_update_file_count = (integer)
76 # or when mercurial is built with rust support
77 warn_update_file_count_rust = (integer)
78
79 If ``warn_when_unused`` is set and fsmonitor isn't enabled, a warning will
80 be printed during working directory updates if this many files will be
81 created.
82 '''
83
84 # Platforms Supported
85 # ===================
86 #
87 # **Linux:** *Stable*. Watchman and fsmonitor are both known to work reliably,
88 # even under severe loads.
89 #
90 # **Mac OS X:** *Stable*. The Mercurial test suite passes with fsmonitor
91 # turned on, on case-insensitive HFS+. There has been a reasonable amount of
92 # user testing under normal loads.
93 #
94 # **Solaris, BSD:** *Alpha*. watchman and fsmonitor are believed to work, but
95 # very little testing has been done.
96 #
97 # **Windows:** *Alpha*. Not in a release version of watchman or fsmonitor yet.
98 #
99 # Known Issues
100 # ============
101 #
102 # * fsmonitor will disable itself if any of the following extensions are
103 # enabled: largefiles, inotify, eol; or if the repository has subrepos.
104 # * fsmonitor will produce incorrect results if nested repos that are not
105 # subrepos exist. *Workaround*: add nested repo paths to your `.hgignore`.
106 #
107 # The issues related to nested repos and subrepos are probably not fundamental
108 # ones. Patches to fix them are welcome.
109
110 from __future__ import annotations
111
112 import codecs
113 import os
114 import stat
115 import sys
116 import tempfile
117 import weakref
118
119 from mercurial.i18n import _
120 from mercurial.node import hex
121
122 from mercurial import (
123 context,
124 encoding,
125 error,
126 extensions,
127 localrepo,
128 merge,
129 pathutil,
130 pycompat,
131 registrar,
132 scmutil,
133 util,
134 )
135
136 # no-check-code because we're accessing private information only public in pure
137 from mercurial.pure import parsers
138 from mercurial import match as matchmod
139 from mercurial.utils import (
140 hashutil,
141 stringutil,
142 )
143
144 from . import (
145 pywatchman,
146 state,
147 watchmanclient,
148 )
149
150 # Note for extension authors: ONLY specify testedwith = 'ships-with-hg-core' for
151 # extensions which SHIP WITH MERCURIAL. Non-mainline extensions should
152 # be specifying the version(s) of Mercurial they are tested with, or
153 # leave the attribute unspecified.
154 testedwith = b'ships-with-hg-core'
155
156 configtable = {}
157 configitem = registrar.configitem(configtable)
158
159 configitem(
160 b'fsmonitor',
161 b'mode',
162 default=b'on',
163 )
164 configitem(
165 b'fsmonitor',
166 b'walk_on_invalidate',
167 default=False,
168 )
169 configitem(
170 b'fsmonitor',
171 b'timeout',
172 default=b'2',
173 )
174 configitem(
175 b'fsmonitor',
176 b'blacklistusers',
177 default=list,
178 )
179 configitem(
180 b'fsmonitor',
181 b'watchman_exe',
182 default=b'watchman',
183 )
184 configitem(
185 b'fsmonitor',
186 b'verbose',
187 default=True,
188 experimental=True,
189 )
190 configitem(
191 b'experimental',
192 b'fsmonitor.transaction_notify',
193 default=False,
194 )
195
196 # This extension is incompatible with the following blacklisted extensions
197 # and will disable itself when encountering one of these:
198 _blacklist = [b'largefiles', b'eol']
199
200
201 def debuginstall(ui, fm):
202 fm.write(
203 b"fsmonitor-watchman",
204 _(b"fsmonitor checking for watchman binary... (%s)\n"),
205 ui.configpath(b"fsmonitor", b"watchman_exe"),
206 )
207 root = tempfile.mkdtemp()
208 c = watchmanclient.client(ui, root)
209 err = None
210 try:
211 v = c.command(b"version")
212 fm.write(
213 b"fsmonitor-watchman-version",
214 _(b" watchman binary version %s\n"),
215 pycompat.bytestr(v["version"]),
216 )
217 except watchmanclient.Unavailable as e:
218 err = stringutil.forcebytestr(e)
219 fm.condwrite(
220 err,
221 b"fsmonitor-watchman-error",
222 _(b" watchman binary missing or broken: %s\n"),
223 err,
224 )
225 return 1 if err else 0
226
227
228 def _handleunavailable(ui, state, ex):
229 """Exception handler for Watchman interaction exceptions"""
230 if isinstance(ex, watchmanclient.Unavailable):
231 # experimental config: fsmonitor.verbose
232 if ex.warn and ui.configbool(b'fsmonitor', b'verbose'):
233 if b'illegal_fstypes' not in stringutil.forcebytestr(ex):
234 ui.warn(stringutil.forcebytestr(ex) + b'\n')
235 if ex.invalidate:
236 state.invalidate()
237 # experimental config: fsmonitor.verbose
238 if ui.configbool(b'fsmonitor', b'verbose'):
239 ui.log(
240 b'fsmonitor',
241 b'Watchman unavailable: %s\n',
242 stringutil.forcebytestr(ex.msg),
243 )
244 else:
245 ui.log(
246 b'fsmonitor',
247 b'Watchman exception: %s\n',
248 stringutil.forcebytestr(ex),
249 )
250
251
252 def _hashignore(ignore):
253 """Calculate hash for ignore patterns and filenames
254
255 If this information changes between Mercurial invocations, we can't
256 rely on Watchman information anymore and have to re-scan the working
257 copy.
258
259 """
260 sha1 = hashutil.sha1()
261 sha1.update(pycompat.byterepr(ignore))
262 return pycompat.sysbytes(sha1.hexdigest())
263
264
265 _watchmanencoding = pywatchman.encoding.get_local_encoding()
266 _fsencoding = sys.getfilesystemencoding() or sys.getdefaultencoding()
267 _fixencoding = codecs.lookup(_watchmanencoding) != codecs.lookup(_fsencoding)
268
269
270 def _watchmantofsencoding(path):
271 """Fix path to match watchman and local filesystem encoding
272
273 watchman's paths encoding can differ from filesystem encoding. For example,
274 on Windows, it's always utf-8.
275 """
276 try:
277 decoded = path.decode(_watchmanencoding)
278 except UnicodeDecodeError as e:
279 raise error.Abort(
280 stringutil.forcebytestr(e), hint=b'watchman encoding error'
281 )
282
283 try:
284 encoded = decoded.encode(_fsencoding, 'strict')
285 except UnicodeEncodeError as e:
286 raise error.Abort(stringutil.forcebytestr(e))
287
288 return encoded
289
290
291 def overridewalk(orig, self, match, subrepos, unknown, ignored, full=True):
292 """Replacement for dirstate.walk, hooking into Watchman.
293
294 Whenever full is False, ignored is False, and the Watchman client is
295 available, use Watchman combined with saved state to possibly return only a
296 subset of files."""
297
298 def bail(reason):
299 self._ui.debug(b'fsmonitor: fallback to core status, %s\n' % reason)
300 return orig(match, subrepos, unknown, ignored, full=True)
301
302 if full:
303 return bail(b'full rewalk requested')
304 if ignored:
305 return bail(b'listing ignored files')
306 if not self._watchmanclient.available():
307 return bail(b'client unavailable')
308 state = self._fsmonitorstate
309 clock, ignorehash, notefiles = state.get()
310 if not clock:
311 if state.walk_on_invalidate:
312 return bail(b'no clock')
313 # Initial NULL clock value, see
314 # https://facebook.github.io/watchman/docs/clockspec.html
315 clock = b'c:0:0'
316 notefiles = []
317
318 ignore = self._ignore
319 dirignore = self._dirignore
320 if unknown:
321 if _hashignore(ignore) != ignorehash and clock != b'c:0:0':
322 # ignore list changed -- can't rely on Watchman state any more
323 if state.walk_on_invalidate:
324 return bail(b'ignore rules changed')
325 notefiles = []
326 clock = b'c:0:0'
327 else:
328 # always ignore
329 ignore = util.always
330 dirignore = util.always
331
332 matchfn = match.matchfn
333 matchalways = match.always()
334 dmap = self._map
335 if hasattr(dmap, '_map'):
336 # for better performance, directly access the inner dirstate map if the
337 # standard dirstate implementation is in use.
338 dmap = dmap._map
339
340 has_mtime = parsers.DIRSTATE_V2_HAS_MTIME
341 mtime_is_ambiguous = parsers.DIRSTATE_V2_MTIME_SECOND_AMBIGUOUS
342 mask = has_mtime | mtime_is_ambiguous
343
344 # All entries that may not be clean
345 nonnormalset = {
346 f
347 for f, e in self._map.items()
348 if not e.maybe_clean
349 # same as "not has_time or has_ambiguous_time", but factored to only
350 # need a single access to flags for performance.
351 # `mask` removes all irrelevant bits, then we flip the `mtime` bit so
352 # its `true` value is NOT having a mtime, then check if either bit
353 # is set.
354 or bool((e.v2_data()[0] & mask) ^ has_mtime)
355 }
356
357 copymap = self._map.copymap
358 getkind = stat.S_IFMT
359 dirkind = stat.S_IFDIR
360 regkind = stat.S_IFREG
361 lnkkind = stat.S_IFLNK
362 join = self._join
363 normcase = util.normcase
364 fresh_instance = False
365
366 exact = skipstep3 = False
367 if match.isexact(): # match.exact
368 exact = True
369 dirignore = util.always # skip step 2
370 elif match.prefix(): # match.match, no patterns
371 skipstep3 = True
372
373 if not exact and self._checkcase:
374 # note that even though we could receive directory entries, we're only
375 # interested in checking if a file with the same name exists. So only
376 # normalize files if possible.
377 normalize = self._normalizefile
378 skipstep3 = False
379 else:
380 normalize = None
381
382 # step 1: find all explicit files
383 results, work, dirsnotfound = self._walkexplicit(match, subrepos)
384
385 skipstep3 = skipstep3 and not (work or dirsnotfound)
386 work = [d for d in work if not dirignore(d[0])]
387
388 if not work and (exact or skipstep3):
389 for s in subrepos:
390 del results[s]
391 del results[b'.hg']
392 return results
393
394 # step 2: query Watchman
395 try:
396 # Use the user-configured timeout for the query.
397 # Add a little slack over the top of the user query to allow for
398 # overheads while transferring the data
399 self._watchmanclient.settimeout(state.timeout + 0.1)
400 result = self._watchmanclient.command(
401 b'query',
402 {
403 b'fields': [b'mode', b'mtime', b'size', b'exists', b'name'],
404 b'since': clock,
405 b'expression': [
406 b'not',
407 [
408 b'anyof',
409 [b'dirname', b'.hg'],
410 [b'name', b'.hg', b'wholename'],
411 ],
412 ],
413 b'sync_timeout': int(state.timeout * 1000),
414 b'empty_on_fresh_instance': state.walk_on_invalidate,
415 },
416 )
417 except Exception as ex:
418 _handleunavailable(self._ui, state, ex)
419 self._watchmanclient.clearconnection()
420 return bail(b'exception during run')
421 else:
422 # We need to propagate the last observed clock up so that we
423 # can use it for our next query
424 state.setlastclock(pycompat.sysbytes(result[b'clock']))
425 if result[b'is_fresh_instance']:
426 if state.walk_on_invalidate:
427 state.invalidate()
428 return bail(b'fresh instance')
429 fresh_instance = True
430 # Ignore any prior noteable files from the state info
431 notefiles = []
432
433 # for file paths which require normalization and we encounter a case
434 # collision, we store our own foldmap
435 if normalize:
436 foldmap = {normcase(k): k for k in results}
437
438 switch_slashes = pycompat.ossep == b'\\'
439 # The order of the results is, strictly speaking, undefined.
440 # For case changes on a case insensitive filesystem we may receive
441 # two entries, one with exists=True and another with exists=False.
442 # The exists=True entries in the same response should be interpreted
443 # as being happens-after the exists=False entries due to the way that
444 # Watchman tracks files. We use this property to reconcile deletes
445 # for name case changes.
446 for entry in result[b'files']:
447 fname = entry[b'name']
448
449 # Watchman always give us a str. Normalize to bytes on Python 3
450 # using Watchman's encoding, if needed.
451 if not isinstance(fname, bytes):
452 fname = fname.encode(_watchmanencoding)
453
454 if _fixencoding:
455 fname = _watchmantofsencoding(fname)
456
457 if switch_slashes:
458 fname = fname.replace(b'\\', b'/')
459 if normalize:
460 normed = normcase(fname)
461 fname = normalize(fname, True, True)
462 foldmap[normed] = fname
463 fmode = entry[b'mode']
464 fexists = entry[b'exists']
465 kind = getkind(fmode)
466
467 if b'/.hg/' in fname or fname.endswith(b'/.hg'):
468 return bail(b'nested-repo-detected')
469
470 if not fexists:
471 # if marked as deleted and we don't already have a change
472 # record, mark it as deleted. If we already have an entry
473 # for fname then it was either part of walkexplicit or was
474 # an earlier result that was a case change
475 if (
476 fname not in results
477 and fname in dmap
478 and (matchalways or matchfn(fname))
479 ):
480 results[fname] = None
481 elif kind == dirkind:
482 if fname in dmap and (matchalways or matchfn(fname)):
483 results[fname] = None
484 elif kind == regkind or kind == lnkkind:
485 if fname in dmap:
486 if matchalways or matchfn(fname):
487 results[fname] = entry
488 elif (matchalways or matchfn(fname)) and not ignore(fname):
489 results[fname] = entry
490 elif fname in dmap and (matchalways or matchfn(fname)):
491 results[fname] = None
492
493 # step 3: query notable files we don't already know about
494 # XXX try not to iterate over the entire dmap
495 if normalize:
496 # any notable files that have changed case will already be handled
497 # above, so just check membership in the foldmap
498 notefiles = {
499 normalize(f, True, True)
500 for f in notefiles
501 if normcase(f) not in foldmap
502 }
503 visit = {
504 f
505 for f in notefiles
506 if (f not in results and matchfn(f) and (f in dmap or not ignore(f)))
507 }
508
509 if not fresh_instance:
510 if matchalways:
511 visit.update(f for f in nonnormalset if f not in results)
512 visit.update(f for f in copymap if f not in results)
513 else:
514 visit.update(
515 f for f in nonnormalset if f not in results and matchfn(f)
516 )
517 visit.update(f for f in copymap if f not in results and matchfn(f))
518 else:
519 if matchalways:
520 visit.update(f for f, st in dmap.items() if f not in results)
521 visit.update(f for f in copymap if f not in results)
522 else:
523 visit.update(
524 f for f, st in dmap.items() if f not in results and matchfn(f)
525 )
526 visit.update(f for f in copymap if f not in results and matchfn(f))
527
528 audit = pathutil.pathauditor(self._root, cached=True).check
529 auditpass = [f for f in visit if audit(f)]
530 auditpass.sort()
531 auditfail = visit.difference(auditpass)
532 for f in auditfail:
533 results[f] = None
534
535 nf = iter(auditpass)
536 for st in util.statfiles([join(f) for f in auditpass]):
537 f = next(nf)
538 if st or f in dmap:
539 results[f] = st
540
541 for s in subrepos:
542 del results[s]
543 del results[b'.hg']
544 return results
545
546
547 def overridestatus(
548 orig,
549 self,
550 node1=b'.',
551 node2=None,
552 match=None,
553 ignored=False,
554 clean=False,
555 unknown=False,
556 listsubrepos=False,
557 ):
558 listignored = ignored
559 listclean = clean
560 listunknown = unknown
561
562 def _cmpsets(l1, l2):
563 try:
564 if b'FSMONITOR_LOG_FILE' in encoding.environ:
565 fn = encoding.environ[b'FSMONITOR_LOG_FILE']
566 f = open(fn, 'wb')
567 else:
568 fn = b'fsmonitorfail.log'
569 f = self.vfs.open(fn, b'wb')
570 except OSError:
571 self.ui.warn(_(b'warning: unable to write to %s\n') % fn)
572 return
573
574 try:
575 for i, (s1, s2) in enumerate(zip(l1, l2)):
576 if set(s1) != set(s2):
577 f.write(b'sets at position %d are unequal\n' % i)
578 f.write(b'watchman returned: %r\n' % s1)
579 f.write(b'stat returned: %r\n' % s2)
580 finally:
581 f.close()
582
583 if isinstance(node1, context.changectx):
584 ctx1 = node1
585 else:
586 ctx1 = self[node1]
587 if isinstance(node2, context.changectx):
588 ctx2 = node2
589 else:
590 ctx2 = self[node2]
591
592 working = ctx2.rev() is None
593 parentworking = working and ctx1 == self[b'.']
594 match = match or matchmod.always()
595
596 # Maybe we can use this opportunity to update Watchman's state.
597 # Mercurial uses workingcommitctx and/or memctx to represent the part of
598 # the workingctx that is to be committed. So don't update the state in
599 # that case.
600 # HG_PENDING is set in the environment when the dirstate is being updated
601 # in the middle of a transaction; we must not update our state in that
602 # case, or we risk forgetting about changes in the working copy.
603 updatestate = (
604 parentworking
605 and match.always()
606 and not isinstance(ctx2, (context.workingcommitctx, context.memctx))
607 and b'HG_PENDING' not in encoding.environ
608 )
609
610 try:
611 if self._fsmonitorstate.walk_on_invalidate:
612 # Use a short timeout to query the current clock. If that
613 # takes too long then we assume that the service will be slow
614 # to answer our query.
615 # walk_on_invalidate indicates that we prefer to walk the
616 # tree ourselves because we can ignore portions that Watchman
617 # cannot and we tend to be faster in the warmer buffer cache
618 # cases.
619 self._watchmanclient.settimeout(0.1)
620 else:
621 # Give Watchman more time to potentially complete its walk
622 # and return the initial clock. In this mode we assume that
623 # the filesystem will be slower than parsing a potentially
624 # very large Watchman result set.
625 self._watchmanclient.settimeout(self._fsmonitorstate.timeout + 0.1)
626 startclock = self._watchmanclient.getcurrentclock()
627 except Exception as ex:
628 self._watchmanclient.clearconnection()
629 _handleunavailable(self.ui, self._fsmonitorstate, ex)
630 # boo, Watchman failed. bail
631 return orig(
632 node1,
633 node2,
634 match,
635 listignored,
636 listclean,
637 listunknown,
638 listsubrepos,
639 )
640
641 if updatestate:
642 # We need info about unknown files. This may make things slower the
643 # first time, but whatever.
644 stateunknown = True
645 else:
646 stateunknown = listunknown
647
648 if updatestate:
649 ps = poststatus(startclock)
650 self.addpostdsstatus(ps)
651
652 r = orig(
653 node1, node2, match, listignored, listclean, stateunknown, listsubrepos
654 )
655 modified, added, removed, deleted, unknown, ignored, clean = r
656
657 if not listunknown:
658 unknown = []
659
660 # don't do paranoid checks if we're not going to query Watchman anyway
661 full = listclean or match.traversedir is not None
662 if self._fsmonitorstate.mode == b'paranoid' and not full:
663 # run status again and fall back to the old walk this time
664 self.dirstate._fsmonitordisable = True
665
666 # shut the UI up
667 quiet = self.ui.quiet
668 self.ui.quiet = True
669 fout, ferr = self.ui.fout, self.ui.ferr
670
671 with open(os.devnull, 'wb') as fp:
672 self.ui.fout = self.ui.ferr = fp
673
674 try:
675 rv2 = orig(
676 node1,
677 node2,
678 match,
679 listignored,
680 listclean,
681 listunknown,
682 listsubrepos,
683 )
684 finally:
685 self.dirstate._fsmonitordisable = False
686 self.ui.quiet = quiet
687 self.ui.fout, self.ui.ferr = fout, ferr
688
689 # clean isn't tested since it's set to True above
690 with self.wlock():
691 _cmpsets(
692 [modified, added, removed, deleted, unknown, ignored, clean],
693 rv2,
694 )
695 modified, added, removed, deleted, unknown, ignored, clean = rv2
696
697 return scmutil.status(
698 modified, added, removed, deleted, unknown, ignored, clean
699 )
700
701
702 class poststatus:
703 def __init__(self, startclock):
704 self._startclock = pycompat.sysbytes(startclock)
705
706 def __call__(self, wctx, status):
707 clock = wctx.repo()._fsmonitorstate.getlastclock() or self._startclock
708 hashignore = _hashignore(wctx.repo().dirstate._ignore)
709 notefiles = (
710 status.modified
711 + status.added
712 + status.removed
713 + status.deleted
714 + status.unknown
715 )
716 wctx.repo()._fsmonitorstate.set(clock, hashignore, notefiles)
717
718
719 def makedirstate(repo, dirstate):
720 class fsmonitordirstate(dirstate.__class__):
721 def _fsmonitorinit(self, repo):
722 # _fsmonitordisable is used in paranoid mode
723 self._fsmonitordisable = False
724 self._fsmonitorstate = repo._fsmonitorstate
725 self._watchmanclient = repo._watchmanclient
726 self._repo = weakref.proxy(repo)
727
728 def walk(self, *args, **kwargs):
729 orig = super().walk
730 if self._fsmonitordisable:
731 return orig(*args, **kwargs)
732 return overridewalk(orig, self, *args, **kwargs)
733
734 def rebuild(self, *args, **kwargs):
735 self._fsmonitorstate.invalidate()
736 return super().rebuild(*args, **kwargs)
737
738 def invalidate(self, *args, **kwargs):
739 self._fsmonitorstate.invalidate()
740 return super().invalidate(*args, **kwargs)
741
742 dirstate.__class__ = fsmonitordirstate
743 dirstate._fsmonitorinit(repo)
744
745
746 def wrapdirstate(orig, self):
747 ds = orig(self)
748 # only override the dirstate when Watchman is available for the repo
749 if hasattr(self, '_fsmonitorstate'):
750 makedirstate(self, ds)
751 return ds
752
753
754 def extsetup(ui):
755 extensions.wrapfilecache(
756 localrepo.localrepository, b'dirstate', wrapdirstate
757 )
758 if pycompat.isdarwin:
759 # An assist for avoiding the dangling-symlink fsevents bug
760 extensions.wrapfunction(os, 'symlink', wrapsymlink)
761
762 extensions.wrapfunction(merge, '_update', wrapupdate)
763 merge._fs_monitor_loaded = True
764
765
766 def wrapsymlink(orig, source, link_name):
767 """if we create a dangling symlink, also touch the parent dir
768 to encourage fsevents notifications to work more correctly"""
769 try:
770 return orig(source, link_name)
771 finally:
772 try:
773 os.utime(os.path.dirname(link_name), None)
774 except OSError:
775 pass
776
777
778 class state_update:
779 """This context manager is responsible for dispatching the state-enter
780 and state-leave signals to the watchman service. The enter and leave
781 methods can be invoked manually (for scenarios where context manager
782 semantics are not possible). If parameters oldnode and newnode are None,
783 they will be populated based on current working copy in enter and
784 leave, respectively. Similarly, if the distance is none, it will be
785 calculated based on the oldnode and newnode in the leave method."""
786
787 def __init__(
788 self,
789 repo,
790 name,
791 oldnode=None,
792 newnode=None,
793 distance=None,
794 partial=False,
795 ):
796 self.repo = repo.unfiltered()
797 self.name = name
798 self.oldnode = oldnode
799 self.newnode = newnode
800 self.distance = distance
801 self.partial = partial
802 self._lock = None
803 self.need_leave = False
804
805 def __enter__(self):
806 self.enter()
807
808 def enter(self):
809 # Make sure we have a wlock prior to sending notifications to watchman.
810 # We don't want to race with other actors. In the update case,
811 # merge.update is going to take the wlock almost immediately. We are
812 # effectively extending the lock around several short sanity checks.
813 if self.oldnode is None:
814 self.oldnode = self.repo[b'.'].node()
815
816 if self.repo.currentwlock() is None:
817 if hasattr(self.repo, 'wlocknostateupdate'):
818 self._lock = self.repo.wlocknostateupdate()
819 else:
820 self._lock = self.repo.wlock()
821 self.need_leave = self._state(b'state-enter', hex(self.oldnode))
822 return self
823
824 def __exit__(self, type_, value, tb):
825 abort = True if type_ else False
826 self.exit(abort=abort)
827
828 def exit(self, abort=False):
829 try:
830 if self.need_leave:
831 status = b'failed' if abort else b'ok'
832 if self.newnode is None:
833 self.newnode = self.repo[b'.'].node()
834 if self.distance is None:
835 self.distance = calcdistance(
836 self.repo, self.oldnode, self.newnode
837 )
838 self._state(b'state-leave', hex(self.newnode), status=status)
839 finally:
840 self.need_leave = False
841 if self._lock:
842 self._lock.release()
843
844 def _state(self, cmd, commithash, status=b'ok'):
845 if not hasattr(self.repo, '_watchmanclient'):
846 return False
847 try:
848 self.repo._watchmanclient.command(
849 cmd,
850 {
851 b'name': self.name,
852 b'metadata': {
853 # the target revision
854 b'rev': commithash,
855 # approximate number of commits between current and target
856 b'distance': self.distance if self.distance else 0,
857 # success/failure (only really meaningful for state-leave)
858 b'status': status,
859 # whether the working copy parent is changing
860 b'partial': self.partial,
861 },
862 },
863 )
864 return True
865 except Exception as e:
866 # Swallow any errors; fire and forget
867 self.repo.ui.log(
868 b'watchman', b'Exception %s while running %s\n', e, cmd
869 )
870 return False
871
872
873 # Estimate the distance between two nodes
874 def calcdistance(repo, oldnode, newnode):
875 anc = repo.changelog.ancestor(oldnode, newnode)
876 ancrev = repo[anc].rev()
877 distance = abs(repo[oldnode].rev() - ancrev) + abs(
878 repo[newnode].rev() - ancrev
879 )
880 return distance
881
882
883 # Bracket working copy updates with calls to the watchman state-enter
884 # and state-leave commands. This allows clients to perform more intelligent
885 # settling during bulk file change scenarios
886 # https://facebook.github.io/watchman/docs/cmd/subscribe.html#advanced-settling
887 def wrapupdate(
888 orig,
889 repo,
890 node,
891 branchmerge,
892 force,
893 ancestor=None,
894 mergeancestor=False,
895 labels=None,
896 matcher=None,
897 **kwargs,
898 ):
899 distance = 0
900 partial = True
901 oldnode = repo[b'.'].node()
902 newnode = repo[node].node()
903 if matcher is None or matcher.always():
904 partial = False
905 distance = calcdistance(repo.unfiltered(), oldnode, newnode)
906
907 with state_update(
908 repo,
909 name=b"hg.update",
910 oldnode=oldnode,
911 newnode=newnode,
912 distance=distance,
913 partial=partial,
914 ):
915 return orig(
916 repo,
917 node,
918 branchmerge,
919 force,
920 ancestor,
921 mergeancestor,
922 labels,
923 matcher,
924 **kwargs,
925 )
926
927
928 def repo_has_depth_one_nested_repo(repo):
929 for f in repo.wvfs.listdir():
930 if os.path.isdir(os.path.join(repo.root, f, b'.hg')):
931 msg = b'fsmonitor: sub-repository %r detected, fsmonitor disabled\n'
932 repo.ui.debug(msg % f)
933 return True
934 return False
935
936
937 def reposetup(ui, repo):
938 # We don't work with largefiles or inotify
939 exts = extensions.enabled()
940 for ext in _blacklist:
941 if ext in exts:
942 ui.warn(
943 _(
944 b'The fsmonitor extension is incompatible with the %s '
945 b'extension and has been disabled.\n'
946 )
947 % ext
948 )
949 return
950
951 if repo.local():
952 # We don't work with subrepos either.
953 #
954 # if repo[None].substate can cause a dirstate parse, which is too
955 # slow. Instead, look for a file called hgsubstate,
956 if repo.wvfs.exists(b'.hgsubstate') or repo.wvfs.exists(b'.hgsub'):
957 return
958
959 if repo_has_depth_one_nested_repo(repo):
960 return
961
962 fsmonitorstate = state.state(repo)
963 if fsmonitorstate.mode == b'off':
964 return
965
966 try:
967 client = watchmanclient.client(repo.ui, repo.root)
968 except Exception as ex:
969 _handleunavailable(ui, fsmonitorstate, ex)
970 return
971
972 repo._fsmonitorstate = fsmonitorstate
973 repo._watchmanclient = client
974
975 dirstate, cached = localrepo.isfilecached(repo, b'dirstate')
976 if cached:
977 # at this point since fsmonitorstate wasn't present,
978 # repo.dirstate is not a fsmonitordirstate
979 makedirstate(repo, dirstate)
980
981 class fsmonitorrepo(repo.__class__):
982 def status(self, *args, **kwargs):
983 orig = super().status
984 return overridestatus(orig, self, *args, **kwargs)
985
986 def wlocknostateupdate(self, *args, **kwargs):
987 return super().wlock(*args, **kwargs)
988
989 def wlock(self, *args, **kwargs):
990 l = super().wlock(*args, **kwargs)
991 if not ui.configbool(
992 b"experimental", b"fsmonitor.transaction_notify"
993 ):
994 return l
995 if l.held != 1:
996 return l
997 origrelease = l.releasefn
998
999 def staterelease():
1000 if origrelease:
1001 origrelease()
1002 if l.stateupdate:
1003 l.stateupdate.exit()
1004 l.stateupdate = None
1005
1006 try:
1007 l.stateupdate = None
1008 l.stateupdate = state_update(self, name=b"hg.transaction")
1009 l.stateupdate.enter()
1010 l.releasefn = staterelease
1011 except Exception as e:
1012 # Swallow any errors; fire and forget
1013 self.ui.log(
1014 b'watchman', b'Exception in state update %s\n', e
1015 )
1016 return l
1017
1018 repo.__class__ = fsmonitorrepo