blob: e0c7c5bd581976df7f374f03c718b6ebce176c85 [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
20def read32(input):
Jeremy Hyltonc19f9971999-03-23 23:05:34 +000021 return struct.unpack("<l", input.read(4))[0]
Guido van Rossum15262191997-04-30 16:04:57 +000022
Guido van Rossum68de3791997-07-19 20:22:23 +000023def open(filename, mode="r", compresslevel=9):
Guido van Rossum15262191997-04-30 16:04:57 +000024 return GzipFile(filename, mode, compresslevel)
25
26class GzipFile:
27
Guido van Rossum68de3791997-07-19 20:22:23 +000028 myfileobj = None
29
30 def __init__(self, filename=None, mode=None,
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000031 compresslevel=9, fileobj=None):
32 if fileobj is None:
33 fileobj = self.myfileobj = __builtin__.open(filename, mode or 'r')
Guido van Rossum68de3791997-07-19 20:22:23 +000034 if filename is None:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000035 if hasattr(fileobj, 'name'): filename = fileobj.name
36 else: filename = ''
Guido van Rossum68de3791997-07-19 20:22:23 +000037 if mode is None:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000038 if hasattr(fileobj, 'mode'): mode = fileobj.mode
39 else: mode = 'r'
Guido van Rossum68de3791997-07-19 20:22:23 +000040
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000041 if mode[0:1] == 'r':
42 self.mode = READ
43 self._init_read()
44 self.filename = filename
45 self.decompress = zlib.decompressobj(-zlib.MAX_WBITS)
Guido van Rossum15262191997-04-30 16:04:57 +000046
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000047 elif mode[0:1] == 'w':
48 self.mode = WRITE
49 self._init_write(filename)
50 self.compress = zlib.compressobj(compresslevel,
51 zlib.DEFLATED,
52 -zlib.MAX_WBITS,
53 zlib.DEF_MEM_LEVEL,
54 0)
55 else:
56 raise ValueError, "Mode " + mode + " not supported"
Guido van Rossum15262191997-04-30 16:04:57 +000057
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000058 self.fileobj = fileobj
Guido van Rossum15262191997-04-30 16:04:57 +000059
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000060 if self.mode == WRITE:
61 self._write_gzip_header()
62 elif self.mode == READ:
63 self._read_gzip_header()
Guido van Rossum15262191997-04-30 16:04:57 +000064
65 def __repr__(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000066 s = repr(self.fileobj)
67 return '<gzip ' + s[1:-1] + ' ' + hex(id(self)) + '>'
Guido van Rossum15262191997-04-30 16:04:57 +000068
69 def _init_write(self, filename):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000070 if filename[-3:] != '.gz':
71 filename = filename + '.gz'
72 self.filename = filename
73 self.crc = zlib.crc32("")
74 self.size = 0
75 self.writebuf = []
76 self.bufsize = 0
Guido van Rossum15262191997-04-30 16:04:57 +000077
78 def _write_gzip_header(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000079 self.fileobj.write('\037\213') # magic header
80 self.fileobj.write('\010') # compression method
81 fname = self.filename[:-3]
82 flags = 0
83 if fname:
84 flags = FNAME
85 self.fileobj.write(chr(flags))
86 write32(self.fileobj, int(time.time()))
87 self.fileobj.write('\002')
88 self.fileobj.write('\377')
89 if fname:
90 self.fileobj.write(fname + '\000')
Guido van Rossum15262191997-04-30 16:04:57 +000091
92 def _init_read(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000093 self.crc = zlib.crc32("")
94 self.size = 0
95 self.extrabuf = ""
96 self.extrasize = 0
Guido van Rossum15262191997-04-30 16:04:57 +000097
98 def _read_gzip_header(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000099 magic = self.fileobj.read(2)
100 if magic != '\037\213':
101 raise RuntimeError, 'Not a gzipped file'
102 method = ord( self.fileobj.read(1) )
103 if method != 8:
104 raise RuntimeError, 'Unknown compression method'
105 flag = ord( self.fileobj.read(1) )
106 # modtime = self.fileobj.read(4)
107 # extraflag = self.fileobj.read(1)
108 # os = self.fileobj.read(1)
109 self.fileobj.read(6)
Guido van Rossum15262191997-04-30 16:04:57 +0000110
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000111 if flag & FEXTRA:
112 # Read & discard the extra field, if present
113 xlen=ord(self.fileobj.read(1))
114 xlen=xlen+256*ord(self.fileobj.read(1))
115 self.fileobj.read(xlen)
116 if flag & FNAME:
117 # Read and discard a null-terminated string containing the filename
118 while (1):
119 s=self.fileobj.read(1)
120 if not s or s=='\000': break
121 if flag & FCOMMENT:
122 # Read and discard a null-terminated string containing a comment
123 while (1):
124 s=self.fileobj.read(1)
125 if not s or s=='\000': break
126 if flag & FHCRC:
127 self.fileobj.read(2) # Read & discard the 16-bit header CRC
Guido van Rossum15262191997-04-30 16:04:57 +0000128
129
130 def write(self,data):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000131 if self.fileobj is None:
132 raise ValueError, "write() on closed GzipFile object"
133 if len(data) > 0:
134 self.size = self.size + len(data)
135 self.crc = zlib.crc32(data, self.crc)
136 self.fileobj.write( self.compress.compress(data) )
Guido van Rossum15262191997-04-30 16:04:57 +0000137
138 def writelines(self,lines):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000139 self.write(string.join(lines))
Guido van Rossum15262191997-04-30 16:04:57 +0000140
Jeremy Hyltonee918cb1998-05-13 21:49:58 +0000141 def read(self, size=None):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000142 if self.extrasize <= 0 and self.fileobj is None:
143 return ''
Guido van Rossumb16a3b81998-01-27 19:29:45 +0000144
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000145 readsize = 1024
146 if not size: # get the whole thing
147 try:
148 while 1:
149 self._read(readsize)
150 readsize = readsize * 2
151 except EOFError:
152 size = self.extrasize
153 else: # just get some more of it
154 try:
155 while size > self.extrasize:
156 self._read(readsize)
157 readsize = readsize * 2
158 except EOFError:
Guido van Rossum84c6fc91998-08-03 15:41:39 +0000159 if size > self.extrasize:
160 size = self.extrasize
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000161
162 chunk = self.extrabuf[:size]
163 self.extrabuf = self.extrabuf[size:]
164 self.extrasize = self.extrasize - size
Guido van Rossum15262191997-04-30 16:04:57 +0000165
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000166 return chunk
Guido van Rossum15262191997-04-30 16:04:57 +0000167
Guido van Rossumb16a3b81998-01-27 19:29:45 +0000168 def _unread(self, buf):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000169 self.extrabuf = buf + self.extrabuf
Guido van Rossum84c6fc91998-08-03 15:41:39 +0000170 self.extrasize = len(buf) + self.extrasize
Guido van Rossumb16a3b81998-01-27 19:29:45 +0000171
172 def _read(self, size=1024):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000173 try:
174 buf = self.fileobj.read(size)
175 except AttributeError:
176 raise EOFError, "Reached EOF"
177 if buf == "":
178 uncompress = self.decompress.flush()
179 if uncompress == "":
180 self._read_eof()
181 self.fileobj = None
182 raise EOFError, 'Reached EOF'
183 else:
184 uncompress = self.decompress.decompress(buf)
185 self.crc = zlib.crc32(uncompress, self.crc)
186 self.extrabuf = self.extrabuf + uncompress
187 self.extrasize = self.extrasize + len(uncompress)
188 self.size = self.size + len(uncompress)
Guido van Rossum15262191997-04-30 16:04:57 +0000189
190 def _read_eof(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000191 # Andrew writes:
192 ## We've read to the end of the file, so we have to rewind in order
193 ## to reread the 8 bytes containing the CRC and the file size. The
194 ## decompressor is smart and knows when to stop, so feeding it
195 ## extra data is harmless.
196 self.fileobj.seek(-8, 2)
197 crc32 = read32(self.fileobj)
198 isize = read32(self.fileobj)
199 if crc32 != self.crc:
200 self.error = "CRC check failed"
201 elif isize != self.size:
202 self.error = "Incorrect length of data produced"
Guido van Rossum15262191997-04-30 16:04:57 +0000203
204 def close(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000205 if self.mode == WRITE:
206 self.fileobj.write(self.compress.flush())
207 write32(self.fileobj, self.crc)
208 write32(self.fileobj, self.size)
209 self.fileobj = None
210 elif self.mode == READ:
211 self.fileobj = None
212 if self.myfileobj:
213 self.myfileobj.close()
214 self.myfileobj = None
Guido van Rossum15262191997-04-30 16:04:57 +0000215
216 def flush(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000217 self.fileobj.flush()
Guido van Rossum15262191997-04-30 16:04:57 +0000218
219 def seek(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000220 raise IOError, 'Random access not allowed in gzip files'
Guido van Rossum15262191997-04-30 16:04:57 +0000221
222 def tell(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000223 raise IOError, 'I won\'t tell() you for gzip files'
Guido van Rossum15262191997-04-30 16:04:57 +0000224
225 def isatty(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000226 return 0
Guido van Rossum15262191997-04-30 16:04:57 +0000227
228 def readline(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000229 bufs = []
230 readsize = 100
231 while 1:
232 c = self.read(readsize)
233 i = string.find(c, '\n')
234 if i >= 0 or c == '':
Jeremy Hyltonee918cb1998-05-13 21:49:58 +0000235 bufs.append(c[:i+1])
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000236 self._unread(c[i+1:])
237 return string.join(bufs, '')
238 bufs.append(c)
239 readsize = readsize * 2
Guido van Rossum15262191997-04-30 16:04:57 +0000240
241 def readlines(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000242 buf = self.read()
Guido van Rossum84c6fc91998-08-03 15:41:39 +0000243 lines = string.split(buf, '\n')
244 for i in range(len(lines)-1):
245 lines[i] = lines[i] + '\n'
246 if lines and not lines[-1]:
247 del lines[-1]
248 return lines
Guido van Rossum15262191997-04-30 16:04:57 +0000249
Guido van Rossum68de3791997-07-19 20:22:23 +0000250 def writelines(self, L):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000251 for line in L:
252 self.write(line)
Guido van Rossum51ca6e31997-12-30 20:09:08 +0000253
254
255def _test():
256 # Act like gzip; with -d, act like gunzip.
257 # The input file is not deleted, however, nor are any other gzip
258 # options or features supported.
259 import sys
260 args = sys.argv[1:]
261 decompress = args and args[0] == "-d"
262 if decompress:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000263 args = args[1:]
Guido van Rossum51ca6e31997-12-30 20:09:08 +0000264 if not args:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000265 args = ["-"]
Guido van Rossum51ca6e31997-12-30 20:09:08 +0000266 for arg in args:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000267 if decompress:
268 if arg == "-":
269 f = GzipFile(filename="", mode="rb", fileobj=sys.stdin)
270 g = sys.stdout
271 else:
272 if arg[-3:] != ".gz":
273 print "filename doesn't end in .gz:", `arg`
274 continue
275 f = open(arg, "rb")
276 g = __builtin__.open(arg[:-3], "wb")
277 else:
278 if arg == "-":
279 f = sys.stdin
280 g = GzipFile(filename="", mode="wb", fileobj=sys.stdout)
281 else:
282 f = __builtin__.open(arg, "rb")
283 g = open(arg + ".gz", "wb")
284 while 1:
285 chunk = f.read(1024)
286 if not chunk:
287 break
288 g.write(chunk)
289 if g is not sys.stdout:
290 g.close()
291 if f is not sys.stdin:
292 f.close()
Guido van Rossum51ca6e31997-12-30 20:09:08 +0000293
294if __name__ == '__main__':
295 _test()