Commits

ZyX_I committed 5edcb4e

@aurum/drivers/mercurial: Moved lots of same lines in python script to a decorator

Comments (0)

Files changed (1)

 import json
 import re
 
+def outermethod(func):
+    """ Decorator used to make functions omit showing python traceback in case vim_throw was used """
+    def f(*args, **kwargs):
+        try:
+            func(*args, **kwargs)
+        except AurumError:
+            pass
+        except vim.error:
+            pass
+    return f
+
 def nonutf_dumps(obj):
     todump=[('dump', obj)]
     r=''
     r=[set_rev_dict(g_cs(repo, i), {'rev': i,}) for i in range(startrev, cscount+1)]
     return r
 
+@outermethod
 def get_updates(path, oldtip=None):
-    try:
-        repo=g_repo(path)
-        tipcs=repo['tip']
-        if oldtip is not None:
-            try:
-                cs=repo[oldtip]
-                if tipcs.hex()==cs.hex():
-                    return
-                startrev=cs.rev()
-            except error.RepoLookupError:
-                startrev=0
-        else:
+    repo=g_repo(path)
+    tipcs=repo['tip']
+    if oldtip is not None:
+        try:
+            cs=repo[oldtip]
+            if tipcs.hex()==cs.hex():
+                return
+            startrev=cs.rev()
+        except error.RepoLookupError:
             startrev=0
-        r=get_revlist(repo, startrev)
-        tags_vim={}
-        for (tag, b) in repo.tags().items():
-            tags_vim[tag]=repo[b].hex()
-        bookmarks_vim={}
-        if hasattr(repo, 'listkeys'):
-            bookmarks_vim=repo.listkeys('bookmarks')
-        d_vim={      'css': r,
-                'startrev': startrev,
-                    'tags': tags_vim,
-               'bookmarks': bookmarks_vim,}
-        vim.eval('extend(a:repo, {"csnum": '+str(len(repo)+1)+'})')
-        vim.eval('extend(d, '+utf_dumps(d_vim)+')')
-    except AurumError:
-        pass
+    else:
+        startrev=0
+    r=get_revlist(repo, startrev)
+    tags_vim={}
+    for (tag, b) in repo.tags().items():
+        tags_vim[tag]=repo[b].hex()
+    bookmarks_vim={}
+    if hasattr(repo, 'listkeys'):
+        bookmarks_vim=repo.listkeys('bookmarks')
+    d_vim={      'css': r,
+            'startrev': startrev,
+                'tags': tags_vim,
+           'bookmarks': bookmarks_vim,}
+    vim.eval('extend(a:repo, {"csnum": '+str(len(repo)+1)+'})')
+    vim.eval('extend(d, '+utf_dumps(d_vim)+')')
 
+@outermethod
 def get_cs(path, rev):
-    try:
-        cs=g_cs(g_repo(path), rev)
-        cs_vim=set_rev_dict(cs, {'rev': cs.rev()})
-        vim.eval('extend(cs, '+utf_dumps(cs_vim)+')')
-    except AurumError:
-        pass
+    cs=g_cs(g_repo(path), rev)
+    cs_vim=set_rev_dict(cs, {'rev': cs.rev()})
+    vim.eval('extend(cs, '+utf_dumps(cs_vim)+')')
 
+@outermethod
 def new_repo(path):
-    try:
-        repo=g_repo(path)
-        # TODO remove bookmark label type if it is not available
-        vim_repo={'has_octopus_merges': 0,
-                       'requires_sort': 0,
-                          'changesets': {},
-                              'cslist': [],
-                               'local': 1 if repo.local() else 0,
-                          'labeltypes': ['tag', 'bookmark'],
-                 }
-        if hasattr(repo, '__len__'):
-            vim_repo['csnum']=len(repo)+1
-        vim.eval('extend(repo, '+utf_dumps(vim_repo)+')')
-    except AurumError:
-        pass
+    repo=g_repo(path)
+    # TODO remove bookmark label type if it is not available
+    vim_repo={'has_octopus_merges': 0,
+                   'requires_sort': 0,
+                      'changesets': {},
+                          'cslist': [],
+                           'local': 1 if repo.local() else 0,
+                      'labeltypes': ['tag', 'bookmark'],
+             }
+    if hasattr(repo, '__len__'):
+        vim_repo['csnum']=len(repo)+1
+    vim.eval('extend(repo, '+utf_dumps(vim_repo)+')')
 
