diff hgext/fsmonitor/__init__.py @ 43077:687b865b95ad

formatting: byteify all mercurial/ and hgext/ string literals Done with python3.7 contrib/byteify-strings.py -i $(hg files 'set:mercurial/**.py - mercurial/thirdparty/** + hgext/**.py - hgext/fsmonitor/pywatchman/** - mercurial/__init__.py') black -l 80 -t py33 -S $(hg files 'set:**.py - mercurial/thirdparty/** - "contrib/python-zstandard/**" - hgext/fsmonitor/pywatchman/**') # skip-blame mass-reformatting only Differential Revision: https://phab.mercurial-scm.org/D6972
author Augie Fackler <augie@google.com>
date Sun, 06 Oct 2019 09:48:39 -0400
parents 2372284d9457
children eef9a2d67051
line wrap: on
line diff
--- a/hgext/fsmonitor/__init__.py	Sun Oct 06 09:45:02 2019 -0400
+++ b/hgext/fsmonitor/__init__.py	Sun Oct 06 09:48:39 2019 -0400
@@ -143,60 +143,60 @@
 # extensions which SHIP WITH MERCURIAL. Non-mainline extensions should
 # be specifying the version(s) of Mercurial they are tested with, or
 # leave the attribute unspecified.
-testedwith = 'ships-with-hg-core'
+testedwith = b'ships-with-hg-core'
 
 configtable = {}
 configitem = registrar.configitem(configtable)
 
 configitem(
-    'fsmonitor', 'mode', default='on',
+    b'fsmonitor', b'mode', default=b'on',
 )
 configitem(
-    'fsmonitor', 'walk_on_invalidate', default=False,
+    b'fsmonitor', b'walk_on_invalidate', default=False,
 )
 configitem(
-    'fsmonitor', 'timeout', default='2',
+    b'fsmonitor', b'timeout', default=b'2',
 )
 configitem(
-    'fsmonitor', 'blacklistusers', default=list,
+    b'fsmonitor', b'blacklistusers', default=list,
 )
 configitem(
-    'fsmonitor', 'watchman_exe', default='watchman',
+    b'fsmonitor', b'watchman_exe', default=b'watchman',
 )
 configitem(
-    'fsmonitor', 'verbose', default=True, experimental=True,
+    b'fsmonitor', b'verbose', default=True, experimental=True,
 )
 configitem(
-    'experimental', 'fsmonitor.transaction_notify', default=False,
+    b'experimental', b'fsmonitor.transaction_notify', default=False,
 )
 
 # This extension is incompatible with the following blacklisted extensions
 # and will disable itself when encountering one of these:
-_blacklist = ['largefiles', 'eol']
+_blacklist = [b'largefiles', b'eol']
 
 
 def debuginstall(ui, fm):
     fm.write(
-        "fsmonitor-watchman",
-        _("fsmonitor checking for watchman binary... (%s)\n"),
-        ui.configpath("fsmonitor", "watchman_exe"),
+        b"fsmonitor-watchman",
+        _(b"fsmonitor checking for watchman binary... (%s)\n"),
+        ui.configpath(b"fsmonitor", b"watchman_exe"),
     )
     root = tempfile.mkdtemp()
     c = watchmanclient.client(ui, root)
     err = None
     try:
-        v = c.command("version")
+        v = c.command(b"version")
         fm.write(
-            "fsmonitor-watchman-version",
-            _(" watchman binary version %s\n"),
-            v["version"],
+            b"fsmonitor-watchman-version",
+            _(b" watchman binary version %s\n"),
+            v[b"version"],
         )
     except watchmanclient.Unavailable as e:
         err = str(e)
     fm.condwrite(
         err,
-        "fsmonitor-watchman-error",
-        _(" watchman binary missing or broken: %s\n"),
+        b"fsmonitor-watchman-error",
+        _(b" watchman binary missing or broken: %s\n"),
         err,
     )
     return 1 if err else 0
@@ -206,16 +206,16 @@
     """Exception handler for Watchman interaction exceptions"""
     if isinstance(ex, watchmanclient.Unavailable):
         # experimental config: fsmonitor.verbose
