blob: ffcf812564efe1353854cf45c0565dd6aca017ff [file] [log] [blame]
Nadeem Vawda3ff069e2011-11-30 00:25:06 +02001"""Interface to the liblzma compression library.
2
3This module provides a class for reading and writing compressed files,
4classes for incremental (de)compression, and convenience functions for
5one-shot (de)compression.
6
7These classes and functions support both the XZ and legacy LZMA
8container formats, as well as raw compressed data streams.
9"""
10
11__all__ = [
12 "CHECK_NONE", "CHECK_CRC32", "CHECK_CRC64", "CHECK_SHA256",
13 "CHECK_ID_MAX", "CHECK_UNKNOWN",
14 "FILTER_LZMA1", "FILTER_LZMA2", "FILTER_DELTA", "FILTER_X86", "FILTER_IA64",
15 "FILTER_ARM", "FILTER_ARMTHUMB", "FILTER_POWERPC", "FILTER_SPARC",
16 "FORMAT_AUTO", "FORMAT_XZ", "FORMAT_ALONE", "FORMAT_RAW",
17 "MF_HC3", "MF_HC4", "MF_BT2", "MF_BT3", "MF_BT4",
18 "MODE_FAST", "MODE_NORMAL", "PRESET_DEFAULT", "PRESET_EXTREME",
19
20 "LZMACompressor", "LZMADecompressor", "LZMAFile", "LZMAError",
Nadeem Vawdae8604042012-06-04 23:38:12 +020021 "open", "compress", "decompress", "is_check_supported",
Nadeem Vawda3ff069e2011-11-30 00:25:06 +020022]
23
Nadeem Vawdae8604042012-06-04 23:38:12 +020024import builtins
Nadeem Vawda3ff069e2011-11-30 00:25:06 +020025import io
26from _lzma import *
Nadeem Vawdaa425c3d2012-06-21 23:36:48 +020027from _lzma import _encode_filter_properties, _decode_filter_properties
Nadeem Vawda3ff069e2011-11-30 00:25:06 +020028
29
30_MODE_CLOSED = 0
31_MODE_READ = 1
32_MODE_READ_EOF = 2
33_MODE_WRITE = 3
34
35_BUFFER_SIZE = 8192
36
37
38class LZMAFile(io.BufferedIOBase):
39
40 """A file object providing transparent LZMA (de)compression.
41
42 An LZMAFile can act as a wrapper for an existing file object, or
43 refer directly to a named file on disk.
44
45 Note that LZMAFile provides a *binary* file interface - data read
46 is returned as bytes, and data to be written must be given as bytes.
47 """
48
49 def __init__(self, filename=None, mode="r", *,
Nadeem Vawda33c34da2012-06-04 23:34:07 +020050 format=None, check=-1, preset=None, filters=None):
51 """Open an LZMA-compressed file in binary mode.
Nadeem Vawda3ff069e2011-11-30 00:25:06 +020052
Nadeem Vawda33c34da2012-06-04 23:34:07 +020053 filename can be either an actual file name (given as a str or
54 bytes object), in which case the named file is opened, or it can
55 be an existing file object to read from or write to.
Nadeem Vawda3ff069e2011-11-30 00:25:06 +020056
57 mode can be "r" for reading (default), "w" for (over)writing, or
Nadeem Vawda6cbb20c2012-06-04 23:36:24 +020058 "a" for appending. These can equivalently be given as "rb", "wb",
59 and "ab" respectively.
Nadeem Vawda3ff069e2011-11-30 00:25:06 +020060
61 format specifies the container format to use for the file.
62 If mode is "r", this defaults to FORMAT_AUTO. Otherwise, the
63 default is FORMAT_XZ.
64
65 check specifies the integrity check to use. This argument can
66 only be used when opening a file for writing. For FORMAT_XZ,
67 the default is CHECK_CRC64. FORMAT_ALONE and FORMAT_RAW do not
68 support integrity checks - for these formats, check must be
69 omitted, or be CHECK_NONE.
70
71 When opening a file for reading, the *preset* argument is not
72 meaningful, and should be omitted. The *filters* argument should
73 also be omitted, except when format is FORMAT_RAW (in which case
74 it is required).
75
76 When opening a file for writing, the settings used by the
77 compressor can be specified either as a preset compression
78 level (with the *preset* argument), or in detail as a custom
79 filter chain (with the *filters* argument). For FORMAT_XZ and
80 FORMAT_ALONE, the default is to use the PRESET_DEFAULT preset
81 level. For FORMAT_RAW, the caller must always specify a filter
82 chain; the raw compressor does not support preset compression
83 levels.
84
85 preset (if provided) should be an integer in the range 0-9,
86 optionally OR-ed with the constant PRESET_EXTREME.
87
88 filters (if provided) should be a sequence of dicts. Each dict
89 should have an entry for "id" indicating ID of the filter, plus
90 additional entries for options to the filter.
91 """
92 self._fp = None
93 self._closefp = False
94 self._mode = _MODE_CLOSED
95 self._pos = 0
96 self._size = -1
97
Nadeem Vawda6cbb20c2012-06-04 23:36:24 +020098 if mode in ("r", "rb"):
Nadeem Vawda3ff069e2011-11-30 00:25:06 +020099 if check != -1:
100 raise ValueError("Cannot specify an integrity check "
101 "when opening a file for reading")
102 if preset is not None:
103 raise ValueError("Cannot specify a preset compression "
104 "level when opening a file for reading")
105 if format is None:
106 format = FORMAT_AUTO
107 mode_code = _MODE_READ
108 # Save the args to pass to the LZMADecompressor initializer.
109 # If the file contains multiple compressed streams, each
110 # stream will need a separate decompressor object.
111 self._init_args = {"format":format, "filters":filters}
112 self._decompressor = LZMADecompressor(**self._init_args)
113 self._buffer = None
Nadeem Vawda6cbb20c2012-06-04 23:36:24 +0200114 elif mode in ("w", "wb", "a", "ab"):
Nadeem Vawda3ff069e2011-11-30 00:25:06 +0200115 if format is None:
116 format = FORMAT_XZ
117 mode_code = _MODE_WRITE
118 self._compressor = LZMACompressor(format=format, check=check,
119 preset=preset, filters=filters)
120 else:
121 raise ValueError("Invalid mode: {!r}".format(mode))
122
Nadeem Vawda33c34da2012-06-04 23:34:07 +0200123 if isinstance(filename, (str, bytes)):
Nadeem Vawda6cbb20c2012-06-04 23:36:24 +0200124 if "b" not in mode:
125 mode += "b"
Nadeem Vawdae8604042012-06-04 23:38:12 +0200126 self._fp = builtins.open(filename, mode)
Nadeem Vawda3ff069e2011-11-30 00:25:06 +0200127 self._closefp = True
128 self._mode = mode_code
Nadeem Vawda33c34da2012-06-04 23:34:07 +0200129 elif hasattr(filename, "read") or hasattr(filename, "write"):
130 self._fp = filename
Nadeem Vawda3ff069e2011-11-30 00:25:06 +0200131 self._mode = mode_code
132 else:
Nadeem Vawda33c34da2012-06-04 23:34:07 +0200133 raise TypeError("filename must be a str or bytes object, or a file")
Nadeem Vawda3ff069e2011-11-30 00:25:06 +0200134
135 def close(self):
136 """Flush and close the file.
137
138 May be called more than once without error. Once the file is
139 closed, any other operation on it will raise a ValueError.
140 """
141 if self._mode == _MODE_CLOSED:
142 return
143 try:
144 if self._mode in (_MODE_READ, _MODE_READ_EOF):
145 self._decompressor = None
146 self._buffer = None
147 elif self._mode == _MODE_WRITE:
148 self._fp.write(self._compressor.flush())
149 self._compressor = None
150 finally:
151 try:
152 if self._closefp:
153 self._fp.close()
154 finally:
155 self._fp = None
156 self._closefp = False
157 self._mode = _MODE_CLOSED
158
159 @property
160 def closed(self):
161 """True if this file is closed."""
162 return self._mode == _MODE_CLOSED
163
164 def fileno(self):
165 """Return the file descriptor for the underlying file."""
166 self._check_not_closed()
167 return self._fp.fileno()
168
169 def seekable(self):
170 """Return whether the file supports seeking."""
Nadeem Vawdaae557d72012-02-12 01:51:38 +0200171 return self.readable() and self._fp.seekable()
Nadeem Vawda3ff069e2011-11-30 00:25:06 +0200172
173 def readable(self):
174 """Return whether the file was opened for reading."""
175 self._check_not_closed()
176 return self._mode in (_MODE_READ, _MODE_READ_EOF)
177
178 def writable(self):
179 """Return whether the file was opened for writing."""
180 self._check_not_closed()
181 return self._mode == _MODE_WRITE
182
183 # Mode-checking helper functions.
184
185 def _check_not_closed(self):
186 if self.closed:
187 raise ValueError("I/O operation on closed file")
188
189 def _check_can_read(self):
190 if not self.readable():
191 raise io.UnsupportedOperation("File not open for reading")
192
193 def _check_can_write(self):
194 if not self.writable():
195 raise io.UnsupportedOperation("File not open for writing")
196
197 def _check_can_seek(self):
Nadeem Vawdaae557d72012-02-12 01:51:38 +0200198 if not self.readable():
Nadeem Vawda3ff069e2011-11-30 00:25:06 +0200199 raise io.UnsupportedOperation("Seeking is only supported "
200 "on files open for reading")
Nadeem Vawdaae557d72012-02-12 01:51:38 +0200201 if not self._fp.seekable():
202 raise io.UnsupportedOperation("The underlying file object "
203 "does not support seeking")
Nadeem Vawda3ff069e2011-11-30 00:25:06 +0200204
205 # Fill the readahead buffer if it is empty. Returns False on EOF.
206 def _fill_buffer(self):
207 if self._buffer:
208 return True
209
210 if self._decompressor.unused_data:
211 rawblock = self._decompressor.unused_data
212 else:
213 rawblock = self._fp.read(_BUFFER_SIZE)
214
215 if not rawblock:
216 if self._decompressor.eof:
217 self._mode = _MODE_READ_EOF
218 self._size = self._pos
219 return False
220 else:
221 raise EOFError("Compressed file ended before the "
222 "end-of-stream marker was reached")
223
224 # Continue to next stream.
225 if self._decompressor.eof:
226 self._decompressor = LZMADecompressor(**self._init_args)
227
228 self._buffer = self._decompressor.decompress(rawblock)
229 return True
230
231 # Read data until EOF.
232 # If return_data is false, consume the data without returning it.
233 def _read_all(self, return_data=True):
234 blocks = []
235 while self._fill_buffer():
236 if return_data:
237 blocks.append(self._buffer)
238 self._pos += len(self._buffer)
239 self._buffer = None
240 if return_data:
241 return b"".join(blocks)
242
243 # Read a block of up to n bytes.
244 # If return_data is false, consume the data without returning it.
245 def _read_block(self, n, return_data=True):
246 blocks = []
247 while n > 0 and self._fill_buffer():
248 if n < len(self._buffer):
249 data = self._buffer[:n]
250 self._buffer = self._buffer[n:]
251 else:
252 data = self._buffer
253 self._buffer = None
254 if return_data:
255 blocks.append(data)
256 self._pos += len(data)
257 n -= len(data)
258 if return_data:
259 return b"".join(blocks)
260
261 def peek(self, size=-1):
262 """Return buffered data without advancing the file position.
263
264 Always returns at least one byte of data, unless at EOF.
265 The exact number of bytes returned is unspecified.
266 """
267 self._check_can_read()
268 if self._mode == _MODE_READ_EOF or not self._fill_buffer():
269 return b""
270 return self._buffer
271
272 def read(self, size=-1):
273 """Read up to size uncompressed bytes from the file.
274
275 If size is negative or omitted, read until EOF is reached.
276 Returns b"" if the file is already at EOF.
277 """
278 self._check_can_read()
279 if self._mode == _MODE_READ_EOF or size == 0:
280 return b""
281 elif size < 0:
282 return self._read_all()
283 else:
284 return self._read_block(size)
285
286 def read1(self, size=-1):
287 """Read up to size uncompressed bytes with at most one read
288 from the underlying stream.
289
290 Returns b"" if the file is at EOF.
291 """
292 self._check_can_read()
293 if (size == 0 or self._mode == _MODE_READ_EOF or
294 not self._fill_buffer()):
295 return b""
296 if 0 < size < len(self._buffer):
297 data = self._buffer[:size]
298 self._buffer = self._buffer[size:]
299 else:
300 data = self._buffer
301 self._buffer = None
302 self._pos += len(data)
303 return data
304
305 def write(self, data):
306 """Write a bytes object to the file.
307
308 Returns the number of uncompressed bytes written, which is
309 always len(data). Note that due to buffering, the file on disk
310 may not reflect the data written until close() is called.
311 """
312 self._check_can_write()
313 compressed = self._compressor.compress(data)
314 self._fp.write(compressed)
315 self._pos += len(data)
316 return len(data)
317
318 # Rewind the file to the beginning of the data stream.
319 def _rewind(self):
320 self._fp.seek(0, 0)
321 self._mode = _MODE_READ
322 self._pos = 0
323 self._decompressor = LZMADecompressor(**self._init_args)
324 self._buffer = None
325
326 def seek(self, offset, whence=0):
327 """Change the file position.
328
329 The new position is specified by offset, relative to the
330 position indicated by whence. Possible values for whence are:
331
332 0: start of stream (default): offset must not be negative
333 1: current stream position
334 2: end of stream; offset must not be positive
335
336 Returns the new file position.
337
338 Note that seeking is emulated, sp depending on the parameters,
339 this operation may be extremely slow.
340 """
341 self._check_can_seek()
342
343 # Recalculate offset as an absolute file position.
344 if whence == 0:
345 pass
346 elif whence == 1:
347 offset = self._pos + offset
348 elif whence == 2:
349 # Seeking relative to EOF - we need to know the file's size.
350 if self._size < 0:
351 self._read_all(return_data=False)
352 offset = self._size + offset
353 else:
354 raise ValueError("Invalid value for whence: {}".format(whence))
355
356 # Make it so that offset is the number of bytes to skip forward.
357 if offset < self._pos:
358 self._rewind()
359 else:
360 offset -= self._pos
361
362 # Read and discard data until we reach the desired position.
363 if self._mode != _MODE_READ_EOF:
364 self._read_block(offset, return_data=False)
365
366 return self._pos
367
368 def tell(self):
369 """Return the current file position."""
370 self._check_not_closed()
371 return self._pos
372
373
Nadeem Vawdae8604042012-06-04 23:38:12 +0200374def open(filename, mode="rb", *,
375 format=None, check=-1, preset=None, filters=None,
376 encoding=None, errors=None, newline=None):
377 """Open an LZMA-compressed file in binary or text mode.
378
379 filename can be either an actual file name (given as a str or bytes object),
380 in which case the named file is opened, or it can be an existing file object
381 to read from or write to.
382
383 The mode argument can be "r", "rb" (default), "w", "wb", "a", or "ab" for
384 binary mode, or "rt", "wt" or "at" for text mode.
385
386 The format, check, preset and filters arguments specify the compression
387 settings, as for LZMACompressor, LZMADecompressor and LZMAFile.
388
389 For binary mode, this function is equivalent to the LZMAFile constructor:
390 LZMAFile(filename, mode, ...). In this case, the encoding, errors and
391 newline arguments must not be provided.
392
393 For text mode, a LZMAFile object is created, and wrapped in an
394 io.TextIOWrapper instance with the specified encoding, error handling
395 behavior, and line ending(s).
396
397 """
398 if "t" in mode:
399 if "b" in mode:
400 raise ValueError("Invalid mode: %r" % (mode,))
401 else:
402 if encoding is not None:
403 raise ValueError("Argument 'encoding' not supported in binary mode")
404 if errors is not None:
405 raise ValueError("Argument 'errors' not supported in binary mode")
406 if newline is not None:
407 raise ValueError("Argument 'newline' not supported in binary mode")
408
409 lz_mode = mode.replace("t", "")
410 binary_file = LZMAFile(filename, lz_mode, format=format, check=check,
411 preset=preset, filters=filters)
412
413 if "t" in mode:
414 return io.TextIOWrapper(binary_file, encoding, errors, newline)
415 else:
416 return binary_file
417
418
Nadeem Vawda3ff069e2011-11-30 00:25:06 +0200419def compress(data, format=FORMAT_XZ, check=-1, preset=None, filters=None):
420 """Compress a block of data.
421
422 Refer to LZMACompressor's docstring for a description of the
423 optional arguments *format*, *check*, *preset* and *filters*.
424
425 For incremental compression, use an LZMACompressor object instead.
426 """
427 comp = LZMACompressor(format, check, preset, filters)
428 return comp.compress(data) + comp.flush()
429
430
431def decompress(data, format=FORMAT_AUTO, memlimit=None, filters=None):
432 """Decompress a block of data.
433
434 Refer to LZMADecompressor's docstring for a description of the
435 optional arguments *format*, *check* and *filters*.
436
437 For incremental decompression, use a LZMADecompressor object instead.
438 """
439 results = []
440 while True:
441 decomp = LZMADecompressor(format, memlimit, filters)
442 results.append(decomp.decompress(data))
443 if not decomp.eof:
444 raise LZMAError("Compressed data ended before the "
445 "end-of-stream marker was reached")
446 if not decomp.unused_data:
447 return b"".join(results)
448 # There is unused data left over. Proceed to next stream.
449 data = decomp.unused_data