Update TODO list.
[docutils.git] / docutils / io.py
blobbdff123cdf414cf49102e817b7b43595efd9095d
1 # $Id$
2 # Author: David Goodger <goodger@python.org>
3 # Copyright: This module has been placed in the public domain.
5 """
6 I/O classes provide a uniform API for low-level input and output. Subclasses
7 exist for a variety of input/output mechanisms.
8 """
10 __docformat__ = 'reStructuredText'
12 import sys
13 import os
14 import re
15 import codecs
16 from docutils import TransformSpec
17 from docutils._compat import b
18 from docutils.utils.error_reporting import locale_encoding, ErrorString, ErrorOutput
21 class InputError(IOError): pass
22 class OutputError(IOError): pass
24 def check_encoding(stream, encoding):
25 """Test, whether the encoding of `stream` matches `encoding`.
27 Returns
29 :None: if `encoding` or `stream.encoding` are not a valid encoding
30 argument (e.g. ``None``) or `stream.encoding is missing.
31 :True: if the encoding argument resolves to the same value as `encoding`,
32 :False: if the encodings differ.
33 """
34 try:
35 return codecs.lookup(stream.encoding) == codecs.lookup(encoding)
36 except (LookupError, AttributeError, TypeError):
37 return None
40 class Input(TransformSpec):
42 """
43 Abstract base class for input wrappers.
44 """
46 component_type = 'input'
48 default_source_path = None
50 def __init__(self, source=None, source_path=None, encoding=None,
51 error_handler='strict'):
52 self.encoding = encoding
53 """Text encoding for the input source."""
55 self.error_handler = error_handler
56 """Text decoding error handler."""
58 self.source = source
59 """The source of input data."""
61 self.source_path = source_path
62 """A text reference to the source."""
64 if not source_path:
65 self.source_path = self.default_source_path
67 self.successful_encoding = None
68 """The encoding that successfully decoded the source data."""
70 def __repr__(self):
71 return '%s: source=%r, source_path=%r' % (self.__class__, self.source,
72 self.source_path)
74 def read(self):
75 raise NotImplementedError
77 def decode(self, data):
78 """
79 Decode a string, `data`, heuristically.
80 Raise UnicodeError if unsuccessful.
82 The client application should call ``locale.setlocale`` at the
83 beginning of processing::
85 locale.setlocale(locale.LC_ALL, '')
86 """
87 if self.encoding and self.encoding.lower() == 'unicode':
88 assert isinstance(data, unicode), (
89 'input encoding is "unicode" '
90 'but input is not a unicode object')
91 if isinstance(data, unicode):
92 # Accept unicode even if self.encoding != 'unicode'.
93 return data
94 if self.encoding:
95 # We believe the user/application when the encoding is
96 # explicitly given.
97 encodings = [self.encoding]
98 else:
99 data_encoding = self.determine_encoding_from_data(data)
100 if data_encoding:
101 # If the data declares its encoding (explicitly or via a BOM),
102 # we believe it.
103 encodings = [data_encoding]
104 else:
105 # Apply heuristics only if no encoding is explicitly given and
106 # no BOM found. Start with UTF-8, because that only matches
107 # data that *IS* UTF-8:
108 encodings = ['utf-8', 'latin-1']
109 if locale_encoding:
110 encodings.insert(1, locale_encoding)
111 for enc in encodings:
112 try:
113 decoded = unicode(data, enc, self.error_handler)
114 self.successful_encoding = enc
115 # Return decoded, removing BOMs.
116 return decoded.replace(u'\ufeff', u'')
117 except (UnicodeError, LookupError), err:
118 error = err # in Python 3, the <exception instance> is
119 # local to the except clause
120 raise UnicodeError(
121 'Unable to decode input data. Tried the following encodings: '
122 '%s.\n(%s)' % (', '.join([repr(enc) for enc in encodings]),
123 ErrorString(error)))
125 coding_slug = re.compile(b("coding[:=]\s*([-\w.]+)"))
126 """Encoding declaration pattern."""
128 byte_order_marks = ((codecs.BOM_UTF8, 'utf-8'), # 'utf-8-sig' new in v2.5
129 (codecs.BOM_UTF16_BE, 'utf-16-be'),
130 (codecs.BOM_UTF16_LE, 'utf-16-le'),)
131 """Sequence of (start_bytes, encoding) tuples for encoding detection.
132 The first bytes of input data are checked against the start_bytes strings.
133 A match indicates the given encoding."""
135 def determine_encoding_from_data(self, data):
137 Try to determine the encoding of `data` by looking *in* `data`.
138 Check for a byte order mark (BOM) or an encoding declaration.
140 # check for a byte order mark:
141 for start_bytes, encoding in self.byte_order_marks:
142 if data.startswith(start_bytes):
143 return encoding
144 # check for an encoding declaration pattern in first 2 lines of file:
145 for line in data.splitlines()[:2]:
146 match = self.coding_slug.search(line)
147 if match:
148 return match.group(1).decode('ascii')
149 return None
152 class Output(TransformSpec):
155 Abstract base class for output wrappers.
158 component_type = 'output'
160 default_destination_path = None
162 def __init__(self, destination=None, destination_path=None,
163 encoding=None, error_handler='strict'):
164 self.encoding = encoding
165 """Text encoding for the output destination."""
167 self.error_handler = error_handler or 'strict'
168 """Text encoding error handler."""
170 self.destination = destination
171 """The destination for output data."""
173 self.destination_path = destination_path
174 """A text reference to the destination."""
176 if not destination_path:
177 self.destination_path = self.default_destination_path
179 def __repr__(self):
180 return ('%s: destination=%r, destination_path=%r'
181 % (self.__class__, self.destination, self.destination_path))
183 def write(self, data):
184 """`data` is a Unicode string, to be encoded by `self.encode`."""
185 raise NotImplementedError
187 def encode(self, data):
188 if self.encoding and self.encoding.lower() == 'unicode':
189 assert isinstance(data, unicode), (
190 'the encoding given is "unicode" but the output is not '
191 'a Unicode string')
192 return data
193 if not isinstance(data, unicode):
194 # Non-unicode (e.g. bytes) output.
195 return data
196 else:
197 return data.encode(self.encoding, self.error_handler)
200 class FileInput(Input):
203 Input for single, simple file-like objects.
205 def __init__(self, source=None, source_path=None,
206 encoding=None, error_handler='strict',
207 autoclose=True, mode='rU'):
209 :Parameters:
210 - `source`: either a file-like object (which is read directly), or
211 `None` (which implies `sys.stdin` if no `source_path` given).
212 - `source_path`: a path to a file, which is opened and then read.
213 - `encoding`: the expected text encoding of the input file.
214 - `error_handler`: the encoding error handler to use.
215 - `autoclose`: close automatically after read (except when
216 `sys.stdin` is the source).
217 - `mode`: how the file is to be opened (see standard function
218 `open`). The default 'rU' provides universal newline support
219 for text files.
221 Input.__init__(self, source, source_path, encoding, error_handler)
222 self.autoclose = autoclose
223 self._stderr = ErrorOutput()
225 if source is None:
226 if source_path:
227 # Specify encoding in Python 3
228 if sys.version_info >= (3,0):
229 kwargs = {'encoding': self.encoding,
230 'errors': self.error_handler}
231 else:
232 kwargs = {}
234 try:
235 self.source = open(source_path, mode, **kwargs)
236 except IOError, error:
237 raise InputError(error.errno, error.strerror, source_path)
238 else:
239 self.source = sys.stdin
240 elif (sys.version_info >= (3,0) and
241 check_encoding(self.source, self.encoding) is False):
242 # TODO: re-open, warn or raise error?
243 raise UnicodeError('Encoding clash: encoding given is "%s" '
244 'but source is opened with encoding "%s".' %
245 (self.encoding, self.source.encoding))
246 if not source_path:
247 try:
248 self.source_path = self.source.name
249 except AttributeError:
250 pass
252 def read(self):
254 Read and decode a single file and return the data (Unicode string).
256 try: # In Python < 2.5, try...except has to be nested in try...finally.
257 try:
258 if self.source is sys.stdin and sys.version_info >= (3,0):
259 # read as binary data to circumvent auto-decoding
260 data = self.source.buffer.read()
261 # normalize newlines
262 data = b('\n').join(data.splitlines()) + b('\n')
263 else:
264 data = self.source.read()
265 except (UnicodeError, LookupError), err: # (in Py3k read() decodes)
266 if not self.encoding and self.source_path:
267 # re-read in binary mode and decode with heuristics
268 b_source = open(self.source_path, 'rb')
269 data = b_source.read()
270 b_source.close()
271 # normalize newlines
272 data = b('\n').join(data.splitlines()) + b('\n')
273 else:
274 raise
275 finally:
276 if self.autoclose:
277 self.close()
278 return self.decode(data)
280 def readlines(self):
282 Return lines of a single file as list of Unicode strings.
284 return self.read().splitlines(True)
286 def close(self):
287 if self.source is not sys.stdin:
288 self.source.close()
291 class FileOutput(Output):
294 Output for single, simple file-like objects.
297 mode = 'w'
298 """The mode argument for `open()`."""
299 # 'wb' for binary (e.g. OpenOffice) files (see also `BinaryFileOutput`).
300 # (Do not use binary mode ('wb') for text files, as this prevents the
301 # conversion of newlines to the system specific default.)
303 def __init__(self, destination=None, destination_path=None,
304 encoding=None, error_handler='strict', autoclose=True,
305 mode=None):
307 :Parameters:
308 - `destination`: either a file-like object (which is written
309 directly) or `None` (which implies `sys.stdout` if no
310 `destination_path` given).
311 - `destination_path`: a path to a file, which is opened and then
312 written.
313 - `encoding`: the text encoding of the output file.
314 - `error_handler`: the encoding error handler to use.
315 - `autoclose`: close automatically after write (except when
316 `sys.stdout` or `sys.stderr` is the destination).
317 - `mode`: how the file is to be opened (see standard function
318 `open`). The default is 'w', providing universal newline
319 support for text files.
321 Output.__init__(self, destination, destination_path,
322 encoding, error_handler)
323 self.opened = True
324 self.autoclose = autoclose
325 if mode is not None:
326 self.mode = mode
327 self._stderr = ErrorOutput()
328 if destination is None:
329 if destination_path:
330 self.opened = False
331 else:
332 self.destination = sys.stdout
333 elif (# destination is file-type object -> check mode:
334 mode and hasattr(self.destination, 'mode')
335 and mode != self.destination.mode):
336 print >>self._stderr, ('Warning: Destination mode "%s" '
337 'differs from specified mode "%s"' %
338 (self.destination.mode, mode))
339 if not destination_path:
340 try:
341 self.destination_path = self.destination.name
342 except AttributeError:
343 pass
345 def open(self):
346 # Specify encoding in Python 3.
347 if sys.version_info >= (3,0) and 'b' not in self.mode:
348 kwargs = {'encoding': self.encoding,
349 'errors': self.error_handler}
350 else:
351 kwargs = {}
352 try:
353 self.destination = open(self.destination_path, self.mode, **kwargs)
354 except IOError, error:
355 raise OutputError(error.errno, error.strerror,
356 self.destination_path)
357 self.opened = True
359 def write(self, data):
360 """Encode `data`, write it to a single file, and return it.
362 With Python 3 or binary output mode, `data` is returned unchanged,
363 except when specified encoding and output encoding differ.
365 if not self.opened:
366 self.open()
367 if ('b' not in self.mode and sys.version_info < (3,0)
368 or check_encoding(self.destination, self.encoding) is False
370 data = self.encode(data)
371 if sys.version_info >= (3,0) and os.linesep != '\n':
372 data = data.replace(b('\n'), b(os.linesep)) # fix endings
374 try: # In Python < 2.5, try...except has to be nested in try...finally.
375 try:
376 self.destination.write(data)
377 except TypeError, e:
378 if sys.version_info >= (3,0) and isinstance(data, bytes):
379 try:
380 self.destination.buffer.write(data)
381 except AttributeError:
382 if check_encoding(self.destination,
383 self.encoding) is False:
384 raise ValueError('Encoding of %s (%s) differs \n'
385 ' from specified encoding (%s)' %
386 (self.destination_path or 'destination',
387 self.destination.encoding, self.encoding))
388 else:
389 raise e
390 except (UnicodeError, LookupError), err:
391 raise UnicodeError(
392 'Unable to encode output data. output-encoding is: '
393 '%s.\n(%s)' % (self.encoding, ErrorString(err)))
394 finally:
395 if self.autoclose:
396 self.close()
397 return data
399 def close(self):
400 if self.destination not in (sys.stdout, sys.stderr):
401 self.destination.close()
402 self.opened = False
405 class BinaryFileOutput(FileOutput):
407 A version of docutils.io.FileOutput which writes to a binary file.
409 # Used by core.publish_cmdline_to_binary() which in turn is used by
410 # rst2odt (OpenOffice writer)
411 mode = 'wb'
414 class StringInput(Input):
417 Direct string input.
420 default_source_path = '<string>'
422 def read(self):
423 """Decode and return the source string."""
424 return self.decode(self.source)
427 class StringOutput(Output):
430 Direct string output.
433 default_destination_path = '<string>'
435 def write(self, data):
436 """Encode `data`, store it in `self.destination`, and return it."""
437 self.destination = self.encode(data)
438 return self.destination
441 class NullInput(Input):
444 Degenerate input: read nothing.
447 default_source_path = 'null input'
449 def read(self):
450 """Return a null string."""
451 return u''
454 class NullOutput(Output):
457 Degenerate output: write nothing.
460 default_destination_path = 'null output'
462 def write(self, data):
463 """Do nothing ([don't even] send data to the bit bucket)."""
464 pass
467 class DocTreeInput(Input):
470 Adapter for document tree input.
472 The document tree must be passed in the ``source`` parameter.
475 default_source_path = 'doctree input'
477 def read(self):
478 """Return the document tree."""
479 return self.source