2 from __future__ import absolute_import, print_function
3 from array import array
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 from os import fsencode
16 from shlex import quote
21 """Do nothing (already handled by Python 3 infrastructure)."""
24 def add_ex_ctx(ex, context_ex):
25 """Do nothing (already handled by Python 3 infrastructure)."""
32 """Return the original bytes passed to main() for an argv argument."""
35 def bytes_from_uint(i):
38 byte_int = lambda x: x
40 def buffer(object, offset=None, size=None):
42 assert offset is not None
43 return memoryview(object)[offset:offset + size]
45 return memoryview(object)[offset:]
46 return memoryview(object)
48 def join_bytes(*items):
49 """Return the concatenated bytes or memoryview arguments as bytes."""
50 return b''.join(items)
54 from pipes import quote
59 """Add a traceback to ex if it doesn't already have one. Return ex.
62 if not getattr(ex, '__traceback__', None):
63 ex.__traceback__ = sys.exc_info()[2]
66 def add_ex_ctx(ex, context_ex):
67 """Make context_ex the __context__ of ex (unless it already has one).
72 if not getattr(ex, '__context__', None):
73 ex.__context__ = context_ex
76 def dump_traceback(ex):
78 next_ex = getattr(ex, '__context__', None)
81 next_ex = getattr(next_ex, '__context__', None)
82 stack = reversed(stack)
84 tb = getattr(ex, '__traceback__', None)
85 print_exception(type(ex), ex, tb)
87 print('\nDuring handling of the above exception, another exception occurred:\n',
89 tb = getattr(ex, '__traceback__', None)
90 print_exception(type(ex), ex, tb)
96 """Return the original bytes passed to main() for an argv argument."""
99 def bytes_from_uint(i):
106 def join_bytes(x, y):
107 """Return the concatenated bytes or buffer arguments as bytes."""
108 if type(x) == buffer:
109 assert type(y) in (bytes, buffer)
111 assert type(x) == bytes
113 return b''.join((x, y))
114 assert type(y) in (bytes, buffer)
118 """Run main() and raise a SystemExit with the return value if it
119 returns, pass along any SystemExit it raises, convert
120 KeyboardInterrupts into exit(130), and print a Python 3 style
121 contextual backtrace for other exceptions in both Python 2 and
125 except KeyboardInterrupt as ex:
127 except SystemExit as ex:
129 except BaseException as ex:
137 # Excepting wrap_main() in the traceback, these should produce similar output:
138 # python2 lib/bup/compat.py
139 # python3 lib/bup/compat.py
141 # diff -u <(python2 lib/bup/compat.py 2>&1) <(python3 lib/bup/compat.py 2>&1)
143 # Though the python3 output for 'second' will include a stacktrace
144 # starting from wrap_main, rather than from outer().
146 if __name__ == '__main__':
149 raise Exception('first')
154 except Exception as ex:
157 raise Exception('second')
158 except Exception as ex2:
159 raise add_ex_ctx(add_ex_tb(ex2), ex)