2 from __future__ import absolute_import, print_function
3 from array import array
4 from binascii import hexlify
5 from traceback import print_exception
8 # Please see CODINGSTYLE for important exception handling guidelines
9 # and the rationale behind add_ex_tb(), add_ex_ctx(), etc.
11 py_maj = sys.version_info[0]
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 from os import environ, getcwd
93 from bup.py2raise import reraise
98 int_types = (int, long)
103 """Add a traceback to ex if it doesn't already have one. Return ex.
106 if not getattr(ex, '__traceback__', None):
107 ex.__traceback__ = sys.exc_info()[2]
110 def add_ex_ctx(ex, context_ex):
111 """Make context_ex the __context__ of ex (unless it already has one).
116 if not getattr(ex, '__context__', None):
117 ex.__context__ = context_ex
121 """Rethrow either the provided ex, or any exception raised by the with
122 statement body, after making ex the __context__ of the newer
123 exception (assuming there's no existing __context__). Ensure
124 the exceptions have __tracebacks__. (Supports Python 2
128 def __init__(self, ex):
133 def __exit__(self, exc_type, exc_value, traceback):
137 add_ex_ctx(exc_value, self.ex)
140 def dump_traceback(ex):
142 next_ex = getattr(ex, '__context__', None)
144 stack.append(next_ex)
145 next_ex = getattr(next_ex, '__context__', None)
146 stack = reversed(stack)
148 tb = getattr(ex, '__traceback__', None)
149 print_exception(type(ex), ex, tb)
151 print('\nDuring handling of the above exception, another exception occurred:\n',
153 tb = getattr(ex, '__traceback__', None)
154 print_exception(type(ex), ex, tb)
160 """Return the original bytes passed to main() for an argv argument."""
163 bytes_from_uint = chr
165 def bytes_from_byte(b):
174 except ModuleNotFoundError:
179 "Return a new list containing the current process argv bytes."
180 return bup_main.argv()
183 "Return a new list containing the current process argv strings."
184 return [x.decode(errors='surrogateescape') for x in bup_main.argv()]
187 return bup_main.argv()
190 raise Exception('get_argvb requires the bup_main module');
192 raise Exception('get_argv requires the bup_main module');
195 """Run main() and raise a SystemExit with the return value if it
196 returns, pass along any SystemExit it raises, convert
197 KeyboardInterrupts into exit(130), and print a Python 3 style
198 contextual backtrace for other exceptions in both Python 2 and
202 except KeyboardInterrupt as ex:
204 except SystemExit as ex:
206 except BaseException as ex:
214 # Excepting wrap_main() in the traceback, these should produce similar output:
215 # python2 lib/bup/compat.py
216 # python3 lib/bup/compat.py
218 # diff -u <(python2 lib/bup/compat.py 2>&1) <(python3 lib/bup/compat.py 2>&1)
220 # Though the python3 output for 'second' will include a stacktrace
221 # starting from wrap_main, rather than from outer().
223 if __name__ == '__main__':
226 raise Exception('first')
231 except Exception as ex:
234 raise Exception('second')
235 except Exception as ex2:
236 raise add_ex_ctx(add_ex_tb(ex2), ex)