]> arthur.barton.de Git - bup.git/blob - lib/bup/compat.py
hashsplit: replace join_bytes with cat_bytes
[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 getcwd():
74         return fsencode(os.getcwd())
75
76 else:  # Python 2
77
78     def fsdecode(x):
79         return x
80
81     def fsencode(x):
82         return x
83
84     from pipes import quote
85     from os import environ, getcwd
86
87     from bup.py2raise import reraise
88
89     input = raw_input
90     range = xrange
91     str_type = basestring
92     int_types = (int, long)
93
94     hexstr = hexlify
95
96     def add_ex_tb(ex):
97         """Add a traceback to ex if it doesn't already have one.  Return ex.
98
99         """
100         if not getattr(ex, '__traceback__', None):
101             ex.__traceback__ = sys.exc_info()[2]
102         return ex
103
104     def add_ex_ctx(ex, context_ex):
105         """Make context_ex the __context__ of ex (unless it already has one).
106         Return ex.
107
108         """
109         if context_ex:
110             if not getattr(ex, '__context__', None):
111                 ex.__context__ = context_ex
112         return ex
113
114     def dump_traceback(ex):
115         stack = [ex]
116         next_ex = getattr(ex, '__context__', None)
117         while next_ex:
118             stack.append(next_ex)
119             next_ex = getattr(next_ex, '__context__', None)
120         stack = reversed(stack)
121         ex = next(stack)
122         tb = getattr(ex, '__traceback__', None)
123         print_exception(type(ex), ex, tb)
124         for ex in stack:
125             print('\nDuring handling of the above exception, another exception occurred:\n',
126                   file=sys.stderr)
127             tb = getattr(ex, '__traceback__', None)
128             print_exception(type(ex), ex, tb)
129
130     def items(x):
131         return x.iteritems()
132
133     def argv_bytes(x):
134         """Return the original bytes passed to main() for an argv argument."""
135         return x
136
137     def bytes_from_uint(i):
138         return chr(i)
139
140     def bytes_from_byte(b):
141         return b
142
143     byte_int = ord
144
145     buffer = buffer
146
147
148 def restore_lc_env():
149     # Once we're up and running with iso-8859-1, undo the bup-python
150     # LC_CTYPE hackery, so we don't affect unrelated subprocesses.
151     bup_lc_all = environ.get(b'BUP_LC_ALL')
152     if bup_lc_all:
153         del environ[b'LC_COLLATE']
154         del environ[b'LC_CTYPE']
155         del environ[b'LC_MONETARY']
156         del environ[b'LC_NUMERIC']
157         del environ[b'LC_TIME']
158         del environ[b'LC_MESSAGES']
159         del environ[b'LC_MESSAGES']
160         environ[b'LC_ALL'] = bup_lc_all
161         return
162     bup_lc_ctype = environ.get(b'BUP_LC_CTYPE')
163     if bup_lc_ctype:
164         environ[b'LC_CTYPE'] = bup_lc_ctype
165
166 def wrap_main(main):
167     """Run main() and raise a SystemExit with the return value if it
168     returns, pass along any SystemExit it raises, convert
169     KeyboardInterrupts into exit(130), and print a Python 3 style
170     contextual backtrace for other exceptions in both Python 2 and
171     3)."""
172     try:
173         sys.exit(main())
174     except KeyboardInterrupt as ex:
175         sys.exit(130)
176     except SystemExit as ex:
177         raise
178     except BaseException as ex:
179         if py3:
180             raise
181         add_ex_tb(ex)
182         dump_traceback(ex)
183         sys.exit(1)
184
185
186 # Excepting wrap_main() in the traceback, these should produce similar output:
187 #   python2 lib/bup/compat.py
188 #   python3 lib/bup/compat.py
189 # i.e.:
190 #   diff -u <(python2 lib/bup/compat.py 2>&1) <(python3 lib/bup/compat.py 2>&1)
191 #
192 # Though the python3 output for 'second' will include a stacktrace
193 # starting from wrap_main, rather than from outer().
194
195 if __name__ == '__main__':
196
197     def inner():
198         raise Exception('first')
199
200     def outer():
201         try:
202             inner()
203         except Exception as ex:
204             add_ex_tb(ex)
205             try:
206                 raise Exception('second')
207             except Exception as ex2:
208                 raise add_ex_ctx(add_ex_tb(ex2), ex)
209
210     wrap_main(outer)