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