-        if ex.warn and ui.configbool('fsmonitor', 'verbose'):
-            if 'illegal_fstypes' not in str(ex):
-                ui.warn(str(ex) + '\n')
+        if ex.warn and ui.configbool(b'fsmonitor', b'verbose'):
+            if b'illegal_fstypes' not in str(ex):
+                ui.warn(str(ex) + b'\n')
         if ex.invalidate:
             state.invalidate()
         # experimental config: fsmonitor.verbose
-        if ui.configbool('fsmonitor', 'verbose'):
-            ui.log('fsmonitor', 'Watchman unavailable: %s\n', ex.msg)
+        if ui.configbool(b'fsmonitor', b'verbose'):
+            ui.log(b'fsmonitor', b'Watchman unavailable: %s\n', ex.msg)
     else:
-        ui.log('fsmonitor', 'Watchman exception: %s\n', ex)
+        ui.log(b'fsmonitor', b'Watchman exception: %s\n', ex)
 
 
 def _hashignore(ignore):
@@ -245,7 +245,7 @@
     try:
         decoded = path.decode(_watchmanencoding)
     except UnicodeDecodeError as e:
-        raise error.Abort(str(e), hint='watchman encoding error')
+        raise error.Abort(str(e), hint=b'watchman encoding error')
 
     try:
         encoded = decoded.encode(_fsencoding, 'strict')
