changeset 135:298fa524406a

Update to latest HG Prompt and make it Python 3 compliant
author IBBoard <dev@ibboard.co.uk>
date Sat, 04 Jan 2020 20:09:53 +0000
parents 3448a8c33716
children fcd34011b0f0
files prompt.py
diffstat 1 files changed, 12 insertions(+), 141 deletions(-) [+]
line wrap: on
line diff
--- a/prompt.py	Sat Jan 04 19:41:32 2020 +0000
+++ b/prompt.py	Sat Jan 04 20:09:53 2020 +0000
@@ -7,9 +7,7 @@
 Useful mostly for putting information about the current repository into
 a shell prompt.
 
-
-
-Taken from https://bitbucket.org/sjl/hg-prompt/src @ 5334581
+https://hg.sr.ht/~sjl/hg-prompt/browse/default/prompt.py @ 9f0b70dfcf52
 '''
 
 from __future__ import with_statement
@@ -24,8 +22,13 @@
 from mercurial.i18n import _
 from mercurial.node import hex, short
 
+# command registration moved into `registrar` module in v4.3.
 cmdtable = {}
-command = cmdutil.command(cmdtable)
+try:
+    from mercurial import registrar
+    command = registrar.command(cmdtable)
+except (ImportError, AttributeError) as e:
+    command = cmdutil.command(cmdtable)
 
 # `revrange' has been moved into module `scmutil' since v1.9.
 try :
@@ -34,43 +37,14 @@
 except :
     revrange = cmdutil.revrange
 
-CACHE_PATH = ".hg/prompt/cache"
-CACHE_TIMEOUT = timedelta(minutes=15)
-
 FILTER_ARG = re.compile(r'\|.+\((.*)\)')
 
 
-def _cache_remote(repo, kind):
-    cache = path.join(repo.root, CACHE_PATH, kind)
-    c_tmp = cache + '.temp'
-
-    popenargs = ['hg', kind, '--quiet']
-    remote_path = repo.ui.config('prompt', 'remote')
-    if remote_path is not None:
-        popenargs.append(remote_path)
-
-    null_path = 'NUL:' if subprocess.mswindows else '/dev/null'
-    with open(null_path, 'w') as null_fp:
-        with open(c_tmp, 'w') as stdout_fp:
-            exit_code = subprocess.call(popenargs, stdout=stdout_fp, stderr=null_fp)
-
-    if exit_code not in (0, 1): # (changesets_found, changesets_not_found)
-        msg = "hg-prompt error: "
-        if remote_path: # Failure likely due to bad remote. Is 255 a valid check?
-            msg += "Can't access remote '%s'" % remote_path
-        else:
-            msg += "Error attempting 'hg %s'" % kind
-        print msg
-
-    os.rename(c_tmp, cache)
-    return
-
-
 def _with_groups(groups, out):
     out_groups = [groups[0]] + [groups[-1]]
 
     if any(out_groups) and not all(out_groups):
-        print 'Error parsing prompt string.  Mismatched braces?'
+        print('Error parsing prompt string.  Mismatched braces?')
 
     out = out.replace('%', '%%')
     return ("%s" + out + "%s") % (out_groups[0][:-1] if out_groups[0] else '',
@@ -97,11 +71,9 @@
     else:
         return None
 
-@command('prompt',
-         [('', 'angle-brackets', None, 'use angle brackets (<>) for keywords'),
-          ('', 'cache-incoming', None, 'used internally by hg-prompt'),
-          ('', 'cache-outgoing', None, 'used internally by hg-prompt')],
-         'hg prompt STRING')
+@command(b'prompt',
+         [(b'', b'angle-brackets', None, b'use angle brackets (<>) for keywords')],
+         b'hg prompt STRING')
 def prompt(ui, repo, fs='', **opts):
     '''get repository information for use in a shell prompt
 
@@ -292,36 +264,6 @@
 
         return _with_groups(g, out) if out else ''
 
