Fix [ 130 ] support streams expectiong byte-strings in ErrorOutput.
[docutils.git] / docutils / docutils / utils / error_reporting.py
blobf56a3a770b4b2ee9f75190557b92b39ce906b8cc
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
4 # :Id: $Id$
5 # :Copyright: © 2011 Günter Milde.
6 # :License: Released under the terms of the `2-Clause BSD license`_, in short:
8 # Copying and distribution of this file, with or without modification,
9 # are permitted in any medium without royalty provided the copyright
10 # notice and this notice are preserved.
11 # This file is offered as-is, without any warranty.
13 # .. _2-Clause BSD license: http://www.spdx.org/licenses/BSD-2-Clause
15 """
16 Error reporting should be safe from encoding/decoding errors.
17 However, implicit conversions of strings and exceptions like
19 >>> u'%s world: %s' % ('H\xe4llo', Exception(u'H\xe4llo')
21 fail in some Python versions:
23 * In Python <= 2.6, ``unicode(<exception instance>)`` uses
24 `__str__` and fails with non-ASCII chars in`unicode` arguments.
25 (work around http://bugs.python.org/issue2517):
27 * In Python 2, unicode(<exception instance>) fails, with non-ASCII
28 chars in arguments. (Use case: in some locales, the errstr
29 argument of IOError contains non-ASCII chars.)
31 * In Python 2, str(<exception instance>) fails, with non-ASCII chars
32 in `unicode` arguments.
34 The `SafeString`, `ErrorString` and `ErrorOutput` classes handle
35 common exceptions.
36 """
38 import sys, codecs
40 # Guess the locale's encoding.
41 # If no valid guess can be made, locale_encoding is set to `None`:
42 try:
43 import locale # module missing in Jython
44 except ImportError:
45 locale_encoding = None
46 else:
47 locale_encoding = locale.getlocale()[1] or locale.getdefaultlocale()[1]
48 # locale.getpreferredencoding([do_setlocale=True|False])
49 # has side-effects | might return a wrong guess.
50 # (cf. Update 1 in http://stackoverflow.com/questions/4082645/using-python-2-xs-locale-module-to-format-numbers-and-currency)
51 try:
52 codecs.lookup(locale_encoding or '') # None -> ''
53 except LookupError:
54 locale_encoding = None
58 class SafeString(object):
59 """
60 A wrapper providing robust conversion to `str` and `unicode`.
61 """
63 def __init__(self, data, encoding=None, encoding_errors='backslashreplace',
64 decoding_errors='replace'):
65 self.data = data
66 self.encoding = (encoding or getattr(data, 'encoding', None) or
67 locale_encoding or 'ascii')
68 self.encoding_errors = encoding_errors
69 self.decoding_errors = decoding_errors
72 def __str__(self):
73 try:
74 return str(self.data)
75 except UnicodeEncodeError, err:
76 if isinstance(self.data, Exception):
77 args = [str(SafeString(arg, self.encoding,
78 self.encoding_errors))
79 for arg in self.data.args]
80 return ', '.join(args)
81 if isinstance(self.data, unicode):
82 if sys.version_info > (3,0):
83 return self.data
84 else:
85 return self.data.encode(self.encoding,
86 self.encoding_errors)
87 raise
89 def __unicode__(self):
90 """
91 Return unicode representation of `self.data`.
93 Try ``unicode(self.data)``, catch `UnicodeError` and
95 * if `self.data` is an Exception instance, work around
96 http://bugs.python.org/issue2517 with an emulation of
97 Exception.__unicode__,
99 * else decode with `self.encoding` and `self.decoding_errors`.
101 try:
102 u = unicode(self.data)
103 if isinstance(self.data, EnvironmentError):
104 u = u.replace(": u'", ": '") # normalize filename quoting
105 return u
106 except UnicodeError, error: # catch ..Encode.. and ..Decode.. errors
107 if isinstance(self.data, EnvironmentError):
108 return u"[Errno %s] %s: '%s'" % (self.data.errno,
109 SafeString(self.data.strerror, self.encoding,
110 self.decoding_errors),
111 SafeString(self.data.filename, self.encoding,
112 self.decoding_errors))
113 if isinstance(self.data, Exception):
114 args = [unicode(SafeString(arg, self.encoding,
115 decoding_errors=self.decoding_errors))
116 for arg in self.data.args]
117 return u', '.join(args)
118 if isinstance(error, UnicodeDecodeError):
119 return unicode(self.data, self.encoding, self.decoding_errors)
120 raise
122 class ErrorString(SafeString):
124 Safely report exception type and message.
126 def __str__(self):
127 return '%s: %s' % (self.data.__class__.__name__,
128 super(ErrorString, self).__str__())
130 def __unicode__(self):
131 return u'%s: %s' % (self.data.__class__.__name__,
132 super(ErrorString, self).__unicode__())
135 class ErrorOutput(object):
137 Wrapper class for file-like error streams with
138 failsave de- and encoding of `str`, `bytes`, `unicode` and
139 `Exception` instances.
142 def __init__(self, stream=None, encoding=None,
143 encoding_errors='backslashreplace',
144 decoding_errors='replace'):
146 :Parameters:
147 - `stream`: a file-like object,
148 a string (path to a file),
149 `None` (write to `sys.stderr`, default), or
150 evaluating to `False` (write() requests are ignored).
151 - `encoding`: `stream` text encoding. Guessed if None.
152 - `encoding_errors`: how to treat encoding errors.
154 if stream is None:
155 stream = sys.stderr
156 elif not(stream):
157 stream = False
158 # if `stream` is a file name, open it
159 elif isinstance(stream, str):
160 stream = open(stream, 'w')
161 elif isinstance(stream, unicode):
162 stream = open(stream.encode(sys.getfilesystemencoding()), 'w')
164 self.stream = stream
165 """Where warning output is sent."""
167 self.encoding = (encoding or getattr(stream, 'encoding', None) or
168 locale_encoding or 'ascii')
169 """The output character encoding."""
171 self.encoding_errors = encoding_errors
172 """Encoding error handler."""
174 self.decoding_errors = decoding_errors
175 """Decoding error handler."""
177 def write(self, data):
179 Write `data` to self.stream. Ignore, if self.stream is False.
181 `data` can be a `string`, `unicode`, or `Exception` instance.
183 if self.stream is False:
184 return
185 if isinstance(data, Exception):
186 data = unicode(SafeString(data, self.encoding,
187 self.encoding_errors, self.decoding_errors))
188 try:
189 self.stream.write(data)
190 except UnicodeEncodeError:
191 self.stream.write(data.encode(self.encoding, self.encoding_errors))
192 except TypeError:
193 if isinstance(data, unicode): # passed stream may expect bytes
194 self.stream.write(data.encode(self.encoding,
195 self.encoding_errors))
196 return
197 if self.stream in (sys.stderr, sys.stdout):
198 self.stream.buffer.write(data) # write bytes to raw stream
199 else:
200 self.stream.write(unicode(data, self.encoding,
201 self.decoding_errors))
203 def close(self):
205 Close the error-output stream.
207 Ignored if the stream is` sys.stderr` or `sys.stdout` or has no
208 close() method.
210 if self.stream in (sys.stdout, sys.stderr):
211 return
212 try:
213 self.stream.close()
214 except AttributeError:
215 pass