+@outermethod
 def get_file(path, rev, filepath):
-    try:
-        fctx=g_fctx(g_cs(g_repo(path), rev), filepath)
-        lines=[line.replace("\0", "\n") for line in fctx.data().split("\n")]
-        vim.eval('extend(r, '+nonutf_dumps(lines)+')')
-    except AurumError:
-        pass
+    fctx=g_fctx(g_cs(g_repo(path), rev), filepath)
+    lines=[line.replace("\0", "\n") for line in fctx.data().split("\n")]
+    vim.eval('extend(r, '+nonutf_dumps(lines)+')')
 
+@outermethod
 def annotate(path, rev, filepath):
-    try:
-        ann=g_fctx(g_cs(g_repo(path), rev), filepath).annotate(follow=True,
-                                                               linenumber=True)
-        ann_vim=[(line[0][0].path(), str(line[0][0].rev()), line[0][1])
-                                                                for line in ann]
-        vim.eval('extend(r, '+nonutf_dumps(ann_vim)+')')
-    except AurumError:
-        pass
+    ann=g_fctx(g_cs(g_repo(path), rev), filepath).annotate(follow=True,
+                                                           linenumber=True)
+    ann_vim=[(line[0][0].path(), str(line[0][0].rev()), line[0][1])
+                                                            for line in ann]
+    vim.eval('extend(r, '+nonutf_dumps(ann_vim)+')')
 
 def run_in_dir(dir, func, *args, **kwargs):
     workdir=os.path.abspath('.')
             kwargs["change"]=rev1
     run_in_dir(repo.root, commands.diff, *args, **kwargs)
 
+@outermethod
 def diff(*args, **kwargs):
-    try:
-        ui=CaptureUI()
-        dodiff(ui, *args, **kwargs)
-        vim.eval('extend(r, '+nonutf_dumps(ui._getCaptured())+')')
-    except AurumError:
-        pass
+    ui=CaptureUI()
+    dodiff(ui, *args, **kwargs)
+    vim.eval('extend(r, '+nonutf_dumps(ui._getCaptured())+')')
 
+@outermethod
 def diffToBuffer(*args, **kwargs):
-    try:
-        ui=CaptureToBuf(vim.current.buffer)
-        dodiff(ui, *args, **kwargs)
-        if len(vim.current.buffer)>1 and vim.current.buffer[-1] == '':
-            vim.current.buffer[-1:]=[]
-        else:
-            vim.command('setlocal binary noendofline')
-    except AurumError:
-        pass
+    ui=CaptureToBuf(vim.current.buffer)
+    dodiff(ui, *args, **kwargs)
+    if len(vim.current.buffer)>1 and vim.current.buffer[-1] == '':
+        vim.current.buffer[-1:]=[]
+    else:
+        vim.command('setlocal binary noendofline')
 
 def get_renames(cs):
     def get_renames_value(rename):
     vim.eval('extend(a:cs, '+nonutf_dumps({'renames': renames_vim,
                                             'copies': copies_vim})+')')
 
+@outermethod
 def get_cs_prop(path, rev, prop):
