changeset 49:3d7e0325ba1c

util: introduce a generic error handler that is aware of return codes
author Idan Kamara <idankk86@gmail.com>
date Thu, 18 Aug 2011 16:20:22 +0300
parents 82d927ac1329
children bd7dfd94b0d9
files hglib/util.py
diffstat 1 files changed, 33 insertions(+), 1 deletions(-) [+]
line wrap: on
line diff
--- a/hglib/util.py	Thu Aug 18 16:20:04 2011 +0300
+++ b/hglib/util.py	Thu Aug 18 16:20:22 2011 +0300
@@ -1,4 +1,4 @@
-import itertools, cStringIO
+import itertools, cStringIO, error
 
 def grouper(n, iterable):
     ''' list(grouper(2, range(4))) -> [(0, 1), (2, 3)] '''
@@ -98,3 +98,35 @@
             cmd.append(a)
 
     return cmd
+
+class reterrorhandler(object):
+    """
+    This class is meant to be used with rawcommand() error handler argument.
+    It remembers the return value the command returned if it's one of allowed
+    values, which is only 1 if none are given. Otherwise it raises a CommandError.
+
+    >>> e = reterrorhandler('')
+    >>> bool(e)
+    True
+    >>> e(1, 'a', '')
+    'a'
+    >>> bool(e)
+    False
+    """
+    def __init__(self, args, allowed=None):
+        self.args = args
+        self.ret = 0
+        if allowed is None:
+            self.allowed = [1]
+        else:
+            self.allowed = allowed
+
+    def __call__(self, ret, out, err):
+        self.ret = ret
+        if ret not in self.allowed:
+            raise error.CommandError(self.args, ret, out, err)
+        return out
+
+    def __nonzero__(self):
+        """ Returns True if the return code was 0, False otherwise """
+        return self.ret == 0