logo

oasis-root

Compiled tree of Oasis Linux based on own branch at <https://hacktivis.me/git/oasis/> git clone https://anongit.hacktivis.me/git/oasis-root.git

gzip.py (21946B)


  1. """Functions that read and write gzipped files.
  2. The user of the file doesn't have to worry about the compression,
  3. but random access is not allowed."""
  4. # based on Andrew Kuchling's minigzip.py distributed with the zlib module
  5. import struct, sys, time, os
  6. import zlib
  7. import builtins
  8. import io
  9. import _compression
  10. __all__ = ["BadGzipFile", "GzipFile", "open", "compress", "decompress"]
  11. FTEXT, FHCRC, FEXTRA, FNAME, FCOMMENT = 1, 2, 4, 8, 16
  12. READ, WRITE = 1, 2
  13. _COMPRESS_LEVEL_FAST = 1
  14. _COMPRESS_LEVEL_TRADEOFF = 6
  15. _COMPRESS_LEVEL_BEST = 9
  16. def open(filename, mode="rb", compresslevel=_COMPRESS_LEVEL_BEST,
  17. encoding=None, errors=None, newline=None):
  18. """Open a gzip-compressed file in binary or text mode.
  19. The filename argument can be an actual filename (a str or bytes object), or
  20. an existing file object to read from or write to.
  21. The mode argument can be "r", "rb", "w", "wb", "x", "xb", "a" or "ab" for
  22. binary mode, or "rt", "wt", "xt" or "at" for text mode. The default mode is
  23. "rb", and the default compresslevel is 9.
  24. For binary mode, this function is equivalent to the GzipFile constructor:
  25. GzipFile(filename, mode, compresslevel). In this case, the encoding, errors
  26. and newline arguments must not be provided.
  27. For text mode, a GzipFile object is created, and wrapped in an
  28. io.TextIOWrapper instance with the specified encoding, error handling
  29. behavior, and line ending(s).
  30. """
  31. if "t" in mode:
  32. if "b" in mode:
  33. raise ValueError("Invalid mode: %r" % (mode,))
  34. else:
  35. if encoding is not None:
  36. raise ValueError("Argument 'encoding' not supported in binary mode")
  37. if errors is not None:
  38. raise ValueError("Argument 'errors' not supported in binary mode")
  39. if newline is not None:
  40. raise ValueError("Argument 'newline' not supported in binary mode")
  41. gz_mode = mode.replace("t", "")
  42. if isinstance(filename, (str, bytes, os.PathLike)):
  43. binary_file = GzipFile(filename, gz_mode, compresslevel)
  44. elif hasattr(filename, "read") or hasattr(filename, "write"):
  45. binary_file = GzipFile(None, gz_mode, compresslevel, filename)
  46. else:
  47. raise TypeError("filename must be a str or bytes object, or a file")
  48. if "t" in mode:
  49. encoding = io.text_encoding(encoding)
  50. return io.TextIOWrapper(binary_file, encoding, errors, newline)
  51. else:
  52. return binary_file
  53. def write32u(output, value):
  54. # The L format writes the bit pattern correctly whether signed
  55. # or unsigned.
  56. output.write(struct.pack("<L", value))
  57. class _PaddedFile:
  58. """Minimal read-only file object that prepends a string to the contents
  59. of an actual file. Shouldn't be used outside of gzip.py, as it lacks
  60. essential functionality."""
  61. def __init__(self, f, prepend=b''):
  62. self._buffer = prepend
  63. self._length = len(prepend)
  64. self.file = f
  65. self._read = 0
  66. def read(self, size):
  67. if self._read is None:
  68. return self.file.read(size)
  69. if self._read + size <= self._length:
  70. read = self._read
  71. self._read += size
  72. return self._buffer[read:self._read]
  73. else:
  74. read = self._read
  75. self._read = None
  76. return self._buffer[read:] + \
  77. self.file.read(size-self._length+read)
  78. def prepend(self, prepend=b''):
  79. if self._read is None:
  80. self._buffer = prepend
  81. else: # Assume data was read since the last prepend() call
  82. self._read -= len(prepend)
  83. return
  84. self._length = len(self._buffer)
  85. self._read = 0
  86. def seek(self, off):
  87. self._read = None
  88. self._buffer = None
  89. return self.file.seek(off)
  90. def seekable(self):
  91. return True # Allows fast-forwarding even in unseekable streams
  92. class BadGzipFile(OSError):
  93. """Exception raised in some cases for invalid gzip files."""
  94. class GzipFile(_compression.BaseStream):
  95. """The GzipFile class simulates most of the methods of a file object with
  96. the exception of the truncate() method.
  97. This class only supports opening files in binary mode. If you need to open a
  98. compressed file in text mode, use the gzip.open() function.
  99. """
  100. # Overridden with internal file object to be closed, if only a filename
  101. # is passed in
  102. myfileobj = None
  103. def __init__(self, filename=None, mode=None,
  104. compresslevel=_COMPRESS_LEVEL_BEST, fileobj=None, mtime=None):
  105. """Constructor for the GzipFile class.
  106. At least one of fileobj and filename must be given a
  107. non-trivial value.
  108. The new class instance is based on fileobj, which can be a regular
  109. file, an io.BytesIO object, or any other object which simulates a file.
  110. It defaults to None, in which case filename is opened to provide
  111. a file object.
  112. When fileobj is not None, the filename argument is only used to be
  113. included in the gzip file header, which may include the original
  114. filename of the uncompressed file. It defaults to the filename of
  115. fileobj, if discernible; otherwise, it defaults to the empty string,
  116. and in this case the original filename is not included in the header.
  117. The mode argument can be any of 'r', 'rb', 'a', 'ab', 'w', 'wb', 'x', or
  118. 'xb' depending on whether the file will be read or written. The default
  119. is the mode of fileobj if discernible; otherwise, the default is 'rb'.
  120. A mode of 'r' is equivalent to one of 'rb', and similarly for 'w' and
  121. 'wb', 'a' and 'ab', and 'x' and 'xb'.
  122. The compresslevel argument is an integer from 0 to 9 controlling the
  123. level of compression; 1 is fastest and produces the least compression,
  124. and 9 is slowest and produces the most compression. 0 is no compression
  125. at all. The default is 9.
  126. The mtime argument is an optional numeric timestamp to be written
  127. to the last modification time field in the stream when compressing.
  128. If omitted or None, the current time is used.
  129. """
  130. if mode and ('t' in mode or 'U' in mode):
  131. raise ValueError("Invalid mode: {!r}".format(mode))
  132. if mode and 'b' not in mode:
  133. mode += 'b'
  134. if fileobj is None:
  135. fileobj = self.myfileobj = builtins.open(filename, mode or 'rb')
  136. if filename is None:
  137. filename = getattr(fileobj, 'name', '')
  138. if not isinstance(filename, (str, bytes)):
  139. filename = ''
  140. else:
  141. filename = os.fspath(filename)
  142. origmode = mode
  143. if mode is None:
  144. mode = getattr(fileobj, 'mode', 'rb')
  145. if mode.startswith('r'):
  146. self.mode = READ
  147. raw = _GzipReader(fileobj)
  148. self._buffer = io.BufferedReader(raw)
  149. self.name = filename
  150. elif mode.startswith(('w', 'a', 'x')):
  151. if origmode is None:
  152. import warnings
  153. warnings.warn(
  154. "GzipFile was opened for writing, but this will "
  155. "change in future Python releases. "
  156. "Specify the mode argument for opening it for writing.",
  157. FutureWarning, 2)
  158. self.mode = WRITE
  159. self._init_write(filename)
  160. self.compress = zlib.compressobj(compresslevel,
  161. zlib.DEFLATED,
  162. -zlib.MAX_WBITS,
  163. zlib.DEF_MEM_LEVEL,
  164. 0)
  165. self._write_mtime = mtime
  166. else:
  167. raise ValueError("Invalid mode: {!r}".format(mode))
  168. self.fileobj = fileobj
  169. if self.mode == WRITE:
  170. self._write_gzip_header(compresslevel)
  171. @property
  172. def filename(self):
  173. import warnings
  174. warnings.warn("use the name attribute", DeprecationWarning, 2)
  175. if self.mode == WRITE and self.name[-3:] != ".gz":
  176. return self.name + ".gz"
  177. return self.name
  178. @property
  179. def mtime(self):
  180. """Last modification time read from stream, or None"""
  181. return self._buffer.raw._last_mtime
  182. def __repr__(self):
  183. s = repr(self.fileobj)
  184. return '<gzip ' + s[1:-1] + ' ' + hex(id(self)) + '>'
  185. def _init_write(self, filename):
  186. self.name = filename
  187. self.crc = zlib.crc32(b"")
  188. self.size = 0
  189. self.writebuf = []
  190. self.bufsize = 0
  191. self.offset = 0 # Current file offset for seek(), tell(), etc
  192. def _write_gzip_header(self, compresslevel):
  193. self.fileobj.write(b'\037\213') # magic header
  194. self.fileobj.write(b'\010') # compression method
  195. try:
  196. # RFC 1952 requires the FNAME field to be Latin-1. Do not
  197. # include filenames that cannot be represented that way.
  198. fname = os.path.basename(self.name)
  199. if not isinstance(fname, bytes):
  200. fname = fname.encode('latin-1')
  201. if fname.endswith(b'.gz'):
  202. fname = fname[:-3]
  203. except UnicodeEncodeError:
  204. fname = b''
  205. flags = 0
  206. if fname:
  207. flags = FNAME
  208. self.fileobj.write(chr(flags).encode('latin-1'))
  209. mtime = self._write_mtime
  210. if mtime is None:
  211. mtime = time.time()
  212. write32u(self.fileobj, int(mtime))
  213. if compresslevel == _COMPRESS_LEVEL_BEST:
  214. xfl = b'\002'
  215. elif compresslevel == _COMPRESS_LEVEL_FAST:
  216. xfl = b'\004'
  217. else:
  218. xfl = b'\000'
  219. self.fileobj.write(xfl)
  220. self.fileobj.write(b'\377')
  221. if fname:
  222. self.fileobj.write(fname + b'\000')
  223. def write(self,data):
  224. self._check_not_closed()
  225. if self.mode != WRITE:
  226. import errno
  227. raise OSError(errno.EBADF, "write() on read-only GzipFile object")
  228. if self.fileobj is None:
  229. raise ValueError("write() on closed GzipFile object")
  230. if isinstance(data, (bytes, bytearray)):
  231. length = len(data)
  232. else:
  233. # accept any data that supports the buffer protocol
  234. data = memoryview(data)
  235. length = data.nbytes
  236. if length > 0:
  237. self.fileobj.write(self.compress.compress(data))
  238. self.size += length
  239. self.crc = zlib.crc32(data, self.crc)
  240. self.offset += length
  241. return length
  242. def read(self, size=-1):
  243. self._check_not_closed()
  244. if self.mode != READ:
  245. import errno
  246. raise OSError(errno.EBADF, "read() on write-only GzipFile object")
  247. return self._buffer.read(size)
  248. def read1(self, size=-1):
  249. """Implements BufferedIOBase.read1()
  250. Reads up to a buffer's worth of data if size is negative."""
  251. self._check_not_closed()
  252. if self.mode != READ:
  253. import errno
  254. raise OSError(errno.EBADF, "read1() on write-only GzipFile object")
  255. if size < 0:
  256. size = io.DEFAULT_BUFFER_SIZE
  257. return self._buffer.read1(size)
  258. def peek(self, n):
  259. self._check_not_closed()
  260. if self.mode != READ:
  261. import errno
  262. raise OSError(errno.EBADF, "peek() on write-only GzipFile object")
  263. return self._buffer.peek(n)
  264. @property
  265. def closed(self):
  266. return self.fileobj is None
  267. def close(self):
  268. fileobj = self.fileobj
  269. if fileobj is None:
  270. return
  271. self.fileobj = None
  272. try:
  273. if self.mode == WRITE:
  274. fileobj.write(self.compress.flush())
  275. write32u(fileobj, self.crc)
  276. # self.size may exceed 2 GiB, or even 4 GiB
  277. write32u(fileobj, self.size & 0xffffffff)
  278. elif self.mode == READ:
  279. self._buffer.close()
  280. finally:
  281. myfileobj = self.myfileobj
  282. if myfileobj:
  283. self.myfileobj = None
  284. myfileobj.close()
  285. def flush(self,zlib_mode=zlib.Z_SYNC_FLUSH):
  286. self._check_not_closed()
  287. if self.mode == WRITE:
  288. # Ensure the compressor's buffer is flushed
  289. self.fileobj.write(self.compress.flush(zlib_mode))
  290. self.fileobj.flush()
  291. def fileno(self):
  292. """Invoke the underlying file object's fileno() method.
  293. This will raise AttributeError if the underlying file object
  294. doesn't support fileno().
  295. """
  296. return self.fileobj.fileno()
  297. def rewind(self):
  298. '''Return the uncompressed stream file position indicator to the
  299. beginning of the file'''
  300. if self.mode != READ:
  301. raise OSError("Can't rewind in write mode")
  302. self._buffer.seek(0)
  303. def readable(self):
  304. return self.mode == READ
  305. def writable(self):
  306. return self.mode == WRITE
  307. def seekable(self):
  308. return True
  309. def seek(self, offset, whence=io.SEEK_SET):
  310. if self.mode == WRITE:
  311. if whence != io.SEEK_SET:
  312. if whence == io.SEEK_CUR:
  313. offset = self.offset + offset
  314. else:
  315. raise ValueError('Seek from end not supported')
  316. if offset < self.offset:
  317. raise OSError('Negative seek in write mode')
  318. count = offset - self.offset
  319. chunk = b'\0' * 1024
  320. for i in range(count // 1024):
  321. self.write(chunk)
  322. self.write(b'\0' * (count % 1024))
  323. elif self.mode == READ:
  324. self._check_not_closed()
  325. return self._buffer.seek(offset, whence)
  326. return self.offset
  327. def readline(self, size=-1):
  328. self._check_not_closed()
  329. return self._buffer.readline(size)
  330. def __iter__(self):
  331. self._check_not_closed()
  332. return self._buffer.__iter__()
  333. class _GzipReader(_compression.DecompressReader):
  334. def __init__(self, fp):
  335. super().__init__(_PaddedFile(fp), zlib.decompressobj,
  336. wbits=-zlib.MAX_WBITS)
  337. # Set flag indicating start of a new member
  338. self._new_member = True
  339. self._last_mtime = None
  340. def _init_read(self):
  341. self._crc = zlib.crc32(b"")
  342. self._stream_size = 0 # Decompressed size of unconcatenated stream
  343. def _read_exact(self, n):
  344. '''Read exactly *n* bytes from `self._fp`
  345. This method is required because self._fp may be unbuffered,
  346. i.e. return short reads.
  347. '''
  348. data = self._fp.read(n)
  349. while len(data) < n:
  350. b = self._fp.read(n - len(data))
  351. if not b:
  352. raise EOFError("Compressed file ended before the "
  353. "end-of-stream marker was reached")
  354. data += b
  355. return data
  356. def _read_gzip_header(self):
  357. magic = self._fp.read(2)
  358. if magic == b'':
  359. return False
  360. if magic != b'\037\213':
  361. raise BadGzipFile('Not a gzipped file (%r)' % magic)
  362. (method, flag,
  363. self._last_mtime) = struct.unpack("<BBIxx", self._read_exact(8))
  364. if method != 8:
  365. raise BadGzipFile('Unknown compression method')
  366. if flag & FEXTRA:
  367. # Read & discard the extra field, if present
  368. extra_len, = struct.unpack("<H", self._read_exact(2))
  369. self._read_exact(extra_len)
  370. if flag & FNAME:
  371. # Read and discard a null-terminated string containing the filename
  372. while True:
  373. s = self._fp.read(1)
  374. if not s or s==b'\000':
  375. break
  376. if flag & FCOMMENT:
  377. # Read and discard a null-terminated string containing a comment
  378. while True:
  379. s = self._fp.read(1)
  380. if not s or s==b'\000':
  381. break
  382. if flag & FHCRC:
  383. self._read_exact(2) # Read & discard the 16-bit header CRC
  384. return True
  385. def read(self, size=-1):
  386. if size < 0:
  387. return self.readall()
  388. # size=0 is special because decompress(max_length=0) is not supported
  389. if not size:
  390. return b""
  391. # For certain input data, a single
  392. # call to decompress() may not return
  393. # any data. In this case, retry until we get some data or reach EOF.
  394. while True:
  395. if self._decompressor.eof:
  396. # Ending case: we've come to the end of a member in the file,
  397. # so finish up this member, and read a new gzip header.
  398. # Check the CRC and file size, and set the flag so we read
  399. # a new member
  400. self._read_eof()
  401. self._new_member = True
  402. self._decompressor = self._decomp_factory(
  403. **self._decomp_args)
  404. if self._new_member:
  405. # If the _new_member flag is set, we have to
  406. # jump to the next member, if there is one.
  407. self._init_read()
  408. if not self._read_gzip_header():
  409. self._size = self._pos
  410. return b""
  411. self._new_member = False
  412. # Read a chunk of data from the file
  413. buf = self._fp.read(io.DEFAULT_BUFFER_SIZE)
  414. uncompress = self._decompressor.decompress(buf, size)
  415. if self._decompressor.unconsumed_tail != b"":
  416. self._fp.prepend(self._decompressor.unconsumed_tail)
  417. elif self._decompressor.unused_data != b"":
  418. # Prepend the already read bytes to the fileobj so they can
  419. # be seen by _read_eof() and _read_gzip_header()
  420. self._fp.prepend(self._decompressor.unused_data)
  421. if uncompress != b"":
  422. break
  423. if buf == b"":
  424. raise EOFError("Compressed file ended before the "
  425. "end-of-stream marker was reached")
  426. self._add_read_data( uncompress )
  427. self._pos += len(uncompress)
  428. return uncompress
  429. def _add_read_data(self, data):
  430. self._crc = zlib.crc32(data, self._crc)
  431. self._stream_size = self._stream_size + len(data)
  432. def _read_eof(self):
  433. # We've read to the end of the file
  434. # We check that the computed CRC and size of the
  435. # uncompressed data matches the stored values. Note that the size
  436. # stored is the true file size mod 2**32.
  437. crc32, isize = struct.unpack("<II", self._read_exact(8))
  438. if crc32 != self._crc:
  439. raise BadGzipFile("CRC check failed %s != %s" % (hex(crc32),
  440. hex(self._crc)))
  441. elif isize != (self._stream_size & 0xffffffff):
  442. raise BadGzipFile("Incorrect length of data produced")
  443. # Gzip files can be padded with zeroes and still have archives.
  444. # Consume all zero bytes and set the file position to the first
  445. # non-zero byte. See http://www.gzip.org/#faq8
  446. c = b"\x00"
  447. while c == b"\x00":
  448. c = self._fp.read(1)
  449. if c:
  450. self._fp.prepend(c)
  451. def _rewind(self):
  452. super()._rewind()
  453. self._new_member = True
  454. def compress(data, compresslevel=_COMPRESS_LEVEL_BEST, *, mtime=None):
  455. """Compress data in one shot and return the compressed string.
  456. Optional argument is the compression level, in range of 0-9.
  457. """
  458. buf = io.BytesIO()
  459. with GzipFile(fileobj=buf, mode='wb', compresslevel=compresslevel, mtime=mtime) as f:
  460. f.write(data)
  461. return buf.getvalue()
  462. def decompress(data):
  463. """Decompress a gzip compressed string in one shot.
  464. Return the decompressed string.
  465. """
  466. with GzipFile(fileobj=io.BytesIO(data)) as f:
  467. return f.read()
  468. def main():
  469. from argparse import ArgumentParser
  470. parser = ArgumentParser(description=
  471. "A simple command line interface for the gzip module: act like gzip, "
  472. "but do not delete the input file.")
  473. group = parser.add_mutually_exclusive_group()
  474. group.add_argument('--fast', action='store_true', help='compress faster')
  475. group.add_argument('--best', action='store_true', help='compress better')
  476. group.add_argument("-d", "--decompress", action="store_true",
  477. help="act like gunzip instead of gzip")
  478. parser.add_argument("args", nargs="*", default=["-"], metavar='file')
  479. args = parser.parse_args()
  480. compresslevel = _COMPRESS_LEVEL_TRADEOFF
  481. if args.fast:
  482. compresslevel = _COMPRESS_LEVEL_FAST
  483. elif args.best:
  484. compresslevel = _COMPRESS_LEVEL_BEST
  485. for arg in args.args:
  486. if args.decompress:
  487. if arg == "-":
  488. f = GzipFile(filename="", mode="rb", fileobj=sys.stdin.buffer)
  489. g = sys.stdout.buffer
  490. else:
  491. if arg[-3:] != ".gz":
  492. sys.exit(f"filename doesn't end in .gz: {arg!r}")
  493. f = open(arg, "rb")
  494. g = builtins.open(arg[:-3], "wb")
  495. else:
  496. if arg == "-":
  497. f = sys.stdin.buffer
  498. g = GzipFile(filename="", mode="wb", fileobj=sys.stdout.buffer,
  499. compresslevel=compresslevel)
  500. else:
  501. f = builtins.open(arg, "rb")
  502. g = open(arg + ".gz", "wb")
  503. while True:
  504. chunk = f.read(io.DEFAULT_BUFFER_SIZE)
  505. if not chunk:
  506. break
  507. g.write(chunk)
  508. if g is not sys.stdout.buffer:
  509. g.close()
  510. if f is not sys.stdin.buffer:
  511. f.close()
  512. if __name__ == '__main__':
  513. main()