+    cs=g_cs(g_repo(path), rev)
+    if prop=='files' or prop=='removes' or prop=='changes':
+        am=[]
+        r=[]
+        c=cs.files()
+        for f in c:
+            if f in cs:
+                am.append(f)
+            else:
+                r.append(f)
+        vim.eval('extend(a:cs, {  "files": '+nonutf_dumps(am)+', '+
+                               '"removes": '+nonutf_dumps(r) +', '+
+                               '"changes": '+nonutf_dumps(c) +'})')
+        return
+    elif prop=='renames' or prop=='copies':
+        get_renames(cs)
+        return
+    elif prop=='allfiles':
+        r=[f for f in cs]
+    elif prop=='children':
+        r=[ccs.hex() for ccs in cs.children()]
+    else:
+        r=cs.__getattribute__(prop)()
+    # XXX There is much code relying on the fact that after getcsprop
+    #     property with given name is added to changeset dictionary
+    vim.eval('extend(a:cs, {"'+prop+'": '+nonutf_dumps(r)+'})')
+
+@outermethod
+def get_status(path, rev1=None, rev2=None, files=None, clean=None):
+    if rev1 is None and rev2 is None:
+        rev1='.'
+    repo=g_repo(path)
+    if hasattr(repo, 'status'):
+        if not files:
+            m=None
+        else:
+            m=match.match(None, None, files, exact=True)
+        status=repo.status(rev1, rev2, ignored=True, clean=clean,
+                           unknown=True, match=m)
+        vim.eval('extend(r, '+nonutf_dumps({'modified': status[0],
+                                               'added': status[1],
+                                             'removed': status[2],
+                                             'deleted': status[3],
+                                             'unknown': status[4],
+                                             'ignored': status[5],
+                                               'clean': status[6],
+                                           })+')')
+    else:
+        vim_throw('statuns', repo.path)
+
+@outermethod
+def update(path, rev='tip', force=False):
+    repo=g_repo(path)
+    if not hasattr(repo, '__getitem__'):
+        vim_throw('upduns', repo.path)
+    rev=g_cs(repo, rev).hex()
+    args=[PrintUI(), repo, rev]
+    kwargs={'clean': bool(force)}
+    run_in_dir(repo.root, commands.update, *args, **kwargs)
+
+@outermethod
+def dirty(path, filepath):
+    repo=g_repo(path)
+    if not hasattr(repo, '__getitem__'):
+        vim_throw('statuns', repo.path)
+    dirty=repo[None].dirty()
+    if dirty and filepath in dirty:
+        vim.command('let r=1')
+
+@outermethod
+def get_repo_prop(path, prop):
+    repo=g_repo(path)
+    r=None
+    if prop=='tagslist':
+        r=repo.tags().keys()
+    elif prop=='brancheslist':
+        r=repo.branchmap().keys()
+    elif prop=='bookmarkslist':
+        if hasattr(repo, 'listkeys'):
+            r=repo.listkeys('bookmarks').keys()
+        else:
+            r=[]
+    elif prop=='url':
+        r=repo.ui.config('paths', 'default-push')
+        if r is None:
+            r=repo.ui.config('paths', 'default')
+    if r is None:
+        vim_throw('nocfg', prop, repo.path)
+    else:
+        vim.eval('extend(a:repo, {"'+prop+'": '+utf_dumps(r)+'})')
+
+@outermethod
+def call_cmd(path, attr, *args, **kwargs):
+    repo=g_repo(path)
+    if 'force' in kwargs:
+        kwargs['force']=bool(kwargs['force'])
+    else:
+        kwargs['force']=False
+    if 'bundle' not in kwargs:
+        kwargs['bundle']=None
+    for key in [key for key in kwargs if key.find('-')!=-1]:
+        newkey=key.replace('-', '_')
+        kwargs[newkey]=kwargs.pop(key)
+    cargs=[repo.ui, repo]
+    cargs.extend(args)
+    run_in_dir(repo.root, commands.__getattribute__(attr),
+               *cargs, **kwargs)
+
+@outermethod
+def grep(path, pattern, files, revisions=None, ignore_case=False, wdfiles=True):
+    repo=g_repo(path)
+    ui=CaptureUI()
+    args=[ui, repo, pattern]
+    args.extend(files)
+    revisions=[":".join(rev) if type(rev) is list else rev
+                             for rev in revisions]
+    if not revisions:
+        revisions=None
+    kwargs={'rev': revisions, 'ignore_case': bool(ignore_case),
+            'line_number': True, 'print0': True}
+    cs=g_cs(repo, '.')
+    kwargs['follow']=not [f for f in files if f not in cs]
+    run_in_dir(repo.root, commands.grep, *args, **kwargs)
+    items=(ui._getCaptured(verbatim=True)).split("\0")
+    # XXX grep uses "\0" as a terminator, thus last line ends with "\0"
+    items.pop()
+    r_vim=[]
+    status_cache={}
+    def check_not_modified_since(rev, file):
+        key=rev+':'+file
+        if key in status_cache:
+            return status_cache[key]
+        r=file in repo.status(node1=rev, clean=True,
+                              match=match.match(None, None, [file],
+                                                exact=True))[6]
+        status_cache[key]=r
+        return r
+    while items:
+        file=items.pop(0)
+        rev=items.pop(0)
+        lnum=int(items.pop(0))
+        text=items.pop(0)
+        if wdfiles and check_not_modified_since(rev, file):
+            file=os.path.join(repo.root, file)
+        else:
+            file=(rev, file)
+        r_vim.append({'filename': file, 'lnum': int(lnum), 'text': text})
+    vim.eval('extend(r, '+nonutf_dumps(r_vim)+')')
+
+@outermethod
+def git_hash(path, rev):
+    repo=g_repo(path)
+    hggitpath=None
+    hggitname=None
+    for hggitname in ['hggit', 'git']:
+        hggitpath=repo.ui.config('extensions', hggitname)
+        if hggitpath is not None:
+            break
+    if hggitpath is None:
+        vim_throw('nohggitc')
+    import sys
+    sys.path.insert(0, hggitpath)
     try:
