]> arthur.barton.de Git - bup.git/blob - lib/bup/compat.py
Add compat.reraise to handle python 3 syntax breakage
[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
18     lc_ctype = environ.get(b'LC_CTYPE')
19     if lc_ctype and lc_ctype.lower() != b'iso-8859-1':
20         # Because of argv, options.py, pwd, grp, and any number of other issues
21         print('error: bup currently only works with ISO-8859-1, not LC_CTYPE=%s'
22               % lc_ctype.decode(),
23               file=sys.stderr)
24         print('error: this should already have been arranged, so indicates a bug',
25               file=sys.stderr)
26         sys.exit(2)
27
28     from os import fsencode
29     from shlex import quote
30     range = range
31     str_type = str
32     int_types = (int,)
33
34     def hexstr(b):
35         """Return hex string (not bytes as with hexlify) representation of b."""
36         return b.hex()
37
38     def reraise(ex):
39         raise ex.with_traceback(sys.exc_info()[2])
40
41     def add_ex_tb(ex):
42         """Do nothing (already handled by Python 3 infrastructure)."""
43         return ex
44
45     def add_ex_ctx(ex, context_ex):
46         """Do nothing (already handled by Python 3 infrastructure)."""
47         return ex
48
49     def items(x):
50         return x.items()
51
52     def argv_bytes(x):
53         """Return the original bytes passed to main() for an argv argument."""
54         return fsencode(x)
55
56     def bytes_from_uint(i):
57         return bytes((i,))
58
59     byte_int = lambda x: x
60
61     def buffer(object, offset=None, size=None):
62         if size:
63             assert offset is not None
64             return memoryview(object)[offset:offset + size]
65         if offset:
66             return memoryview(object)[offset:]
67         return memoryview(object)
68
69     def join_bytes(*items):
70         """Return the concatenated bytes or memoryview arguments as bytes."""
71         return b''.join(items)
72
73 else:  # Python 2
74
75     def fsencode(x):
76         return x
77
78     from pipes import quote
79     from os import environ
80
81     from bup.py2raise import reraise
82
83     range = xrange
84     str_type = basestring
85     int_types = (int, long)
86
87     hexstr = hexlify
88
89     def add_ex_tb(ex):
90         """Add a traceback to ex if it doesn't already have one.  Return ex.
91
92         """
93         if not getattr(ex, '__traceback__', None):
94             ex.__traceback__ = sys.exc_info()[2]
95         return ex
96
97     def add_ex_ctx(ex, context_ex):
98         """Make context_ex the __context__ of ex (unless it already has one).
99         Return ex.
100
101         """
102         if context_ex:
103             if not getattr(ex, '__context__', None):
104                 ex.__context__ = context_ex
105         return ex
106
107     def dump_traceback(ex):
108         stack = [ex]
109         next_ex = getattr(ex, '__context__', None)
110         while next_ex:
111             stack.append(next_ex)
112             next_ex = getattr(next_ex, '__context__', None)
113         stack = reversed(stack)
114         ex = next(stack)
115         tb = getattr(ex, '__traceback__', None)
116         print_exception(type(ex), ex, tb)
117         for ex in stack:
118             print('\nDuring handling of the above exception, another exception occurred:\n',
119                   file=sys.stderr)
120             tb = getattr(ex, '__traceback__', None)
121             print_exception(type(ex), ex, tb)
122
123     def items(x):
124         return x.iteritems()
125
126     def argv_bytes(x):
127         """Return the original bytes passed to main() for an argv argument."""
128         return x
129
130     def bytes_from_uint(i):
131         return chr(i)
132
133     byte_int = ord
134
135     buffer = buffer
136
137     def join_bytes(x, y):
138         """Return the concatenated bytes or buffer arguments as bytes."""
139         if type(x) == buffer:
140             assert type(y) in (bytes, buffer)
141             return x + y
142         assert type(x) == bytes
143         if type(y) == bytes:
144             return b''.join((x, y))
145         assert type(y) in (bytes, buffer)
146         return buffer(x) + y
147
148
149 def restore_lc_env():
150     # Once we're up and running with iso-8859-1, undo the bup-python
151     # LC_CTYPE hackery, so we don't affect unrelated subprocesses.
152     bup_lc_all = environ.get(b'BUP_LC_ALL')
153     if bup_lc_all:
154         del environ[b'LC_COLLATE']
155         del environ[b'LC_CTYPE']
156         del environ[b'LC_MONETARY']
157         del environ[b'LC_NUMERIC']
158         del environ[b'LC_TIME']
159         del environ[b'LC_MESSAGES']
160         del environ[b'LC_MESSAGES']
161         environ[b'LC_ALL'] = bup_lc_all
162         return
163     bup_lc_ctype = environ.get(b'BUP_LC_CTYPE')
164     if bup_lc_ctype:
165         environ[b'LC_CTYPE'] = bup_lc_ctype
166
167 def wrap_main(main):
168     """Run main() and raise a SystemExit with the return value if it
169     returns, pass along any SystemExit it raises, convert
170     KeyboardInterrupts into exit(130), and print a Python 3 style
171     contextual backtrace for other exceptions in both Python 2 and
172     3)."""
173     try:
174         sys.exit(main())
175     except KeyboardInterrupt as ex:
176         sys.exit(130)
177     except SystemExit as ex:
178         raise
179     except BaseException as ex:
180         if py3:
181             raise
182         add_ex_tb(ex)
183         dump_traceback(ex)
184         sys.exit(1)
185
186
187 # Excepting wrap_main() in the traceback, these should produce similar output:
188 #   python2 lib/bup/compat.py
189 #   python3 lib/bup/compat.py
190 # i.e.:
191 #   diff -u <(python2 lib/bup/compat.py 2>&1) <(python3 lib/bup/compat.py 2>&1)
192 #
193 # Though the python3 output for 'second' will include a stacktrace
194 # starting from wrap_main, rather than from outer().
195
196 if __name__ == '__main__':
197
198     def inner():
199         raise Exception('first')
200
201     def outer():
202         try:
203             inner()
204         except Exception as ex:
205             add_ex_tb(ex)
206             try:
207                 raise Exception('second')
208             except Exception as ex2:
209                 raise add_ex_ctx(add_ex_tb(ex2), ex)
210
211     wrap_main(outer)