blob: 8e34ed2b8d9adaaa7db68324668dbd82c64b9629 [file] [log] [blame]
Guido van Rossum4b8c6ea2000-02-04 15:39:30 +00001"""Functions that read and write gzipped files.
2
Guido van Rossum54f22ed2000-02-04 15:10:34 +00003The user of the file doesn't have to worry about the compression,
4but random access is not allowed."""
5
6# based on Andrew Kuchling's minigzip.py distributed with the zlib module
7
Eric S. Raymondee5e61d2001-02-09 09:10:35 +00008import struct, sys, time
Guido van Rossum15262191997-04-30 16:04:57 +00009import zlib
Guido van Rossum68de3791997-07-19 20:22:23 +000010import __builtin__
Guido van Rossum15262191997-04-30 16:04:57 +000011
Skip Montanaro2dd42762001-01-23 15:35:05 +000012__all__ = ["GzipFile","open"]
13
Guido van Rossum15262191997-04-30 16:04:57 +000014FTEXT, FHCRC, FEXTRA, FNAME, FCOMMENT = 1, 2, 4, 8, 16
15
16READ, WRITE = 1, 2
17
18def write32(output, value):
Jeremy Hyltonc19f9971999-03-23 23:05:34 +000019 output.write(struct.pack("<l", value))
Tim Peters07e99cb2001-01-14 23:47:14 +000020
Guido van Rossum95bdd0b1999-04-12 14:34:16 +000021def write32u(output, value):
22 output.write(struct.pack("<L", value))
23
Guido van Rossum15262191997-04-30 16:04:57 +000024def read32(input):
Jeremy Hyltonc19f9971999-03-23 23:05:34 +000025 return struct.unpack("<l", input.read(4))[0]
Guido van Rossum15262191997-04-30 16:04:57 +000026
Fred Drakefa1591c1999-04-05 18:37:59 +000027def open(filename, mode="rb", compresslevel=9):
Guido van Rossum15262191997-04-30 16:04:57 +000028 return GzipFile(filename, mode, compresslevel)
29
30class GzipFile:
31
Guido van Rossum68de3791997-07-19 20:22:23 +000032 myfileobj = None
33
Tim Peters07e99cb2001-01-14 23:47:14 +000034 def __init__(self, filename=None, mode=None,
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000035 compresslevel=9, fileobj=None):
36 if fileobj is None:
Fred Drake9bb76d11999-04-05 18:33:40 +000037 fileobj = self.myfileobj = __builtin__.open(filename, mode or 'rb')
Guido van Rossum68de3791997-07-19 20:22:23 +000038 if filename is None:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000039 if hasattr(fileobj, 'name'): filename = fileobj.name
40 else: filename = ''
Guido van Rossum68de3791997-07-19 20:22:23 +000041 if mode is None:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000042 if hasattr(fileobj, 'mode'): mode = fileobj.mode
Fred Drake9bb76d11999-04-05 18:33:40 +000043 else: mode = 'rb'
Guido van Rossum68de3791997-07-19 20:22:23 +000044
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000045 if mode[0:1] == 'r':
46 self.mode = READ
Tim Peters07e99cb2001-01-14 23:47:14 +000047 # Set flag indicating start of a new member
48 self._new_member = 1
Andrew M. Kuchlingf4f119c1999-03-25 21:49:14 +000049 self.extrabuf = ""
50 self.extrasize = 0
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000051 self.filename = filename
Guido van Rossum15262191997-04-30 16:04:57 +000052
Andrew M. Kuchlingf4f119c1999-03-25 21:49:14 +000053 elif mode[0:1] == 'w' or mode[0:1] == 'a':
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000054 self.mode = WRITE
55 self._init_write(filename)
56 self.compress = zlib.compressobj(compresslevel,
Tim Peters07e99cb2001-01-14 23:47:14 +000057 zlib.DEFLATED,
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000058 -zlib.MAX_WBITS,
59 zlib.DEF_MEM_LEVEL,
60 0)
61 else:
62 raise ValueError, "Mode " + mode + " not supported"
Guido van Rossum15262191997-04-30 16:04:57 +000063
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000064 self.fileobj = fileobj
Guido van Rossum15262191997-04-30 16:04:57 +000065
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000066 if self.mode == WRITE:
67 self._write_gzip_header()
Guido van Rossum15262191997-04-30 16:04:57 +000068
69 def __repr__(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000070 s = repr(self.fileobj)
71 return '<gzip ' + s[1:-1] + ' ' + hex(id(self)) + '>'
Guido van Rossum15262191997-04-30 16:04:57 +000072
73 def _init_write(self, filename):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000074 if filename[-3:] != '.gz':
75 filename = filename + '.gz'
76 self.filename = filename
77 self.crc = zlib.crc32("")
78 self.size = 0
79 self.writebuf = []
80 self.bufsize = 0
Guido van Rossum15262191997-04-30 16:04:57 +000081
82 def _write_gzip_header(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000083 self.fileobj.write('\037\213') # magic header
84 self.fileobj.write('\010') # compression method
85 fname = self.filename[:-3]
86 flags = 0
87 if fname:
88 flags = FNAME
89 self.fileobj.write(chr(flags))
Guido van Rossum95bdd0b1999-04-12 14:34:16 +000090 write32u(self.fileobj, long(time.time()))
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000091 self.fileobj.write('\002')
92 self.fileobj.write('\377')
93 if fname:
94 self.fileobj.write(fname + '\000')
Guido van Rossum15262191997-04-30 16:04:57 +000095
96 def _init_read(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000097 self.crc = zlib.crc32("")
98 self.size = 0
Guido van Rossum15262191997-04-30 16:04:57 +000099
100 def _read_gzip_header(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000101 magic = self.fileobj.read(2)
102 if magic != '\037\213':
Andrew M. Kuchlingf4f119c1999-03-25 21:49:14 +0000103 raise IOError, 'Not a gzipped file'
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000104 method = ord( self.fileobj.read(1) )
105 if method != 8:
Andrew M. Kuchlingf4f119c1999-03-25 21:49:14 +0000106 raise IOError, 'Unknown compression method'
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000107 flag = ord( self.fileobj.read(1) )
108 # modtime = self.fileobj.read(4)
109 # extraflag = self.fileobj.read(1)
110 # os = self.fileobj.read(1)
111 self.fileobj.read(6)
Guido van Rossum15262191997-04-30 16:04:57 +0000112
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000113 if flag & FEXTRA:
114 # Read & discard the extra field, if present
Tim Peters07e99cb2001-01-14 23:47:14 +0000115 xlen=ord(self.fileobj.read(1))
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000116 xlen=xlen+256*ord(self.fileobj.read(1))
117 self.fileobj.read(xlen)
118 if flag & FNAME:
119 # Read and discard a null-terminated string containing the filename
120 while (1):
121 s=self.fileobj.read(1)
122 if not s or s=='\000': break
123 if flag & FCOMMENT:
124 # Read and discard a null-terminated string containing a comment
125 while (1):
126 s=self.fileobj.read(1)
127 if not s or s=='\000': break
128 if flag & FHCRC:
129 self.fileobj.read(2) # Read & discard the 16-bit header CRC
Guido van Rossum15262191997-04-30 16:04:57 +0000130
131
132 def write(self,data):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000133 if self.fileobj is None:
134 raise ValueError, "write() on closed GzipFile object"
135 if len(data) > 0:
136 self.size = self.size + len(data)
137 self.crc = zlib.crc32(data, self.crc)
138 self.fileobj.write( self.compress.compress(data) )
Guido van Rossum15262191997-04-30 16:04:57 +0000139
140 def writelines(self,lines):
Eric S. Raymondee5e61d2001-02-09 09:10:35 +0000141 self.write(" ".join(lines))
Guido van Rossum15262191997-04-30 16:04:57 +0000142
Guido van Rossum56068012000-02-02 16:51:06 +0000143 def read(self, size=-1):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000144 if self.extrasize <= 0 and self.fileobj is None:
145 return ''
Guido van Rossumb16a3b81998-01-27 19:29:45 +0000146
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000147 readsize = 1024
Guido van Rossum56068012000-02-02 16:51:06 +0000148 if size < 0: # get the whole thing
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000149 try:
150 while 1:
151 self._read(readsize)
152 readsize = readsize * 2
153 except EOFError:
154 size = self.extrasize
155 else: # just get some more of it
156 try:
157 while size > self.extrasize:
158 self._read(readsize)
159 readsize = readsize * 2
160 except EOFError:
Guido van Rossum84c6fc91998-08-03 15:41:39 +0000161 if size > self.extrasize:
162 size = self.extrasize
Tim Peters07e99cb2001-01-14 23:47:14 +0000163
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000164 chunk = self.extrabuf[:size]
165 self.extrabuf = self.extrabuf[size:]
166 self.extrasize = self.extrasize - size
Guido van Rossum15262191997-04-30 16:04:57 +0000167
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000168 return chunk
Guido van Rossum15262191997-04-30 16:04:57 +0000169
Guido van Rossumb16a3b81998-01-27 19:29:45 +0000170 def _unread(self, buf):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000171 self.extrabuf = buf + self.extrabuf
Guido van Rossum84c6fc91998-08-03 15:41:39 +0000172 self.extrasize = len(buf) + self.extrasize
Guido van Rossumb16a3b81998-01-27 19:29:45 +0000173
174 def _read(self, size=1024):
Andrew M. Kuchlingf4f119c1999-03-25 21:49:14 +0000175 if self.fileobj is None: raise EOFError, "Reached EOF"
Tim Peters07e99cb2001-01-14 23:47:14 +0000176
Andrew M. Kuchlingf4f119c1999-03-25 21:49:14 +0000177 if self._new_member:
Andrew M. Kuchling41616ee2000-07-29 20:15:26 +0000178 # If the _new_member flag is set, we have to
179 # jump to the next member, if there is one.
Tim Peters07e99cb2001-01-14 23:47:14 +0000180 #
Andrew M. Kuchlingf4f119c1999-03-25 21:49:14 +0000181 # First, check if we're at the end of the file;
182 # if so, it's time to stop; no more members to read.
183 pos = self.fileobj.tell() # Save current position
184 self.fileobj.seek(0, 2) # Seek to end of file
185 if pos == self.fileobj.tell():
186 self.fileobj = None
Andrew M. Kuchling2d813e51999-09-06 16:34:51 +0000187 raise EOFError, "Reached EOF"
Tim Peters07e99cb2001-01-14 23:47:14 +0000188 else:
Andrew M. Kuchlingf4f119c1999-03-25 21:49:14 +0000189 self.fileobj.seek( pos ) # Return to original position
Tim Peters07e99cb2001-01-14 23:47:14 +0000190
191 self._init_read()
Andrew M. Kuchlingf4f119c1999-03-25 21:49:14 +0000192 self._read_gzip_header()
193 self.decompress = zlib.decompressobj(-zlib.MAX_WBITS)
194 self._new_member = 0
Tim Peters07e99cb2001-01-14 23:47:14 +0000195
Andrew M. Kuchlingf4f119c1999-03-25 21:49:14 +0000196 # Read a chunk of data from the file
197 buf = self.fileobj.read(size)
Tim Peters07e99cb2001-01-14 23:47:14 +0000198
Andrew M. Kuchlingf4f119c1999-03-25 21:49:14 +0000199 # If the EOF has been reached, flush the decompression object
200 # and mark this object as finished.
Tim Peters07e99cb2001-01-14 23:47:14 +0000201
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000202 if buf == "":
203 uncompress = self.decompress.flush()
Andrew M. Kuchlingf4f119c1999-03-25 21:49:14 +0000204 self._read_eof()
205 self.fileobj = None
206 self._add_read_data( uncompress )
207 raise EOFError, 'Reached EOF'
Tim Peters07e99cb2001-01-14 23:47:14 +0000208
Andrew M. Kuchlingf4f119c1999-03-25 21:49:14 +0000209 uncompress = self.decompress.decompress(buf)
210 self._add_read_data( uncompress )
211
212 if self.decompress.unused_data != "":
213 # Ending case: we've come to the end of a member in the file,
214 # so seek back to the start of the unused data, finish up
215 # this member, and read a new gzip header.
216 # (The number of bytes to seek back is the length of the unused
217 # data, minus 8 because _read_eof() will rewind a further 8 bytes)
218 self.fileobj.seek( -len(self.decompress.unused_data)+8, 1)
219
220 # Check the CRC and file size, and set the flag so we read
Tim Peters07e99cb2001-01-14 23:47:14 +0000221 # a new member on the next call
Andrew M. Kuchlingf4f119c1999-03-25 21:49:14 +0000222 self._read_eof()
Tim Peters07e99cb2001-01-14 23:47:14 +0000223 self._new_member = 1
224
225 def _add_read_data(self, data):
Andrew M. Kuchlingf4f119c1999-03-25 21:49:14 +0000226 self.crc = zlib.crc32(data, self.crc)
227 self.extrabuf = self.extrabuf + data
228 self.extrasize = self.extrasize + len(data)
229 self.size = self.size + len(data)
Guido van Rossum15262191997-04-30 16:04:57 +0000230
231 def _read_eof(self):
Andrew M. Kuchlingf4f119c1999-03-25 21:49:14 +0000232 # We've read to the end of the file, so we have to rewind in order
Tim Peters07e99cb2001-01-14 23:47:14 +0000233 # to reread the 8 bytes containing the CRC and the file size.
Andrew M. Kuchlingf4f119c1999-03-25 21:49:14 +0000234 # We check the that the computed CRC and size of the
235 # uncompressed data matches the stored values.
236 self.fileobj.seek(-8, 1)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000237 crc32 = read32(self.fileobj)
238 isize = read32(self.fileobj)
Guido van Rossum95bdd0b1999-04-12 14:34:16 +0000239 if crc32%0x100000000L != self.crc%0x100000000L:
Andrew M. Kuchlingf4f119c1999-03-25 21:49:14 +0000240 raise ValueError, "CRC check failed"
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000241 elif isize != self.size:
Andrew M. Kuchlingf4f119c1999-03-25 21:49:14 +0000242 raise ValueError, "Incorrect length of data produced"
Tim Peters07e99cb2001-01-14 23:47:14 +0000243
Guido van Rossum15262191997-04-30 16:04:57 +0000244 def close(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000245 if self.mode == WRITE:
246 self.fileobj.write(self.compress.flush())
247 write32(self.fileobj, self.crc)
248 write32(self.fileobj, self.size)
249 self.fileobj = None
250 elif self.mode == READ:
251 self.fileobj = None
252 if self.myfileobj:
253 self.myfileobj.close()
254 self.myfileobj = None
Guido van Rossum15262191997-04-30 16:04:57 +0000255
Andrew M. Kuchling916fcc31999-08-10 13:19:30 +0000256 def __del__(self):
Jeremy Hyltone298c302000-05-08 16:59:59 +0000257 try:
258 if (self.myfileobj is None and
259 self.fileobj is None):
260 return
261 except AttributeError:
262 return
263 self.close()
Tim Peters07e99cb2001-01-14 23:47:14 +0000264
Guido van Rossum15262191997-04-30 16:04:57 +0000265 def flush(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000266 self.fileobj.flush()
Guido van Rossum15262191997-04-30 16:04:57 +0000267
268 def seek(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000269 raise IOError, 'Random access not allowed in gzip files'
Guido van Rossum15262191997-04-30 16:04:57 +0000270
271 def tell(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000272 raise IOError, 'I won\'t tell() you for gzip files'
Guido van Rossum15262191997-04-30 16:04:57 +0000273
274 def isatty(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000275 return 0
Guido van Rossum15262191997-04-30 16:04:57 +0000276
Andrew M. Kuchling41616ee2000-07-29 20:15:26 +0000277 def readline(self, size=-1):
278 if size < 0: size = sys.maxint
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000279 bufs = []
Andrew M. Kuchling41616ee2000-07-29 20:15:26 +0000280 orig_size = size
281 readsize = min(100, size) # Read from the file in small chunks
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000282 while 1:
Andrew M. Kuchling41616ee2000-07-29 20:15:26 +0000283 if size == 0:
Eric S. Raymondee5e61d2001-02-09 09:10:35 +0000284 return "".join(bufs) # Return resulting line
Andrew M. Kuchling41616ee2000-07-29 20:15:26 +0000285
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000286 c = self.read(readsize)
Eric S. Raymondee5e61d2001-02-09 09:10:35 +0000287 i = c.find('\n')
Andrew M. Kuchling41616ee2000-07-29 20:15:26 +0000288 if size is not None:
289 # We set i=size to break out of the loop under two
Tim Peters07e99cb2001-01-14 23:47:14 +0000290 # conditions: 1) there's no newline, and the chunk is
Andrew M. Kuchling41616ee2000-07-29 20:15:26 +0000291 # larger than size, or 2) there is a newline, but the
292 # resulting line would be longer than 'size'.
293 if i==-1 and len(c) > size: i=size-1
294 elif size <= i: i = size -1
Guido van Rossum15262191997-04-30 16:04:57 +0000295
Andrew M. Kuchling41616ee2000-07-29 20:15:26 +0000296 if i >= 0 or c == '':
297 bufs.append(c[:i+1]) # Add portion of last chunk
298 self._unread(c[i+1:]) # Push back rest of chunk
Eric S. Raymondee5e61d2001-02-09 09:10:35 +0000299 return ''.join(bufs) # Return resulting line
Andrew M. Kuchling41616ee2000-07-29 20:15:26 +0000300
301 # Append chunk to list, decrease 'size',
302 bufs.append(c)
303 size = size - len(c)
304 readsize = min(size, readsize * 2)
Tim Peters07e99cb2001-01-14 23:47:14 +0000305
Andrew M. Kuchling41616ee2000-07-29 20:15:26 +0000306 def readlines(self, sizehint=0):
307 # Negative numbers result in reading all the lines
308 if sizehint <= 0: sizehint = sys.maxint
309 L = []
310 while sizehint > 0:
311 line = self.readline()
312 if line == "": break
313 L.append( line )
314 sizehint = sizehint - len(line)
315
316 return L
Guido van Rossum15262191997-04-30 16:04:57 +0000317
Guido van Rossum68de3791997-07-19 20:22:23 +0000318 def writelines(self, L):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000319 for line in L:
320 self.write(line)
Guido van Rossum51ca6e31997-12-30 20:09:08 +0000321
322
323def _test():
324 # Act like gzip; with -d, act like gunzip.
325 # The input file is not deleted, however, nor are any other gzip
326 # options or features supported.
327 import sys
328 args = sys.argv[1:]
329 decompress = args and args[0] == "-d"
330 if decompress:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000331 args = args[1:]
Guido van Rossum51ca6e31997-12-30 20:09:08 +0000332 if not args:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000333 args = ["-"]
Guido van Rossum51ca6e31997-12-30 20:09:08 +0000334 for arg in args:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000335 if decompress:
336 if arg == "-":
337 f = GzipFile(filename="", mode="rb", fileobj=sys.stdin)
338 g = sys.stdout
339 else:
340 if arg[-3:] != ".gz":
341 print "filename doesn't end in .gz:", `arg`
342 continue
343 f = open(arg, "rb")
344 g = __builtin__.open(arg[:-3], "wb")
345 else:
346 if arg == "-":
347 f = sys.stdin
348 g = GzipFile(filename="", mode="wb", fileobj=sys.stdout)
349 else:
350 f = __builtin__.open(arg, "rb")
351 g = open(arg + ".gz", "wb")
352 while 1:
353 chunk = f.read(1024)
354 if not chunk:
355 break
356 g.write(chunk)
357 if g is not sys.stdout:
358 g.close()
359 if f is not sys.stdin:
360 f.close()
Guido van Rossum51ca6e31997-12-30 20:09:08 +0000361
362if __name__ == '__main__':
363 _test()