-        cs=g_cs(g_repo(path), rev)
-        if prop=='files' or prop=='removes' or prop=='changes':
-            am=[]
-            r=[]
-            c=cs.files()
-            for f in c:
-                if f in cs:
-                    am.append(f)
-                else:
-                    r.append(f)
-            vim.eval('extend(a:cs, {  "files": '+nonutf_dumps(am)+', '+
-                                   '"removes": '+nonutf_dumps(r) +', '+
-                                   '"changes": '+nonutf_dumps(c) +'})')
-            return
-        elif prop=='renames' or prop=='copies':
-            get_renames(cs)
-            return
-        elif prop=='allfiles':
-            r=[f for f in cs]
-        elif prop=='children':
-            r=[ccs.hex() for ccs in cs.children()]
-        else:
-            r=cs.__getattribute__(prop)()
-        # XXX There is much code relying on the fact that after getcsprop
-        #     property with given name is added to changeset dictionary
-        vim.eval('extend(a:cs, {"'+prop+'": '+nonutf_dumps(r)+'})')
-    except AurumError:
-        pass
-
-def get_status(path, rev1=None, rev2=None, files=None, clean=None):
-    try:
-        if rev1 is None and rev2 is None:
-            rev1='.'
-        repo=g_repo(path)
-        if hasattr(repo, 'status'):
-            if not files:
-                m=None
-            else:
-                m=match.match(None, None, files, exact=True)
-            status=repo.status(rev1, rev2, ignored=True, clean=clean,
-                               unknown=True, match=m)
-            vim.eval('extend(r, '+nonutf_dumps({'modified': status[0],
-                                                   'added': status[1],
-                                                 'removed': status[2],
-                                                 'deleted': status[3],
-                                                 'unknown': status[4],
-                                                 'ignored': status[5],
-                                                   'clean': status[6],
-                                               })+')')
-        else:
-            vim_throw('statuns', repo.path)
-    except AurumError:
-        pass
-
-def update(path, rev='tip', force=False):
-    try:
-        repo=g_repo(path)
-        if not hasattr(repo, '__getitem__'):
-            vim_throw('upduns', repo.path)
-        rev=g_cs(repo, rev).hex()
-        args=[PrintUI(), repo, rev]
-        kwargs={'clean': bool(force)}
-        run_in_dir(repo.root, commands.update, *args, **kwargs)
-    except AurumError:
-        pass
-
-def dirty(path, filepath):
-    try:
-        repo=g_repo(path)
-        if not hasattr(repo, '__getitem__'):
-            vim_throw('statuns', repo.path)
-        dirty=repo[None].dirty()
-        if dirty and filepath in dirty:
-            vim.command('let r=1')
-    except AurumError:
-        pass
-
-def get_repo_prop(path, prop):
-    try:
-        repo=g_repo(path)
-        r=None
-        if prop=='tagslist':
-            r=repo.tags().keys()
-        elif prop=='brancheslist':
-            r=repo.branchmap().keys()
-        elif prop=='bookmarkslist':
-            if hasattr(repo, 'listkeys'):
-                r=repo.listkeys('bookmarks').keys()
-            else:
-                r=[]
-        elif prop=='url':
-            r=repo.ui.config('paths', 'default-push')
-            if r is None:
-                r=repo.ui.config('paths', 'default')
+        try:
+            if hggitname=='hggit':
+                from hggit.git_handler import GitHandler
+            elif hggitname=='git':
+                from git.git_handler   import GitHandler
+        except ImportError:
+            vim_throw('nohggit')
+        git=GitHandler(repo, repo.ui)
+        cs=g_cs(repo, rev)
+        r=git.map_git_get(cs.hex())
         if r is None:
