2 from __future__ import absolute_import, print_function
3 from binascii import hexlify
4 from traceback import print_exception
7 # Please see CODINGSTYLE for important exception handling guidelines
8 # and the rationale behind add_ex_tb(), add_ex_ctx(), etc.
10 py_maj = sys.version_info[0]
15 # pylint: disable=unused-import
16 from contextlib import nullcontext
17 from os import environb as environ
18 from os import fsdecode, fsencode
19 from shlex import quote
20 # pylint: disable=undefined-variable
21 # (for python2 looking here)
22 ModuleNotFoundError = ModuleNotFoundError
29 """Return hex string (not bytes as with hexlify) representation of b."""
33 raise ex.with_traceback(sys.exc_info()[2])
36 """Do nothing (already handled by Python 3 infrastructure)."""
39 def add_ex_ctx(ex, context_ex):
40 """Do nothing (already handled by Python 3 infrastructure)."""
44 """If rethrow is true, rethrow ex (if any), unless the body throws.
46 (Supports Python 2 compatibility.)
49 def __init__(self, ex, rethrow=True):
51 self.rethrow = rethrow
54 def __exit__(self, exc_type, exc_value, traceback):
55 if not exc_type and self.ex and self.rethrow:
62 """Return the original bytes passed to main() for an argv argument."""
65 def bytes_from_uint(i):
68 def bytes_from_byte(b): # python > 2: b[3] returns ord('x'), not b'x'
71 byte_int = lambda x: x
73 def buffer(object, offset=None, size=None):
75 assert offset is not None
76 return memoryview(object)[offset:offset + size]
78 return memoryview(object)[offset:]
79 return memoryview(object)
82 return fsencode(os.getcwd())
86 from contextlib import contextmanager
88 ModuleNotFoundError = ImportError
96 from pipes import quote
97 # pylint: disable=unused-import
98 from os import environ, getcwd
100 # pylint: disable=unused-import
101 from bup.py2raise import reraise
104 def nullcontext(enter_result=None):
107 # on py3 this causes errors, obviously
108 # pylint: disable=undefined-variable
110 # pylint: disable=undefined-variable
112 # pylint: disable=undefined-variable
113 str_type = basestring
114 # pylint: disable=undefined-variable
115 int_types = (int, long)
120 """Add a traceback to ex if it doesn't already have one. Return ex.
123 if not getattr(ex, '__traceback__', None):
124 ex.__traceback__ = sys.exc_info()[2]
127 def add_ex_ctx(ex, context_ex):
128 """Make context_ex the __context__ of ex (unless it already has one).
133 if not getattr(ex, '__context__', None):
134 ex.__context__ = context_ex
138 """If rethrow is true, rethrow ex (if any), unless the body throws.
140 If the body does throw, make any provided ex the __context__
141 of the newer exception (assuming there's no existing
142 __context__). Ensure the exceptions have __tracebacks__.
143 (Supports Python 2 compatibility.)
146 def __init__(self, ex, rethrow=True):
148 self.rethrow = rethrow
152 def __exit__(self, exc_type, exc_value, traceback):
156 add_ex_ctx(exc_value, self.ex)
158 if self.rethrow and self.ex:
161 def dump_traceback(ex):
163 next_ex = getattr(ex, '__context__', None)
165 stack.append(next_ex)
166 next_ex = getattr(next_ex, '__context__', None)
167 stack = reversed(stack)
169 tb = getattr(ex, '__traceback__', None)
170 print_exception(type(ex), ex, tb)
172 print('\nDuring handling of the above exception, another exception occurred:\n',
174 tb = getattr(ex, '__traceback__', None)
175 print_exception(type(ex), ex, tb)
181 """Return the original bytes passed to main() for an argv argument."""
184 bytes_from_uint = chr
186 def bytes_from_byte(b):
195 except ModuleNotFoundError:
200 "Return a new list containing the current process argv bytes."
201 return bup_main.argv()
204 "Return a new list containing the current process argv strings."
205 return [x.decode(errors='surrogateescape') for x in bup_main.argv()]
208 return bup_main.argv()
211 raise Exception('get_argvb requires the bup_main module');
213 raise Exception('get_argv requires the bup_main module');
216 """Run main() and raise a SystemExit with the return value if it
217 returns, pass along any SystemExit it raises, convert
218 KeyboardInterrupts into exit(130), and print a Python 3 style
219 contextual backtrace for other exceptions in both Python 2 and
223 except KeyboardInterrupt as ex:
225 except SystemExit as ex:
227 except BaseException as ex:
235 # Excepting wrap_main() in the traceback, these should produce similar output:
236 # python2 lib/bup/compat.py
237 # python3 lib/bup/compat.py
239 # diff -u <(python2 lib/bup/compat.py 2>&1) <(python3 lib/bup/compat.py 2>&1)
241 # Though the python3 output for 'second' will include a stacktrace
242 # starting from wrap_main, rather than from outer().
244 if __name__ == '__main__':
247 raise Exception('first')
252 except Exception as ex:
255 raise Exception('second')
256 except Exception as ex2:
257 raise add_ex_ctx(add_ex_tb(ex2), ex)