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 os import environb as environ
17 from os import fsdecode, fsencode
18 from shlex import quote
19 ModuleNotFoundError = ModuleNotFoundError
26 """Return hex string (not bytes as with hexlify) representation of b."""
30 raise ex.with_traceback(sys.exc_info()[2])
33 """Do nothing (already handled by Python 3 infrastructure)."""
36 def add_ex_ctx(ex, context_ex):
37 """Do nothing (already handled by Python 3 infrastructure)."""
41 """Rethrow either the provided ex, or any exception raised by the with
42 statement body. (Supports Python 2 compatibility.)
45 def __init__(self, ex):
49 def __exit__(self, exc_type, exc_value, traceback):
58 """Return the original bytes passed to main() for an argv argument."""
61 def bytes_from_uint(i):
64 def bytes_from_byte(b): # python > 2: b[3] returns ord('x'), not b'x'
67 byte_int = lambda x: x
69 def buffer(object, offset=None, size=None):
71 assert offset is not None
72 return memoryview(object)[offset:offset + size]
74 return memoryview(object)[offset:]
75 return memoryview(object)
78 return fsencode(os.getcwd())
82 ModuleNotFoundError = ImportError
90 from pipes import quote
91 # pylint: disable=unused-import
92 from os import environ, getcwd
94 # pylint: disable=unused-import
95 from bup.py2raise import reraise
100 int_types = (int, long)
105 """Add a traceback to ex if it doesn't already have one. Return ex.
108 if not getattr(ex, '__traceback__', None):
109 ex.__traceback__ = sys.exc_info()[2]
112 def add_ex_ctx(ex, context_ex):
113 """Make context_ex the __context__ of ex (unless it already has one).
118 if not getattr(ex, '__context__', None):
119 ex.__context__ = context_ex
123 """Rethrow either the provided ex, or any exception raised by the with
124 statement body, after making ex the __context__ of the newer
125 exception (assuming there's no existing __context__). Ensure
126 the exceptions have __tracebacks__. (Supports Python 2
130 def __init__(self, ex):
135 def __exit__(self, exc_type, exc_value, traceback):
139 add_ex_ctx(exc_value, self.ex)
142 def dump_traceback(ex):
144 next_ex = getattr(ex, '__context__', None)
146 stack.append(next_ex)
147 next_ex = getattr(next_ex, '__context__', None)
148 stack = reversed(stack)
150 tb = getattr(ex, '__traceback__', None)
151 print_exception(type(ex), ex, tb)
153 print('\nDuring handling of the above exception, another exception occurred:\n',
155 tb = getattr(ex, '__traceback__', None)
156 print_exception(type(ex), ex, tb)
162 """Return the original bytes passed to main() for an argv argument."""
165 bytes_from_uint = chr
167 def bytes_from_byte(b):
176 except ModuleNotFoundError:
181 "Return a new list containing the current process argv bytes."
182 return bup_main.argv()
185 "Return a new list containing the current process argv strings."
186 return [x.decode(errors='surrogateescape') for x in bup_main.argv()]
189 return bup_main.argv()
192 raise Exception('get_argvb requires the bup_main module');
194 raise Exception('get_argv requires the bup_main module');
197 """Run main() and raise a SystemExit with the return value if it
198 returns, pass along any SystemExit it raises, convert
199 KeyboardInterrupts into exit(130), and print a Python 3 style
200 contextual backtrace for other exceptions in both Python 2 and
204 except KeyboardInterrupt as ex:
206 except SystemExit as ex:
208 except BaseException as ex:
216 # Excepting wrap_main() in the traceback, these should produce similar output:
217 # python2 lib/bup/compat.py
218 # python3 lib/bup/compat.py
220 # diff -u <(python2 lib/bup/compat.py 2>&1) <(python3 lib/bup/compat.py 2>&1)
222 # Though the python3 output for 'second' will include a stacktrace
223 # starting from wrap_main, rather than from outer().
225 if __name__ == '__main__':
228 raise Exception('first')
233 except Exception as ex:
236 raise Exception('second')
237 except Exception as ex2:
238 raise add_ex_ctx(add_ex_tb(ex2), ex)