blob: c0aff91150c47e445f7d39e218e6eedea60c08cc [file] [log] [blame]
Guido van Rossum15262191997-04-30 16:04:57 +00001import time
2import string
3import zlib
Jeremy Hyltonc19f9971999-03-23 23:05:34 +00004import struct
Guido van Rossum68de3791997-07-19 20:22:23 +00005import __builtin__
Guido van Rossum15262191997-04-30 16:04:57 +00006
7# implements a python function that reads and writes a gzipped file
8# the user of the file doesn't have to worry about the compression,
Guido van Rossum51ca6e31997-12-30 20:09:08 +00009# but random access is not allowed
Guido van Rossum15262191997-04-30 16:04:57 +000010
11# based on Andrew Kuchling's minigzip.py distributed with the zlib module
12
13FTEXT, FHCRC, FEXTRA, FNAME, FCOMMENT = 1, 2, 4, 8, 16
14
15READ, WRITE = 1, 2
16
17def write32(output, value):
Jeremy Hyltonc19f9971999-03-23 23:05:34 +000018 output.write(struct.pack("<l", value))
Guido van Rossum15262191997-04-30 16:04:57 +000019
Guido van Rossum95bdd0b1999-04-12 14:34:16 +000020def write32u(output, value):
21 output.write(struct.pack("<L", value))
22
Guido van Rossum15262191997-04-30 16:04:57 +000023def read32(input):
Jeremy Hyltonc19f9971999-03-23 23:05:34 +000024 return struct.unpack("<l", input.read(4))[0]
Guido van Rossum15262191997-04-30 16:04:57 +000025
Fred Drakefa1591c1999-04-05 18:37:59 +000026def open(filename, mode="rb", compresslevel=9):
Guido van Rossum15262191997-04-30 16:04:57 +000027 return GzipFile(filename, mode, compresslevel)
28
29class GzipFile:
30
Guido van Rossum68de3791997-07-19 20:22:23 +000031 myfileobj = None
32
33 def __init__(self, filename=None, mode=None,
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000034 compresslevel=9, fileobj=None):
35 if fileobj is None:
Fred Drake9bb76d11999-04-05 18:33:40 +000036 fileobj = self.myfileobj = __builtin__.open(filename, mode or 'rb')
Guido van Rossum68de3791997-07-19 20:22:23 +000037 if filename is None:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000038 if hasattr(fileobj, 'name'): filename = fileobj.name
39 else: filename = ''
Guido van Rossum68de3791997-07-19 20:22:23 +000040 if mode is None:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000041 if hasattr(fileobj, 'mode'): mode = fileobj.mode
Fred Drake9bb76d11999-04-05 18:33:40 +000042 else: mode = 'rb'
Guido van Rossum68de3791997-07-19 20:22:23 +000043
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000044 if mode[0:1] == 'r':
45 self.mode = READ
Andrew M. Kuchlingf4f119c1999-03-25 21:49:14 +000046 # Set flag indicating start of a new member
47 self._new_member = 1
48 self.extrabuf = ""
49 self.extrasize = 0
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000050 self.filename = filename
Guido van Rossum15262191997-04-30 16:04:57 +000051
Andrew M. Kuchlingf4f119c1999-03-25 21:49:14 +000052 elif mode[0:1] == 'w' or mode[0:1] == 'a':
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000053 self.mode = WRITE
54 self._init_write(filename)
55 self.compress = zlib.compressobj(compresslevel,
56 zlib.DEFLATED,
57 -zlib.MAX_WBITS,
58 zlib.DEF_MEM_LEVEL,
59 0)
60 else:
61 raise ValueError, "Mode " + mode + " not supported"
Guido van Rossum15262191997-04-30 16:04:57 +000062
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000063 self.fileobj = fileobj
Guido van Rossum15262191997-04-30 16:04:57 +000064
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000065 if self.mode == WRITE:
66 self._write_gzip_header()
Guido van Rossum15262191997-04-30 16:04:57 +000067
68 def __repr__(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000069 s = repr(self.fileobj)
70 return '<gzip ' + s[1:-1] + ' ' + hex(id(self)) + '>'
Guido van Rossum15262191997-04-30 16:04:57 +000071
72 def _init_write(self, filename):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000073 if filename[-3:] != '.gz':
74 filename = filename + '.gz'
75 self.filename = filename
76 self.crc = zlib.crc32("")
77 self.size = 0
78 self.writebuf = []
79 self.bufsize = 0
Guido van Rossum15262191997-04-30 16:04:57 +000080
81 def _write_gzip_header(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000082 self.fileobj.write('\037\213') # magic header
83 self.fileobj.write('\010') # compression method
84 fname = self.filename[:-3]
85 flags = 0
86 if fname:
87 flags = FNAME
88 self.fileobj.write(chr(flags))
Guido van Rossum95bdd0b1999-04-12 14:34:16 +000089 write32u(self.fileobj, long(time.time()))
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000090 self.fileobj.write('\002')
91 self.fileobj.write('\377')
92 if fname:
93 self.fileobj.write(fname + '\000')
Guido van Rossum15262191997-04-30 16:04:57 +000094
95 def _init_read(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000096 self.crc = zlib.crc32("")
97 self.size = 0
Guido van Rossum15262191997-04-30 16:04:57 +000098
99 def _read_gzip_header(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000100 magic = self.fileobj.read(2)
101 if magic != '\037\213':
Andrew M. Kuchlingf4f119c1999-03-25 21:49:14 +0000102 raise IOError, 'Not a gzipped file'
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000103 method = ord( self.fileobj.read(1) )
104 if method != 8:
Andrew M. Kuchlingf4f119c1999-03-25 21:49:14 +0000105 raise IOError, 'Unknown compression method'
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000106 flag = ord( self.fileobj.read(1) )
107 # modtime = self.fileobj.read(4)
108 # extraflag = self.fileobj.read(1)
109 # os = self.fileobj.read(1)
110 self.fileobj.read(6)
Guido van Rossum15262191997-04-30 16:04:57 +0000111
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000112 if flag & FEXTRA:
113 # Read & discard the extra field, if present
114 xlen=ord(self.fileobj.read(1))
115 xlen=xlen+256*ord(self.fileobj.read(1))
116 self.fileobj.read(xlen)
117 if flag & FNAME:
118 # Read and discard a null-terminated string containing the filename
119 while (1):
120 s=self.fileobj.read(1)
121 if not s or s=='\000': break
122 if flag & FCOMMENT:
123 # Read and discard a null-terminated string containing a comment
124 while (1):
125 s=self.fileobj.read(1)
126 if not s or s=='\000': break
127 if flag & FHCRC:
128 self.fileobj.read(2) # Read & discard the 16-bit header CRC
Guido van Rossum15262191997-04-30 16:04:57 +0000129
130
131 def write(self,data):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000132 if self.fileobj is None:
133 raise ValueError, "write() on closed GzipFile object"
134 if len(data) > 0:
135 self.size = self.size + len(data)
136 self.crc = zlib.crc32(data, self.crc)
137 self.fileobj.write( self.compress.compress(data) )
Guido van Rossum15262191997-04-30 16:04:57 +0000138
139 def writelines(self,lines):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000140 self.write(string.join(lines))
Guido van Rossum15262191997-04-30 16:04:57 +0000141
Jeremy Hyltonee918cb1998-05-13 21:49:58 +0000142 def read(self, size=None):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000143 if self.extrasize <= 0 and self.fileobj is None:
144 return ''
Guido van Rossumb16a3b81998-01-27 19:29:45 +0000145
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000146 readsize = 1024
147 if not size: # get the whole thing
148 try:
149 while 1:
150 self._read(readsize)
151 readsize = readsize * 2
152 except EOFError:
153 size = self.extrasize
154 else: # just get some more of it
155 try:
156 while size > self.extrasize:
157 self._read(readsize)
158 readsize = readsize * 2
159 except EOFError:
Guido van Rossum84c6fc91998-08-03 15:41:39 +0000160 if size > self.extrasize:
161 size = self.extrasize
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000162
163 chunk = self.extrabuf[:size]
164 self.extrabuf = self.extrabuf[size:]
165 self.extrasize = self.extrasize - size
Guido van Rossum15262191997-04-30 16:04:57 +0000166
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000167 return chunk
Guido van Rossum15262191997-04-30 16:04:57 +0000168
Guido van Rossumb16a3b81998-01-27 19:29:45 +0000169 def _unread(self, buf):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000170 self.extrabuf = buf + self.extrabuf
Guido van Rossum84c6fc91998-08-03 15:41:39 +0000171 self.extrasize = len(buf) + self.extrasize
Guido van Rossumb16a3b81998-01-27 19:29:45 +0000172
173 def _read(self, size=1024):
Andrew M. Kuchlingf4f119c1999-03-25 21:49:14 +0000174 if self.fileobj is None: raise EOFError, "Reached EOF"
175
176 if self._new_member:
177 # If the _new_member flag is set, we have to
178 #
179 # First, check if we're at the end of the file;
180 # if so, it's time to stop; no more members to read.
181 pos = self.fileobj.tell() # Save current position
182 self.fileobj.seek(0, 2) # Seek to end of file
183 if pos == self.fileobj.tell():
184 self.fileobj = None
Andrew M. Kuchling2d813e51999-09-06 16:34:51 +0000185 raise EOFError, "Reached EOF"
Andrew M. Kuchlingf4f119c1999-03-25 21:49:14 +0000186 else:
187 self.fileobj.seek( pos ) # Return to original position
188
189 self._init_read()
190 self._read_gzip_header()
191 self.decompress = zlib.decompressobj(-zlib.MAX_WBITS)
192 self._new_member = 0
193
194 # Read a chunk of data from the file
195 buf = self.fileobj.read(size)
196
197 # If the EOF has been reached, flush the decompression object
198 # and mark this object as finished.
199
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000200 if buf == "":
201 uncompress = self.decompress.flush()
Andrew M. Kuchlingf4f119c1999-03-25 21:49:14 +0000202 self._read_eof()
203 self.fileobj = None
204 self._add_read_data( uncompress )
205 raise EOFError, 'Reached EOF'
206
207 uncompress = self.decompress.decompress(buf)
208 self._add_read_data( uncompress )
209
210 if self.decompress.unused_data != "":
211 # Ending case: we've come to the end of a member in the file,
212 # so seek back to the start of the unused data, finish up
213 # this member, and read a new gzip header.
214 # (The number of bytes to seek back is the length of the unused
215 # data, minus 8 because _read_eof() will rewind a further 8 bytes)
216 self.fileobj.seek( -len(self.decompress.unused_data)+8, 1)
217
218 # Check the CRC and file size, and set the flag so we read
219 # a new member on the next call
220 self._read_eof()
221 self._new_member = 1
222
223 def _add_read_data(self, data):
224 self.crc = zlib.crc32(data, self.crc)
225 self.extrabuf = self.extrabuf + data
226 self.extrasize = self.extrasize + len(data)
227 self.size = self.size + len(data)
Guido van Rossum15262191997-04-30 16:04:57 +0000228
229 def _read_eof(self):
Andrew M. Kuchlingf4f119c1999-03-25 21:49:14 +0000230 # We've read to the end of the file, so we have to rewind in order
231 # to reread the 8 bytes containing the CRC and the file size.
232 # We check the that the computed CRC and size of the
233 # uncompressed data matches the stored values.
234 self.fileobj.seek(-8, 1)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000235 crc32 = read32(self.fileobj)
236 isize = read32(self.fileobj)
Guido van Rossum95bdd0b1999-04-12 14:34:16 +0000237 if crc32%0x100000000L != self.crc%0x100000000L:
Andrew M. Kuchlingf4f119c1999-03-25 21:49:14 +0000238 raise ValueError, "CRC check failed"
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000239 elif isize != self.size:
Andrew M. Kuchlingf4f119c1999-03-25 21:49:14 +0000240 raise ValueError, "Incorrect length of data produced"
241
Guido van Rossum15262191997-04-30 16:04:57 +0000242 def close(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000243 if self.mode == WRITE:
244 self.fileobj.write(self.compress.flush())
245 write32(self.fileobj, self.crc)
246 write32(self.fileobj, self.size)
247 self.fileobj = None
248 elif self.mode == READ:
249 self.fileobj = None
250 if self.myfileobj:
251 self.myfileobj.close()
252 self.myfileobj = None
Guido van Rossum15262191997-04-30 16:04:57 +0000253
Andrew M. Kuchling916fcc31999-08-10 13:19:30 +0000254 def __del__(self):
255 if (self.myfileobj is not None or
256 self.fileobj is not None):
257 self.close()
258
Guido van Rossum15262191997-04-30 16:04:57 +0000259 def flush(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000260 self.fileobj.flush()
Guido van Rossum15262191997-04-30 16:04:57 +0000261
262 def seek(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000263 raise IOError, 'Random access not allowed in gzip files'
Guido van Rossum15262191997-04-30 16:04:57 +0000264
265 def tell(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000266 raise IOError, 'I won\'t tell() you for gzip files'
Guido van Rossum15262191997-04-30 16:04:57 +0000267
268 def isatty(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000269 return 0
Guido van Rossum15262191997-04-30 16:04:57 +0000270
271 def readline(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000272 bufs = []
273 readsize = 100
274 while 1:
275 c = self.read(readsize)
276 i = string.find(c, '\n')
277 if i >= 0 or c == '':
Jeremy Hyltonee918cb1998-05-13 21:49:58 +0000278 bufs.append(c[:i+1])
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000279 self._unread(c[i+1:])
280 return string.join(bufs, '')
281 bufs.append(c)
282 readsize = readsize * 2
Guido van Rossum15262191997-04-30 16:04:57 +0000283
284 def readlines(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000285 buf = self.read()
Guido van Rossum84c6fc91998-08-03 15:41:39 +0000286 lines = string.split(buf, '\n')
287 for i in range(len(lines)-1):
288 lines[i] = lines[i] + '\n'
289 if lines and not lines[-1]:
290 del lines[-1]
291 return lines
Guido van Rossum15262191997-04-30 16:04:57 +0000292
Guido van Rossum68de3791997-07-19 20:22:23 +0000293 def writelines(self, L):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000294 for line in L:
295 self.write(line)
Guido van Rossum51ca6e31997-12-30 20:09:08 +0000296
297
298def _test():
299 # Act like gzip; with -d, act like gunzip.
300 # The input file is not deleted, however, nor are any other gzip
301 # options or features supported.
302 import sys
303 args = sys.argv[1:]
304 decompress = args and args[0] == "-d"
305 if decompress:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000306 args = args[1:]
Guido van Rossum51ca6e31997-12-30 20:09:08 +0000307 if not args:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000308 args = ["-"]
Guido van Rossum51ca6e31997-12-30 20:09:08 +0000309 for arg in args:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000310 if decompress:
311 if arg == "-":
312 f = GzipFile(filename="", mode="rb", fileobj=sys.stdin)
313 g = sys.stdout
314 else:
315 if arg[-3:] != ".gz":
316 print "filename doesn't end in .gz:", `arg`
317 continue
318 f = open(arg, "rb")
319 g = __builtin__.open(arg[:-3], "wb")
320 else:
321 if arg == "-":
322 f = sys.stdin
323 g = GzipFile(filename="", mode="wb", fileobj=sys.stdout)
324 else:
325 f = __builtin__.open(arg, "rb")
326 g = open(arg + ".gz", "wb")
327 while 1:
328 chunk = f.read(1024)
329 if not chunk:
330 break
331 g.write(chunk)
332 if g is not sys.stdout:
333 g.close()
334 if f is not sys.stdin:
335 f.close()
Guido van Rossum51ca6e31997-12-30 20:09:08 +0000336
337if __name__ == '__main__':
338 _test()