-    def _remote(kind):
-        def _r(m):
-            g = m.groups()
-
-            cache_dir = path.join(repo.root, CACHE_PATH)
-            cache = path.join(cache_dir, kind)
-            if not path.isdir(cache_dir):
-                os.makedirs(cache_dir)
-
-            cache_exists = path.isfile(cache)
-
-            cache_time = (datetime.fromtimestamp(os.stat(cache).st_mtime)
-                          if cache_exists else None)
-            if not cache_exists or cache_time < datetime.now() - CACHE_TIMEOUT:
-                if not cache_exists:
-                    open(cache, 'w').close()
-                subprocess.Popen(['hg', 'prompt', '--cache-%s' % kind])
-
-            if cache_exists:
-                with open(cache) as c:
-                    count = len(c.readlines())
-                    if g[1]:
-                        return _with_groups(g, str(count)) if count else ''
-                    elif g[2]:
-                        return _with_groups(g, '0') if not count else ''
-                    else:
-                        return _with_groups(g, '')
-            else:
-                return ''
-        return _r
 
     def _rev(m):
         g = m.groups()
@@ -455,24 +397,9 @@
             '(\|node)'
             '|(\|short)'
             ')*': _tip,
-        'update': _update,
-
-        'incoming(?:'
-            '(\|count)'
-            '|(\|zero)'
-            ')*': _remote('incoming'),
-        'outgoing(?:'
-            '(\|count)'
-            '|(\|zero)'
-            ')*': _remote('outgoing')
+        'update': _update
     }
 
-    if opts.get("cache_incoming"):
-        _cache_remote(repo, 'incoming')
-
-    if opts.get("cache_outgoing"):
-        _cache_remote(repo, 'outgoing')
-
     if not fs:
         fs = repo.ui.config("prompt", "template", "")
 
@@ -480,30 +407,6 @@
         fs = re.sub(tag_start + tag + tag_end, repl, fs)
     ui.status(fs)
 
-def _pull_with_cache(orig, ui, repo, *args, **opts):
-    """Wrap the pull command to delete the incoming cache as well."""
-    res = orig(ui, repo, *args, **opts)
-    cache = path.join(repo.root, CACHE_PATH, 'incoming')
-    if path.isfile(cache):
-        os.remove(cache)
-    return res
-
-def _push_with_cache(orig, ui, repo, *args, **opts):
-    """Wrap the push command to delete the outgoing cache as well."""
-    res = orig(ui, repo, *args, **opts)
-    cache = path.join(repo.root, CACHE_PATH, 'outgoing')
-    if path.isfile(cache):
-        os.remove(cache)
-    return res
-
-def uisetup(ui):
-    extensions.wrapcommand(commands.table, 'pull', _pull_with_cache)
-    extensions.wrapcommand(commands.table, 'push', _push_with_cache)
-    try:
-        extensions.wrapcommand(extensions.find("fetch").cmdtable, 'fetch', _pull_with_cache)
-    except KeyError:
-        pass
-
 help.helptable += (
     (['prompt-keywords'], _('Keywords supported by hg-prompt'),
      lambda _: r'''hg-prompt currently supports a number of keywords.
@@ -533,22 +436,6 @@
      |REVSET
          The revset to count.
 
-incoming
-     Display nothing, but if the default path contains incoming changesets the
-     extra text will be expanded.
-
-     For example: `{incoming changes{incoming}}` will expand to
-     `incoming changes` if there are changes, otherwise nothing.
-
-     Checking for incoming changesets is an expensive operation, so `hg-prompt`
-     will cache the results in `.hg/prompt/cache/` and refresh them every 15
-     minutes.
-
-     |count
-         Display the number of incoming changesets (if greater than 0).
-     |zero
-         Display 0 if there are no incoming changesets.
-
 node
      Display the (full) changeset hash of the current parent.
 
@@ -558,22 +445,6 @@
      |merge
          Display the hash of the changeset you're merging with.
 
-outgoing
-     Display nothing, but if the current repository contains outgoing
-     changesets (to default) the extra text will be expanded.
-
-     For example: `{outgoing changes{outgoing}}` will expand to
-     `outgoing changes` if there are changes, otherwise nothing.
-
-     Checking for outgoing changesets is an expensive operation, so `hg-prompt`
-     will cache the results in `.hg/prompt/cache/` and refresh them every 15
-     minutes.
-
-     |count
-         Display the number of outgoing changesets (if greater than 0).
-     |zero
-         Display 0 if there are no incoming changesets.
-
 patch
      Display the topmost currently-applied patch (requires the mq
      extension).