@@ -263,34 +263,34 @@
     subset of files.'''
 
     def bail(reason):
-        self._ui.debug('fsmonitor: fallback to core status, %s\n' % reason)
+        self._ui.debug(b'fsmonitor: fallback to core status, %s\n' % reason)
         return orig(match, subrepos, unknown, ignored, full=True)
 
     if full:
-        return bail('full rewalk requested')
+        return bail(b'full rewalk requested')
     if ignored:
-        return bail('listing ignored files')
+        return bail(b'listing ignored files')
     if not self._watchmanclient.available():
-        return bail('client unavailable')
+        return bail(b'client unavailable')
     state = self._fsmonitorstate
     clock, ignorehash, notefiles = state.get()
     if not clock:
         if state.walk_on_invalidate:
-            return bail('no clock')
+            return bail(b'no clock')
         # Initial NULL clock value, see
         # https://facebook.github.io/watchman/docs/clockspec.html
-        clock = 'c:0:0'
+        clock = b'c:0:0'
         notefiles = []
 
     ignore = self._ignore
     dirignore = self._dirignore
     if unknown:
-        if _hashignore(ignore) != ignorehash and clock != 'c:0:0':
+        if _hashignore(ignore) != ignorehash and clock != b'c:0:0':
             # ignore list changed -- can't rely on Watchman state any more
             if state.walk_on_invalidate:
-                return bail('ignore rules changed')
+                return bail(b'ignore rules changed')
             notefiles = []
-            clock = 'c:0:0'
+            clock = b'c:0:0'
     else:
         # always ignore
         ignore = util.always
@@ -299,7 +299,7 @@
     matchfn = match.matchfn
     matchalways = match.always()
     dmap = self._map
-    if util.safehasattr(dmap, '_map'):
+    if util.safehasattr(dmap, b'_map'):
         # for better performance, directly access the inner dirstate map if the
         # standard dirstate implementation is in use.
         dmap = dmap._map
@@ -339,7 +339,7 @@
     if not work and (exact or skipstep3):
         for s in subrepos:
             del results[s]
-        del results['.hg']
+        del results[b'.hg']
         return results
 
     # step 2: query Watchman
@@ -349,30 +349,34 @@
         # overheads while transferring the data
         self._watchmanclient.settimeout(state.timeout + 0.1)
         result = self._watchmanclient.command(
-            'query',
+            b'query',
             {
-                'fields': ['mode', 'mtime', 'size', 'exists', 'name'],
-                'since': clock,
-                'expression': [
-                    'not',
-                    ['anyof', ['dirname', '.hg'], ['name', '.hg', 'wholename']],
+                b'fields': [b'mode', b'mtime', b'size', b'exists', b'name'],
+                b'since': clock,
+                b'expression': [
+                    b'not',
+                    [
+                        b'anyof',
+                        [b'dirname', b'.hg'],
+                        [b'name', b'.hg', b'wholename'],
+                    ],
                 ],
-                'sync_timeout': int(state.timeout * 1000),
-                'empty_on_fresh_instance': state.walk_on_invalidate,
+                b'sync_timeout': int(state.timeout * 1000),
+                b'empty_on_fresh_instance': state.walk_on_invalidate,
             },
         )
     except Exception as ex:
         _handleunavailable(self._ui, state, ex)
         self._watchmanclient.clearconnection()
-        return bail('exception during run')
+        return bail(b'exception during run')
     else:
         # We need to propagate the last observed clock up so that we
         # can use it for our next query
-        state.setlastclock(result['clock'])
-        if result['is_fresh_instance']:
+        state.setlastclock(result[b'clock'])
+        if result[b'is_fresh_instance']:
             if state.walk_on_invalidate:
                 state.invalidate()
-                return bail('fresh instance')
+                return bail(b'fresh instance')
             fresh_instance = True
             # Ignore any prior noteable files from the state info
             notefiles = []
@@ -382,7 +386,7 @@
     if normalize:
         foldmap = dict((normcase(k), k) for k in results)
 
-    switch_slashes = pycompat.ossep == '\\'
+    switch_slashes = pycompat.ossep == b'\\'
     # The order of the results is, strictly speaking, undefined.
     # For case changes on a case insensitive filesystem we may receive
     # two entries, one with exists=True and another with exists=False.
@@ -390,22 +394,22 @@
     # as being happens-after the exists=False entries due to the way that
     # Watchman tracks files.  We use this property to reconcile deletes
     # for name case changes.
-    for entry in result['files']:
-        fname = entry['name']
+    for entry in result[b'files']:
+        fname = entry[b'name']
         if _fixencoding:
             fname = _watchmantofsencoding(fname)
         if switch_slashes:
-            fname = fname.replace('\\', '/')
+            fname = fname.replace(b'\\', b'/')
         if normalize:
             normed = normcase(fname)
             fname = normalize(fname, True, True)
             foldmap[normed] = fname
-        fmode = entry['mode']
-        fexists = entry['exists']
+        fmode = entry[b'mode']
+        fexists = entry[b'exists']
         kind = getkind(fmode)
 
-        if '/.hg/' in fname or fname.endswith('/.hg'):
-            return bail('nested-repo-detected')
+        if b'/.hg/' in fname or fname.endswith(b'/.hg'):
+            return bail(b'nested-repo-detected')
 
         if not fexists:
             # if marked as deleted and we don't already have a change
@@ -488,14 +492,14 @@
 
     for s in subrepos:
         del results[s]
-    del results['.hg']
+    del results[b'.hg']
     return results
 
 
 def overridestatus(
     orig,
     self,
-    node1='.',
+    node1=b'.',
     node2=None,
     match=None,
     ignored=False,
@@ -509,22 +513,22 @@
 
     def _cmpsets(l1, l2):
         try:
-            if 'FSMONITOR_LOG_FILE' in encoding.environ:
-                fn = encoding.environ['FSMONITOR_LOG_FILE']
-                f = open(fn, 'wb')
+            if b'FSMONITOR_LOG_FILE' in encoding.environ:
+                fn = encoding.environ[b'FSMONITOR_LOG_FILE']
+                f = open(fn, b'wb')
             else:
-                fn = 'fsmonitorfail.log'
-                f = self.vfs.open(fn, 'wb')
+                fn = b'fsmonitorfail.log'
+                f = self.vfs.open(fn, b'wb')
         except (IOError, OSError):
-            self.ui.warn(_('warning: unable to write to %s\n') % fn)
+            self.ui.warn(_(b'warning: unable to write to %s\n') % fn)
             return
 
         try:
             for i, (s1, s2) in enumerate(zip(l1, l2)):
                 if set(s1) != set(s2):
-                    f.write('sets at position %d are unequal\n' % i)
-                    f.write('watchman returned: %s\n' % s1)
-                    f.write('stat returned: %s\n' % s2)
+                    f.write(b'sets at position %d are unequal\n' % i)
+                    f.write(b'watchman returned: %s\n' % s1)
+                    f.write(b'stat returned: %s\n' % s2)
         finally:
             f.close()
 
@@ -538,7 +542,7 @@
         ctx2 = self[node2]
 
     working = ctx2.rev() is None
-    parentworking = working and ctx1 == self['.']
+    parentworking = working and ctx1 == self[b'.']
     match = match or matchmod.always()
 
     # Maybe we can use this opportunity to update Watchman's state.
@@ -552,7 +556,7 @@
         parentworking
         and match.always()
         and not isinstance(ctx2, (context.workingcommitctx, context.memctx))
-        and 'HG_PENDING' not in encoding.environ
+        and b'HG_PENDING' not in encoding.environ
     )
 
     try:
@@ -607,7 +611,7 @@
 
     # don't do paranoid checks if we're not going to query Watchman anyway
     full = listclean or match.traversedir is not None
-    if self._fsmonitorstate.mode == 'paranoid' and not full:
+    if self._fsmonitorstate.mode == b'paranoid' and not full:
         # run status again and fall back to the old walk this time
         self.dirstate._fsmonitordisable = True
 
@@ -615,7 +619,7 @@
         quiet = self.ui.quiet
         self.ui.quiet = True
         fout, ferr = self.ui.fout, self.ui.ferr
-        self.ui.fout = self.ui.ferr = open(os.devnull, 'wb')
+        self.ui.fout = self.ui.ferr = open(os.devnull, b'wb')
 
         try:
             rv2 = orig(
@@ -692,20 +696,20 @@
 def wrapdirstate(orig, self):
     ds = orig(self)
     # only override the dirstate when Watchman is available for the repo
-    if util.safehasattr(self, '_fsmonitorstate'):
+    if util.safehasattr(self, b'_fsmonitorstate'):
         makedirstate(self, ds)
     return ds
 
 
 def extsetup(ui):
     extensions.wrapfilecache(
-        localrepo.localrepository, 'dirstate', wrapdirstate
+        localrepo.localrepository, b'dirstate', wrapdirstate
     )
     if pycompat.isdarwin:
         # An assist for avoiding the dangling-symlink fsevents bug
-        extensions.wrapfunction(os, 'symlink', wrapsymlink)
+        extensions.wrapfunction(os, b'symlink', wrapsymlink)
 
-    extensions.wrapfunction(merge, 'update', wrapupdate)
+    extensions.wrapfunction(merge, b'update', wrapupdate)
 
 
 def wrapsymlink(orig, source, link_name):
@@ -756,14 +760,14 @@
         # merge.update is going to take the wlock almost immediately. We are
         # effectively extending the lock around several short sanity checks.
         if self.oldnode is None:
-            self.oldnode = self.repo['.'].node()
+            self.oldnode = self.repo[b'.'].node()
 
         if self.repo.currentwlock() is None:
-            if util.safehasattr(self.repo, 'wlocknostateupdate'):
+            if util.safehasattr(self.repo, b'wlocknostateupdate'):
                 self._lock = self.repo.wlocknostateupdate()
             else:
                 self._lock = self.repo.wlock()
-        self.need_leave = self._state('state-enter', hex(self.oldnode))
+        self.need_leave = self._state(b'state-enter', hex(self.oldnode))
         return self
 
     def __exit__(self, type_, value, tb):
@@ -773,36 +777,36 @@
     def exit(self, abort=False):
         try:
             if self.need_leave:
-                status = 'failed' if abort else 'ok'
+                status = b'failed' if abort else b'ok'
                 if self.newnode is None:
-                    self.newnode = self.repo['.'].node()
+                    self.newnode = self.repo[b'.'].node()
                 if self.distance is None:
                     self.distance = calcdistance(
                         self.repo, self.oldnode, self.newnode
                     )
-                self._state('state-leave', hex(self.newnode), status=status)
+                self._state(b'state-leave', hex(self.newnode), status=status)
         finally:
             self.need_leave = False
             if self._lock:
                 self._lock.release()
 
-    def _state(self, cmd, commithash, status='ok'):
-        if not util.safehasattr(self.repo, '_watchmanclient'):
+    def _state(self, cmd, commithash, status=b'ok'):
+        if not util.safehasattr(self.repo, b'_watchmanclient'):
             return False
         try:
             self.repo._watchmanclient.command(
                 cmd,
                 {
-                    'name': self.name,
-                    'metadata': {
+                    b'name': self.name,
+                    b'metadata': {
                         # the target revision
-                        'rev': commithash,
+                        b'rev': commithash,
                         # approximate number of commits between current and target
-                        'distance': self.distance if self.distance else 0,
+                        b'distance': self.distance if self.distance else 0,
                         # success/failure (only really meaningful for state-leave)
-                        'status': status,
+                        b'status': status,
                         # whether the working copy parent is changing
-                        'partial': self.partial,
+                        b'partial': self.partial,
                     },
                 },
             )
@@ -810,7 +814,7 @@
         except Exception as e:
             # Swallow any errors; fire and forget
             self.repo.ui.log(
-                'watchman', 'Exception %s while running %s\n', e, cmd
+                b'watchman', b'Exception %s while running %s\n', e, cmd
             )
             return False
 
@@ -844,7 +848,7 @@
 
     distance = 0
     partial = True
-    oldnode = repo['.'].node()
+    oldnode = repo[b'.'].node()
     newnode = repo[node].node()
     if matcher is None or matcher.always():
         partial = False
@@ -852,7 +856,7 @@
 
     with state_update(
         repo,
-        name="hg.update",
+        name=b"hg.update",
         oldnode=oldnode,
         newnode=newnode,
         distance=distance,
@@ -873,8 +877,8 @@
 
 def repo_has_depth_one_nested_repo(repo):
     for f in repo.wvfs.listdir():
-        if os.path.isdir(os.path.join(repo.root, f, '.hg')):
-            msg = 'fsmonitor: sub-repository %r detected, fsmonitor disabled\n'
+        if os.path.isdir(os.path.join(repo.root, f, b'.hg')):
+            msg = b'fsmonitor: sub-repository %r detected, fsmonitor disabled\n'
             repo.ui.debug(msg % f)
             return True
     return False
@@ -887,8 +891,8 @@
         if ext in exts:
             ui.warn(
                 _(
-                    'The fsmonitor extension is incompatible with the %s '
-                    'extension and has been disabled.\n'
+                    b'The fsmonitor extension is incompatible with the %s '
+                    b'extension and has been disabled.\n'
                 )
                 % ext
             )
@@ -899,14 +903,14 @@
         #
         # if repo[None].substate can cause a dirstate parse, which is too
         # slow. Instead, look for a file called hgsubstate,
-        if repo.wvfs.exists('.hgsubstate') or repo.wvfs.exists('.hgsub'):
+        if repo.wvfs.exists(b'.hgsubstate') or repo.wvfs.exists(b'.hgsub'):
             return
 
         if repo_has_depth_one_nested_repo(repo):
             return
 
         fsmonitorstate = state.state(repo)
-        if fsmonitorstate.mode == 'off':
+        if fsmonitorstate.mode == b'off':
             return
 
         try:
@@ -918,7 +922,7 @@
         repo._fsmonitorstate = fsmonitorstate
         repo._watchmanclient = client
 
-        dirstate, cached = localrepo.isfilecached(repo, 'dirstate')
+        dirstate, cached = localrepo.isfilecached(repo, b'dirstate')
         if cached:
             # at this point since fsmonitorstate wasn't present,
             # repo.dirstate is not a fsmonitordirstate
@@ -935,7 +939,7 @@
             def wlock(self, *args, **kwargs):
                 l = super(fsmonitorrepo, self).wlock(*args, **kwargs)
                 if not ui.configbool(
-                    "experimental", "fsmonitor.transaction_notify"
+                    b"experimental", b"fsmonitor.transaction_notify"
                 ):
                     return l
                 if l.held != 1:
@@ -951,12 +955,14 @@
 
                 try:
                     l.stateupdate = None
-                    l.stateupdate = state_update(self, name="hg.transaction")
+                    l.stateupdate = state_update(self, name=b"hg.transaction")
                     l.stateupdate.enter()
                     l.releasefn = staterelease
                 except Exception as e:
                     # Swallow any errors; fire and forget
-                    self.ui.log('watchman', 'Exception in state update %s\n', e)
+                    self.ui.log(
+                        b'watchman', b'Exception in state update %s\n', e
+                    )
                 return l
 
         repo.__class__ = fsmonitorrepo