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