-            vim_throw('nocfg', prop, repo.path)
-        else:
-            vim.eval('extend(a:repo, {"'+prop+'": '+utf_dumps(r)+'})')
-    except AurumError:
-        pass
-
-def call_cmd(path, attr, *args, **kwargs):
-    try:
-        repo=g_repo(path)
-        if 'force' in kwargs:
-            kwargs['force']=bool(kwargs['force'])
-        else:
-            kwargs['force']=False
-        if 'bundle' not in kwargs:
-            kwargs['bundle']=None
-        for key in [key for key in kwargs if key.find('-')!=-1]:
-            newkey=key.replace('-', '_')
-            kwargs[newkey]=kwargs.pop(key)
-        cargs=[repo.ui, repo]
-        cargs.extend(args)
-        run_in_dir(repo.root, commands.__getattribute__(attr),
-                   *cargs, **kwargs)
-    except AurumError:
-        pass
-
-def grep(path, pattern, files, revisions=None, ignore_case=False, wdfiles=True):
-    try:
-        repo=g_repo(path)
-        ui=CaptureUI()
-        args=[ui, repo, pattern]
-        args.extend(files)
-        revisions=[":".join(rev) if type(rev) is list else rev
-                                 for rev in revisions]
-        if not revisions:
-            revisions=None
-        kwargs={'rev': revisions, 'ignore_case': bool(ignore_case),
-                'line_number': True, 'print0': True}
-        cs=g_cs(repo, '.')
-        kwargs['follow']=not [f for f in files if f not in cs]
-        run_in_dir(repo.root, commands.grep, *args, **kwargs)
-        items=(ui._getCaptured(verbatim=True)).split("\0")
-        # XXX grep uses "\0" as a terminator, thus last line ends with "\0"
-        items.pop()
-        r_vim=[]
-        status_cache={}
-        def check_not_modified_since(rev, file):
-            key=rev+':'+file
-            if key in status_cache:
-                return status_cache[key]
-            r=file in repo.status(node1=rev, clean=True,
-                                  match=match.match(None, None, [file],
-                                                    exact=True))[6]
-            status_cache[key]=r
-            return r
-        while items:
-            file=items.pop(0)
-            rev=items.pop(0)
-            lnum=int(items.pop(0))
-            text=items.pop(0)
-            if wdfiles and check_not_modified_since(rev, file):
-                file=os.path.join(repo.root, file)
-            else:
-                file=(rev, file)
-            r_vim.append({'filename': file, 'lnum': int(lnum), 'text': text})
-        vim.eval('extend(r, '+nonutf_dumps(r_vim)+')')
-    except AurumError:
-        pass
-
-def git_hash(path, rev):
-    try:
-        repo=g_repo(path)
-        hggitpath=None
-        hggitname=None
-        for hggitname in ['hggit', 'git']:
-            hggitpath=repo.ui.config('extensions', hggitname)
-            if hggitpath is not None:
-                break
-        if hggitpath is None:
-            vim_throw('nohggitc')
-        import sys
-        sys.path.insert(0, hggitpath)
-        try:
-            try:
-                if hggitname=='hggit':
-                    from hggit.git_handler import GitHandler
-                elif hggitname=='git':
-                    from git.git_handler   import GitHandler
-            except ImportError:
-                vim_throw('nohggit')
-            git=GitHandler(repo, repo.ui)
-            cs=g_cs(repo, rev)
-            r=git.map_git_get(cs.hex())
-            if r is None:
-                vim_throw('nogitrev', cs.hex(), repo.path)
-            vim.command('return '+json.dumps(r))
-        finally:
-            sys.path.pop(0)
-    except AurumError:
-        pass
+            vim_throw('nogitrev', cs.hex(), repo.path)
+        vim.command('return '+json.dumps(r))
+    finally:
+        sys.path.pop(0)