# HG changeset patch # User Idan Kamara # Date 1313673622 -10800 # Node ID 3d7e0325ba1c9ba57639b92baf36063e9a9e91ae # Parent 82d927ac1329a30098f17503e6b68267dc89eeda util: introduce a generic error handler that is aware of return codes diff -r 82d927ac1329 -r 3d7e0325ba1c hglib/util.py --- 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