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):
57 """Return the original bytes passed to main() for an argv argument."""
60 def bytes_from_uint(i):
63 def bytes_from_byte(b): # python > 2: b[3] returns ord('x'), not b'x'
66 byte_int = lambda x: x
68 def buffer(object, offset=None, size=None):
70 assert offset is not None
71 return memoryview(object)[offset:offset + size]
73 return memoryview(object)[offset:]
74 return memoryview(object)
77 return fsencode(os.getcwd())
81 ModuleNotFoundError = ImportError
89 from pipes import quote
90 # pylint: disable=unused-import
91 from os import environ, getcwd
93 # pylint: disable=unused-import
94 from bup.py2raise import reraise
99 int_types = (int, long)
104 """Add a traceback to ex if it doesn't already have one. Return ex.
107 if not getattr(ex, '__traceback__', None):
108 ex.__traceback__ = sys.exc_info()[2]
111 def add_ex_ctx(ex, context_ex):
112 """Make context_ex the __context__ of ex (unless it already has one).
117 if not getattr(ex, '__context__', None):
118 ex.__context__ = context_ex
122 """Rethrow either the provided ex, or any exception raised by the with
123 statement body, after making ex the __context__ of the newer
124 exception (assuming there's no existing __context__). Ensure
125 the exceptions have __tracebacks__. (Supports Python 2
129 def __init__(self, ex):
133 def __exit__(self, exc_type, exc_value, traceback):
137 add_ex_ctx(exc_value, self.ex)
139 def dump_traceback(ex):
141 next_ex = getattr(ex, '__context__', None)
143 stack.append(next_ex)
144 next_ex = getattr(next_ex, '__context__', None)
145 stack = reversed(stack)
147 tb = getattr(ex, '__traceback__', None)
148 print_exception(type(ex), ex, tb)
150 print('\nDuring handling of the above exception, another exception occurred:\n',
152 tb = getattr(ex, '__traceback__', None)
153 print_exception(type(ex), ex, tb)
159 """Return the original bytes passed to main() for an argv argument."""
162 bytes_from_uint = chr
164 def bytes_from_byte(b):
173 except ModuleNotFoundError:
178 "Return a new list containing the current process argv bytes."
179 return bup_main.argv()
182 "Return a new list containing the current process argv strings."
183 return [x.decode(errors='surrogateescape') for x in bup_main.argv()]
186 return bup_main.argv()
189 raise Exception('get_argvb requires the bup_main module');
191 raise Exception('get_argv requires the bup_main module');
194 """Run main() and raise a SystemExit with the return value if it
195 returns, pass along any SystemExit it raises, convert
196 KeyboardInterrupts into exit(130), and print a Python 3 style
197 contextual backtrace for other exceptions in both Python 2 and
201 except KeyboardInterrupt as ex:
203 except SystemExit as ex:
205 except BaseException as ex:
213 # Excepting wrap_main() in the traceback, these should produce similar output:
214 # python2 lib/bup/compat.py
215 # python3 lib/bup/compat.py
217 # diff -u <(python2 lib/bup/compat.py 2>&1) <(python3 lib/bup/compat.py 2>&1)
219 # Though the python3 output for 'second' will include a stacktrace
220 # starting from wrap_main, rather than from outer().
222 if __name__ == '__main__':
225 raise Exception('first')
230 except Exception as ex:
233 raise Exception('second')
234 except Exception as ex2:
235 raise add_ex_ctx(add_ex_tb(ex2), ex)