blob: fda112180a710d6a761a00c26293d01c3f462039 [file] [log] [blame]
Guido van Rossum15262191997-04-30 16:04:57 +00001import time
2import string
3import zlib
Guido van Rossum68de3791997-07-19 20:22:23 +00004import __builtin__
Guido van Rossum15262191997-04-30 16:04:57 +00005
6# implements a python function that reads and writes a gzipped file
7# the user of the file doesn't have to worry about the compression,
Guido van Rossum51ca6e31997-12-30 20:09:08 +00008# but random access is not allowed
Guido van Rossum15262191997-04-30 16:04:57 +00009
10# based on Andrew Kuchling's minigzip.py distributed with the zlib module
11
12FTEXT, FHCRC, FEXTRA, FNAME, FCOMMENT = 1, 2, 4, 8, 16
13
14READ, WRITE = 1, 2
15
16def write32(output, value):
17 t = divmod(value, 256)
18 b1 = chr(t[1])
19
20 t = divmod(t[0], 256)
21 b2 = chr(t[1])
22
23 t = divmod(t[0], 256)
24 b3 = chr(t[1])
25
26 t = divmod(t[0], 256)
27 b4 = chr(t[1])
28
29 buf = b1 + b2 + b3 + b4
30 output.write(buf)
31
32
33def read32(input):
34 buf = input.read(4)
35 v = ord(buf[0])
36 v = v + (ord(buf[1]) << 8)
37 v = v + (ord(buf[2]) << 16)
38 v = v + (ord(buf[3]) << 24)
39 return v
40
Guido van Rossum68de3791997-07-19 20:22:23 +000041def open(filename, mode="r", compresslevel=9):
Guido van Rossum15262191997-04-30 16:04:57 +000042 return GzipFile(filename, mode, compresslevel)
43
44class GzipFile:
45
Guido van Rossum68de3791997-07-19 20:22:23 +000046 myfileobj = None
47
48 def __init__(self, filename=None, mode=None,
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000049 compresslevel=9, fileobj=None):
50 if fileobj is None:
51 fileobj = self.myfileobj = __builtin__.open(filename, mode or 'r')
Guido van Rossum68de3791997-07-19 20:22:23 +000052 if filename is None:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000053 if hasattr(fileobj, 'name'): filename = fileobj.name
54 else: filename = ''
Guido van Rossum68de3791997-07-19 20:22:23 +000055 if mode is None:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000056 if hasattr(fileobj, 'mode'): mode = fileobj.mode
57 else: mode = 'r'
Guido van Rossum68de3791997-07-19 20:22:23 +000058
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000059 if mode[0:1] == 'r':
60 self.mode = READ
61 self._init_read()
62 self.filename = filename
63 self.decompress = zlib.decompressobj(-zlib.MAX_WBITS)
Guido van Rossum15262191997-04-30 16:04:57 +000064
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000065 elif mode[0:1] == 'w':
66 self.mode = WRITE
67 self._init_write(filename)
68 self.compress = zlib.compressobj(compresslevel,
69 zlib.DEFLATED,
70 -zlib.MAX_WBITS,
71 zlib.DEF_MEM_LEVEL,
72 0)
73 else:
74 raise ValueError, "Mode " + mode + " not supported"
Guido van Rossum15262191997-04-30 16:04:57 +000075
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000076 self.fileobj = fileobj
Guido van Rossum15262191997-04-30 16:04:57 +000077
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000078 if self.mode == WRITE:
79 self._write_gzip_header()
80 elif self.mode == READ:
81 self._read_gzip_header()
Guido van Rossum15262191997-04-30 16:04:57 +000082
83 def __repr__(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000084 s = repr(self.fileobj)
85 return '<gzip ' + s[1:-1] + ' ' + hex(id(self)) + '>'
Guido van Rossum15262191997-04-30 16:04:57 +000086
87 def _init_write(self, filename):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000088 if filename[-3:] != '.gz':
89 filename = filename + '.gz'
90 self.filename = filename
91 self.crc = zlib.crc32("")
92 self.size = 0
93 self.writebuf = []
94 self.bufsize = 0
Guido van Rossum15262191997-04-30 16:04:57 +000095
96 def _write_gzip_header(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000097 self.fileobj.write('\037\213') # magic header
98 self.fileobj.write('\010') # compression method
99 fname = self.filename[:-3]
100 flags = 0
101 if fname:
102 flags = FNAME
103 self.fileobj.write(chr(flags))
104 write32(self.fileobj, int(time.time()))
105 self.fileobj.write('\002')
106 self.fileobj.write('\377')
107 if fname:
108 self.fileobj.write(fname + '\000')
Guido van Rossum15262191997-04-30 16:04:57 +0000109
110 def _init_read(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000111 self.crc = zlib.crc32("")
112 self.size = 0
113 self.extrabuf = ""
114 self.extrasize = 0
Guido van Rossum15262191997-04-30 16:04:57 +0000115
116 def _read_gzip_header(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000117 magic = self.fileobj.read(2)
118 if magic != '\037\213':
119 raise RuntimeError, 'Not a gzipped file'
120 method = ord( self.fileobj.read(1) )
121 if method != 8:
122 raise RuntimeError, 'Unknown compression method'
123 flag = ord( self.fileobj.read(1) )
124 # modtime = self.fileobj.read(4)
125 # extraflag = self.fileobj.read(1)
126 # os = self.fileobj.read(1)
127 self.fileobj.read(6)
Guido van Rossum15262191997-04-30 16:04:57 +0000128
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000129 if flag & FEXTRA:
130 # Read & discard the extra field, if present
131 xlen=ord(self.fileobj.read(1))
132 xlen=xlen+256*ord(self.fileobj.read(1))
133 self.fileobj.read(xlen)
134 if flag & FNAME:
135 # Read and discard a null-terminated string containing the filename
136 while (1):
137 s=self.fileobj.read(1)
138 if not s or s=='\000': break
139 if flag & FCOMMENT:
140 # Read and discard a null-terminated string containing a comment
141 while (1):
142 s=self.fileobj.read(1)
143 if not s or s=='\000': break
144 if flag & FHCRC:
145 self.fileobj.read(2) # Read & discard the 16-bit header CRC
Guido van Rossum15262191997-04-30 16:04:57 +0000146
147
148 def write(self,data):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000149 if self.fileobj is None:
150 raise ValueError, "write() on closed GzipFile object"
151 if len(data) > 0:
152 self.size = self.size + len(data)
153 self.crc = zlib.crc32(data, self.crc)
154 self.fileobj.write( self.compress.compress(data) )
Guido van Rossum15262191997-04-30 16:04:57 +0000155
156 def writelines(self,lines):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000157 self.write(string.join(lines))
Guido van Rossum15262191997-04-30 16:04:57 +0000158
Jeremy Hyltonee918cb1998-05-13 21:49:58 +0000159 def read(self, size=None):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000160 if self.extrasize <= 0 and self.fileobj is None:
161 return ''
Guido van Rossumb16a3b81998-01-27 19:29:45 +0000162
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000163 readsize = 1024
164 if not size: # get the whole thing
165 try:
166 while 1:
167 self._read(readsize)
168 readsize = readsize * 2
169 except EOFError:
170 size = self.extrasize
171 else: # just get some more of it
172 try:
173 while size > self.extrasize:
174 self._read(readsize)
175 readsize = readsize * 2
176 except EOFError:
177 pass
178
179 chunk = self.extrabuf[:size]
180 self.extrabuf = self.extrabuf[size:]
181 self.extrasize = self.extrasize - size
Guido van Rossum15262191997-04-30 16:04:57 +0000182
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000183 return chunk
Guido van Rossum15262191997-04-30 16:04:57 +0000184
Guido van Rossumb16a3b81998-01-27 19:29:45 +0000185 def _unread(self, buf):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000186 self.extrabuf = buf + self.extrabuf
Jeremy Hyltonee918cb1998-05-13 21:49:58 +0000187 self.extrasize = len(self.extrabuf)
Guido van Rossumb16a3b81998-01-27 19:29:45 +0000188
189 def _read(self, size=1024):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000190 try:
191 buf = self.fileobj.read(size)
192 except AttributeError:
193 raise EOFError, "Reached EOF"
194 if buf == "":
195 uncompress = self.decompress.flush()
196 if uncompress == "":
197 self._read_eof()
198 self.fileobj = None
199 raise EOFError, 'Reached EOF'
200 else:
201 uncompress = self.decompress.decompress(buf)
202 self.crc = zlib.crc32(uncompress, self.crc)
203 self.extrabuf = self.extrabuf + uncompress
204 self.extrasize = self.extrasize + len(uncompress)
205 self.size = self.size + len(uncompress)
Guido van Rossum15262191997-04-30 16:04:57 +0000206
207 def _read_eof(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000208 # Andrew writes:
209 ## We've read to the end of the file, so we have to rewind in order
210 ## to reread the 8 bytes containing the CRC and the file size. The
211 ## decompressor is smart and knows when to stop, so feeding it
212 ## extra data is harmless.
213 self.fileobj.seek(-8, 2)
214 crc32 = read32(self.fileobj)
215 isize = read32(self.fileobj)
216 if crc32 != self.crc:
217 self.error = "CRC check failed"
218 elif isize != self.size:
219 self.error = "Incorrect length of data produced"
Guido van Rossum15262191997-04-30 16:04:57 +0000220
221 def close(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000222 if self.mode == WRITE:
223 self.fileobj.write(self.compress.flush())
224 write32(self.fileobj, self.crc)
225 write32(self.fileobj, self.size)
226 self.fileobj = None
227 elif self.mode == READ:
228 self.fileobj = None
229 if self.myfileobj:
230 self.myfileobj.close()
231 self.myfileobj = None
Guido van Rossum15262191997-04-30 16:04:57 +0000232
233 def flush(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000234 self.fileobj.flush()
Guido van Rossum15262191997-04-30 16:04:57 +0000235
236 def seek(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000237 raise IOError, 'Random access not allowed in gzip files'
Guido van Rossum15262191997-04-30 16:04:57 +0000238
239 def tell(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000240 raise IOError, 'I won\'t tell() you for gzip files'
Guido van Rossum15262191997-04-30 16:04:57 +0000241
242 def isatty(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000243 return 0
Guido van Rossum15262191997-04-30 16:04:57 +0000244
245 def readline(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000246 bufs = []
247 readsize = 100
248 while 1:
249 c = self.read(readsize)
250 i = string.find(c, '\n')
251 if i >= 0 or c == '':
Jeremy Hyltonee918cb1998-05-13 21:49:58 +0000252 bufs.append(c[:i+1])
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000253 self._unread(c[i+1:])
254 return string.join(bufs, '')
255 bufs.append(c)
256 readsize = readsize * 2
Guido van Rossum15262191997-04-30 16:04:57 +0000257
258 def readlines(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000259 buf = self.read()
260 return string.split(buf, '\n')
Guido van Rossum15262191997-04-30 16:04:57 +0000261
Guido van Rossum68de3791997-07-19 20:22:23 +0000262 def writelines(self, L):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000263 for line in L:
264 self.write(line)
Guido van Rossum51ca6e31997-12-30 20:09:08 +0000265
266
267def _test():
268 # Act like gzip; with -d, act like gunzip.
269 # The input file is not deleted, however, nor are any other gzip
270 # options or features supported.
271 import sys
272 args = sys.argv[1:]
273 decompress = args and args[0] == "-d"
274 if decompress:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000275 args = args[1:]
Guido van Rossum51ca6e31997-12-30 20:09:08 +0000276 if not args:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000277 args = ["-"]
Guido van Rossum51ca6e31997-12-30 20:09:08 +0000278 for arg in args:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000279 if decompress:
280 if arg == "-":
281 f = GzipFile(filename="", mode="rb", fileobj=sys.stdin)
282 g = sys.stdout
283 else:
284 if arg[-3:] != ".gz":
285 print "filename doesn't end in .gz:", `arg`
286 continue
287 f = open(arg, "rb")
288 g = __builtin__.open(arg[:-3], "wb")
289 else:
290 if arg == "-":
291 f = sys.stdin
292 g = GzipFile(filename="", mode="wb", fileobj=sys.stdout)
293 else:
294 f = __builtin__.open(arg, "rb")
295 g = open(arg + ".gz", "wb")
296 while 1:
297 chunk = f.read(1024)
298 if not chunk:
299 break
300 g.write(chunk)
301 if g is not sys.stdout:
302 g.close()
303 if f is not sys.stdin:
304 f.close()
Guido van Rossum51ca6e31997-12-30 20:09:08 +0000305
306if __name__ == '__main__':
307 _test()