lzma.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  1. """Interface to the liblzma compression library.
  2. This module provides a class for reading and writing compressed files,
  3. classes for incremental (de)compression, and convenience functions for
  4. one-shot (de)compression.
  5. These classes and functions support both the XZ and legacy LZMA
  6. container formats, as well as raw compressed data streams.
  7. """
  8. __all__ = [
  9. "CHECK_NONE", "CHECK_CRC32", "CHECK_CRC64", "CHECK_SHA256",
  10. "CHECK_ID_MAX", "CHECK_UNKNOWN",
  11. "FILTER_LZMA1", "FILTER_LZMA2", "FILTER_DELTA", "FILTER_X86", "FILTER_IA64",
  12. "FILTER_ARM", "FILTER_ARMTHUMB", "FILTER_POWERPC", "FILTER_SPARC",
  13. "FORMAT_AUTO", "FORMAT_XZ", "FORMAT_ALONE", "FORMAT_RAW",
  14. "MF_HC3", "MF_HC4", "MF_BT2", "MF_BT3", "MF_BT4",
  15. "MODE_FAST", "MODE_NORMAL", "PRESET_DEFAULT", "PRESET_EXTREME",
  16. "LZMACompressor", "LZMADecompressor", "LZMAFile", "LZMAError",
  17. "open", "compress", "decompress", "is_check_supported",
  18. ]
  19. import builtins
  20. import io
  21. import os
  22. from _lzma import *
  23. from _lzma import _encode_filter_properties, _decode_filter_properties
  24. import _compression
  25. _MODE_CLOSED = 0
  26. _MODE_READ = 1
  27. # Value 2 no longer used
  28. _MODE_WRITE = 3
  29. class LZMAFile(_compression.BaseStream):
  30. """A file object providing transparent LZMA (de)compression.
  31. An LZMAFile can act as a wrapper for an existing file object, or
  32. refer directly to a named file on disk.
  33. Note that LZMAFile provides a *binary* file interface - data read
  34. is returned as bytes, and data to be written must be given as bytes.
  35. """
  36. def __init__(self, filename=None, mode="r", *,
  37. format=None, check=-1, preset=None, filters=None):
  38. """Open an LZMA-compressed file in binary mode.
  39. filename can be either an actual file name (given as a str,
  40. bytes, or PathLike object), in which case the named file is
  41. opened, or it can be an existing file object to read from or
  42. write to.
  43. mode can be "r" for reading (default), "w" for (over)writing,
  44. "x" for creating exclusively, or "a" for appending. These can
  45. equivalently be given as "rb", "wb", "xb" and "ab" respectively.
  46. format specifies the container format to use for the file.
  47. If mode is "r", this defaults to FORMAT_AUTO. Otherwise, the
  48. default is FORMAT_XZ.
  49. check specifies the integrity check to use. This argument can
  50. only be used when opening a file for writing. For FORMAT_XZ,
  51. the default is CHECK_CRC64. FORMAT_ALONE and FORMAT_RAW do not
  52. support integrity checks - for these formats, check must be
  53. omitted, or be CHECK_NONE.
  54. When opening a file for reading, the *preset* argument is not
  55. meaningful, and should be omitted. The *filters* argument should
  56. also be omitted, except when format is FORMAT_RAW (in which case
  57. it is required).
  58. When opening a file for writing, the settings used by the
  59. compressor can be specified either as a preset compression
  60. level (with the *preset* argument), or in detail as a custom
  61. filter chain (with the *filters* argument). For FORMAT_XZ and
  62. FORMAT_ALONE, the default is to use the PRESET_DEFAULT preset
  63. level. For FORMAT_RAW, the caller must always specify a filter
  64. chain; the raw compressor does not support preset compression
  65. levels.
  66. preset (if provided) should be an integer in the range 0-9,
  67. optionally OR-ed with the constant PRESET_EXTREME.
  68. filters (if provided) should be a sequence of dicts. Each dict
  69. should have an entry for "id" indicating ID of the filter, plus
  70. additional entries for options to the filter.
  71. """
  72. self._fp = None
  73. self._closefp = False
  74. self._mode = _MODE_CLOSED
  75. if mode in ("r", "rb"):
  76. if check != -1:
  77. raise ValueError("Cannot specify an integrity check "
  78. "when opening a file for reading")
  79. if preset is not None:
  80. raise ValueError("Cannot specify a preset compression "
  81. "level when opening a file for reading")
  82. if format is None:
  83. format = FORMAT_AUTO
  84. mode_code = _MODE_READ
  85. elif mode in ("w", "wb", "a", "ab", "x", "xb"):
  86. if format is None:
  87. format = FORMAT_XZ
  88. mode_code = _MODE_WRITE
  89. self._compressor = LZMACompressor(format=format, check=check,
  90. preset=preset, filters=filters)
  91. self._pos = 0
  92. else:
  93. raise ValueError("Invalid mode: {!r}".format(mode))
  94. if isinstance(filename, (str, bytes, os.PathLike)):
  95. if "b" not in mode:
  96. mode += "b"
  97. self._fp = builtins.open(filename, mode)
  98. self._closefp = True
  99. self._mode = mode_code
  100. elif hasattr(filename, "read") or hasattr(filename, "write"):
  101. self._fp = filename
  102. self._mode = mode_code
  103. else:
  104. raise TypeError("filename must be a str, bytes, file or PathLike object")
  105. if self._mode == _MODE_READ:
  106. raw = _compression.DecompressReader(self._fp, LZMADecompressor,
  107. trailing_error=LZMAError, format=format, filters=filters)
  108. self._buffer = io.BufferedReader(raw)
  109. def close(self):
  110. """Flush and close the file.
  111. May be called more than once without error. Once the file is
  112. closed, any other operation on it will raise a ValueError.
  113. """
  114. if self._mode == _MODE_CLOSED:
  115. return
  116. try:
  117. if self._mode == _MODE_READ:
  118. self._buffer.close()
  119. self._buffer = None
  120. elif self._mode == _MODE_WRITE:
  121. self._fp.write(self._compressor.flush())
  122. self._compressor = None
  123. finally:
  124. try:
  125. if self._closefp:
  126. self._fp.close()
  127. finally:
  128. self._fp = None
  129. self._closefp = False
  130. self._mode = _MODE_CLOSED
  131. @property
  132. def closed(self):
  133. """True if this file is closed."""
  134. return self._mode == _MODE_CLOSED
  135. def fileno(self):
  136. """Return the file descriptor for the underlying file."""
  137. self._check_not_closed()
  138. return self._fp.fileno()
  139. def seekable(self):
  140. """Return whether the file supports seeking."""
  141. return self.readable() and self._buffer.seekable()
  142. def readable(self):
  143. """Return whether the file was opened for reading."""
  144. self._check_not_closed()
  145. return self._mode == _MODE_READ
  146. def writable(self):
  147. """Return whether the file was opened for writing."""
  148. self._check_not_closed()
  149. return self._mode == _MODE_WRITE
  150. def peek(self, size=-1):
  151. """Return buffered data without advancing the file position.
  152. Always returns at least one byte of data, unless at EOF.
  153. The exact number of bytes returned is unspecified.
  154. """
  155. self._check_can_read()
  156. # Relies on the undocumented fact that BufferedReader.peek() always
  157. # returns at least one byte (except at EOF)
  158. return self._buffer.peek(size)
  159. def read(self, size=-1):
  160. """Read up to size uncompressed bytes from the file.
  161. If size is negative or omitted, read until EOF is reached.
  162. Returns b"" if the file is already at EOF.
  163. """
  164. self._check_can_read()
  165. return self._buffer.read(size)
  166. def read1(self, size=-1):
  167. """Read up to size uncompressed bytes, while trying to avoid
  168. making multiple reads from the underlying stream. Reads up to a
  169. buffer's worth of data if size is negative.
  170. Returns b"" if the file is at EOF.
  171. """
  172. self._check_can_read()
  173. if size < 0:
  174. size = io.DEFAULT_BUFFER_SIZE
  175. return self._buffer.read1(size)
  176. def readline(self, size=-1):
  177. """Read a line of uncompressed bytes from the file.
  178. The terminating newline (if present) is retained. If size is
  179. non-negative, no more than size bytes will be read (in which
  180. case the line may be incomplete). Returns b'' if already at EOF.
  181. """
  182. self._check_can_read()
  183. return self._buffer.readline(size)
  184. def write(self, data):
  185. """Write a bytes object to the file.
  186. Returns the number of uncompressed bytes written, which is
  187. always the length of data in bytes. Note that due to buffering,
  188. the file on disk may not reflect the data written until close()
  189. is called.
  190. """
  191. self._check_can_write()
  192. if isinstance(data, (bytes, bytearray)):
  193. length = len(data)
  194. else:
  195. # accept any data that supports the buffer protocol
  196. data = memoryview(data)
  197. length = data.nbytes
  198. compressed = self._compressor.compress(data)
  199. self._fp.write(compressed)
  200. self._pos += length
  201. return length
  202. def seek(self, offset, whence=io.SEEK_SET):
  203. """Change the file position.
  204. The new position is specified by offset, relative to the
  205. position indicated by whence. Possible values for whence are:
  206. 0: start of stream (default): offset must not be negative
  207. 1: current stream position
  208. 2: end of stream; offset must not be positive
  209. Returns the new file position.
  210. Note that seeking is emulated, so depending on the parameters,
  211. this operation may be extremely slow.
  212. """
  213. self._check_can_seek()
  214. return self._buffer.seek(offset, whence)
  215. def tell(self):
  216. """Return the current file position."""
  217. self._check_not_closed()
  218. if self._mode == _MODE_READ:
  219. return self._buffer.tell()
  220. return self._pos
  221. def open(filename, mode="rb", *,
  222. format=None, check=-1, preset=None, filters=None,
  223. encoding=None, errors=None, newline=None):
  224. """Open an LZMA-compressed file in binary or text mode.
  225. filename can be either an actual file name (given as a str, bytes,
  226. or PathLike object), in which case the named file is opened, or it
  227. can be an existing file object to read from or write to.
  228. The mode argument can be "r", "rb" (default), "w", "wb", "x", "xb",
  229. "a", or "ab" for binary mode, or "rt", "wt", "xt", or "at" for text
  230. mode.
  231. The format, check, preset and filters arguments specify the
  232. compression settings, as for LZMACompressor, LZMADecompressor and
  233. LZMAFile.
  234. For binary mode, this function is equivalent to the LZMAFile
  235. constructor: LZMAFile(filename, mode, ...). In this case, the
  236. encoding, errors and newline arguments must not be provided.
  237. For text mode, an LZMAFile object is created, and wrapped in an
  238. io.TextIOWrapper instance with the specified encoding, error
  239. handling behavior, and line ending(s).
  240. """
  241. if "t" in mode:
  242. if "b" in mode:
  243. raise ValueError("Invalid mode: %r" % (mode,))
  244. else:
  245. if encoding is not None:
  246. raise ValueError("Argument 'encoding' not supported in binary mode")
  247. if errors is not None:
  248. raise ValueError("Argument 'errors' not supported in binary mode")
  249. if newline is not None:
  250. raise ValueError("Argument 'newline' not supported in binary mode")
  251. lz_mode = mode.replace("t", "")
  252. binary_file = LZMAFile(filename, lz_mode, format=format, check=check,
  253. preset=preset, filters=filters)
  254. if "t" in mode:
  255. return io.TextIOWrapper(binary_file, encoding, errors, newline)
  256. else:
  257. return binary_file
  258. def compress(data, format=FORMAT_XZ, check=-1, preset=None, filters=None):
  259. """Compress a block of data.
  260. Refer to LZMACompressor's docstring for a description of the
  261. optional arguments *format*, *check*, *preset* and *filters*.
  262. For incremental compression, use an LZMACompressor instead.
  263. """
  264. comp = LZMACompressor(format, check, preset, filters)
  265. return comp.compress(data) + comp.flush()
  266. def decompress(data, format=FORMAT_AUTO, memlimit=None, filters=None):
  267. """Decompress a block of data.
  268. Refer to LZMADecompressor's docstring for a description of the
  269. optional arguments *format*, *check* and *filters*.
  270. For incremental decompression, use an LZMADecompressor instead.
  271. """
  272. results = []
  273. while True:
  274. decomp = LZMADecompressor(format, memlimit, filters)
  275. try:
  276. res = decomp.decompress(data)
  277. except LZMAError:
  278. if results:
  279. break # Leftover data is not a valid LZMA/XZ stream; ignore it.
  280. else:
  281. raise # Error on the first iteration; bail out.
  282. results.append(res)
  283. if not decomp.eof:
  284. raise LZMAError("Compressed data ended before the "
  285. "end-of-stream marker was reached")
  286. data = decomp.unused_data
  287. if not data:
  288. break
  289. return b"".join(results)