]> arthur.barton.de Git - bup.git/blob - lib/bup/compat.py
Convert top level executables to binaries and clean up clean
[bup.git] / lib / bup / compat.py
1
2 from __future__ import absolute_import, print_function
3 from array import array
4 from binascii import hexlify
5 from traceback import print_exception
6 import os, sys
7
8 # Please see CODINGSTYLE for important exception handling guidelines
9 # and the rationale behind add_ex_tb(), add_ex_ctx(), etc.
10
11 py_maj = sys.version_info[0]
12 py3 = py_maj >= 3
13
14 if py3:
15
16     from os import environb as environ
17     from os import fsdecode, fsencode
18     from shlex import quote
19     ModuleNotFoundError = ModuleNotFoundError
20     input = input
21     range = range
22     str_type = str
23     int_types = (int,)
24
25     def hexstr(b):
26         """Return hex string (not bytes as with hexlify) representation of b."""
27         return b.hex()
28
29     def reraise(ex):
30         raise ex.with_traceback(sys.exc_info()[2])
31
32     def add_ex_tb(ex):
33         """Do nothing (already handled by Python 3 infrastructure)."""
34         return ex
35
36     def add_ex_ctx(ex, context_ex):
37         """Do nothing (already handled by Python 3 infrastructure)."""
38         return ex
39
40     class pending_raise:
41         """Rethrow either the provided ex, or any exception raised by the with
42         statement body.  (Supports Python 2 compatibility.)
43
44         """
45         def __init__(self, ex):
46             self.ex = ex
47         def __enter__(self):
48             return None
49         def __exit__(self, exc_type, exc_value, traceback):
50             if not exc_type:
51                 raise self.ex
52             return None
53
54     def items(x):
55         return x.items()
56
57     def argv_bytes(x):
58         """Return the original bytes passed to main() for an argv argument."""
59         return fsencode(x)
60
61     def bytes_from_uint(i):
62         return bytes((i,))
63
64     def bytes_from_byte(b):  # python > 2: b[3] returns ord('x'), not b'x'
65         return bytes((b,))
66
67     byte_int = lambda x: x
68
69     def buffer(object, offset=None, size=None):
70         if size:
71             assert offset is not None
72             return memoryview(object)[offset:offset + size]
73         if offset:
74             return memoryview(object)[offset:]
75         return memoryview(object)
76
77     def getcwd():
78         return fsencode(os.getcwd())
79
80 else:  # Python 2
81
82     ModuleNotFoundError = ImportError
83
84     def fsdecode(x):
85         return x
86
87     def fsencode(x):
88         return x
89
90     from pipes import quote
91     from os import environ, getcwd
92
93     from bup.py2raise import reraise
94
95     input = raw_input
96     range = xrange
97     str_type = basestring
98     int_types = (int, long)
99
100     hexstr = hexlify
101
102     def add_ex_tb(ex):
103         """Add a traceback to ex if it doesn't already have one.  Return ex.
104
105         """
106         if not getattr(ex, '__traceback__', None):
107             ex.__traceback__ = sys.exc_info()[2]
108         return ex
109
110     def add_ex_ctx(ex, context_ex):
111         """Make context_ex the __context__ of ex (unless it already has one).
112         Return ex.
113
114         """
115         if context_ex:
116             if not getattr(ex, '__context__', None):
117                 ex.__context__ = context_ex
118         return ex
119
120     class pending_raise:
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
125         compatibility.)
126
127         """
128         def __init__(self, ex):
129             self.ex = ex
130         def __enter__(self):
131             add_ex_tb(self.ex)
132             return None
133         def __exit__(self, exc_type, exc_value, traceback):
134             if not exc_type:
135                 raise self.ex
136             add_ex_tb(exc_value)
137             add_ex_ctx(exc_value, self.ex)
138             return None
139
140     def dump_traceback(ex):
141         stack = [ex]
142         next_ex = getattr(ex, '__context__', None)
143         while next_ex:
144             stack.append(next_ex)
145             next_ex = getattr(next_ex, '__context__', None)
146         stack = reversed(stack)
147         ex = next(stack)
148         tb = getattr(ex, '__traceback__', None)
149         print_exception(type(ex), ex, tb)
150         for ex in stack:
151             print('\nDuring handling of the above exception, another exception occurred:\n',
152                   file=sys.stderr)
153             tb = getattr(ex, '__traceback__', None)
154             print_exception(type(ex), ex, tb)
155
156     def items(x):
157         return x.iteritems()
158
159     def argv_bytes(x):
160         """Return the original bytes passed to main() for an argv argument."""
161         return x
162
163     bytes_from_uint = chr
164
165     def bytes_from_byte(b):
166         return b
167
168     byte_int = ord
169
170     buffer = buffer
171
172 try:
173     import bup_main
174 except ModuleNotFoundError:
175     bup_main = None
176
177 if bup_main:
178     def get_argvb():
179         "Return a new list containing the current process argv bytes."
180         return bup_main.argv()
181     if py3:
182         def get_argv():
183             "Return a new list containing the current process argv strings."
184             return [x.decode(errors='surrogateescape') for x in bup_main.argv()]
185     else:
186         def get_argv():
187             return bup_main.argv()
188 else:
189     def get_argvb():
190         raise Exception('get_argvb requires the bup_main module');
191     def get_argv():
192         raise Exception('get_argv requires the bup_main module');
193
194 def wrap_main(main):
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
199     3)."""
200     try:
201         sys.exit(main())
202     except KeyboardInterrupt as ex:
203         sys.exit(130)
204     except SystemExit as ex:
205         raise
206     except BaseException as ex:
207         if py3:
208             raise
209         add_ex_tb(ex)
210         dump_traceback(ex)
211         sys.exit(1)
212
213
214 # Excepting wrap_main() in the traceback, these should produce similar output:
215 #   python2 lib/bup/compat.py
216 #   python3 lib/bup/compat.py
217 # i.e.:
218 #   diff -u <(python2 lib/bup/compat.py 2>&1) <(python3 lib/bup/compat.py 2>&1)
219 #
220 # Though the python3 output for 'second' will include a stacktrace
221 # starting from wrap_main, rather than from outer().
222
223 if __name__ == '__main__':
224
225     def inner():
226         raise Exception('first')
227
228     def outer():
229         try:
230             inner()
231         except Exception as ex:
232             add_ex_tb(ex)
233             try:
234                 raise Exception('second')
235             except Exception as ex2:
236                 raise add_ex_ctx(add_ex_tb(ex2), ex)
237
238     wrap_main(outer)