gzip.py 24 KB

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