home *** CD-ROM | disk | FTP | other *** search
/ Chip 2004 December / CHIP_CD_2004-12.iso / bonus / oo / OOo_1.1.3_ru_RU_infra_WinIntel_install.exe / $PLUGINSDIR / f_0372 / python-core-2.2.2 / lib / gzip.py < prev    next >
Text File  |  2004-10-09  |  13KB  |  391 lines

  1. """Functions that read and write gzipped files.
  2.  
  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.  
  8. import struct, sys, time
  9. import zlib
  10. import __builtin__
  11.  
  12. __all__ = ["GzipFile","open"]
  13.  
  14. FTEXT, FHCRC, FEXTRA, FNAME, FCOMMENT = 1, 2, 4, 8, 16
  15.  
  16. READ, WRITE = 1, 2
  17.  
  18. def write32(output, value):
  19.     output.write(struct.pack("<l", value))
  20.  
  21. def write32u(output, value):
  22.     if value < 0:
  23.         value = value + 0x100000000L
  24.     output.write(struct.pack("<L", value))
  25.  
  26. def read32(input):
  27.     return struct.unpack("<l", input.read(4))[0]
  28.  
  29. def open(filename, mode="rb", compresslevel=9):
  30.     return GzipFile(filename, mode, compresslevel)
  31.  
  32. class GzipFile:
  33.  
  34.     myfileobj = None
  35.  
  36.     def __init__(self, filename=None, mode=None,
  37.                  compresslevel=9, fileobj=None):
  38.         # guarantee the file is opened in binary mode on platforms
  39.         # that care about that sort of thing
  40.         if mode and 'b' not in mode:
  41.             mode += 'b'
  42.         if fileobj is None:
  43.             fileobj = self.myfileobj = __builtin__.open(filename, mode or 'rb')
  44.         if filename is None:
  45.             if hasattr(fileobj, 'name'): filename = fileobj.name
  46.             else: filename = ''
  47.         if mode is None:
  48.             if hasattr(fileobj, 'mode'): mode = fileobj.mode
  49.             else: mode = 'rb'
  50.  
  51.         if mode[0:1] == 'r':
  52.             self.mode = READ
  53.             # Set flag indicating start of a new member
  54.             self._new_member = 1
  55.             self.extrabuf = ""
  56.             self.extrasize = 0
  57.             self.filename = filename
  58.  
  59.         elif mode[0:1] == 'w' or mode[0:1] == 'a':
  60.             self.mode = WRITE
  61.             self._init_write(filename)
  62.             self.compress = zlib.compressobj(compresslevel,
  63.                                              zlib.DEFLATED,
  64.                                              -zlib.MAX_WBITS,
  65.                                              zlib.DEF_MEM_LEVEL,
  66.                                              0)
  67.         else:
  68.             raise ValueError, "Mode " + mode + " not supported"
  69.  
  70.         self.fileobj = fileobj
  71.         self.offset = 0
  72.  
  73.         if self.mode == WRITE:
  74.             self._write_gzip_header()
  75.  
  76.     def __repr__(self):
  77.         s = repr(self.fileobj)
  78.         return '<gzip ' + s[1:-1] + ' ' + hex(id(self)) + '>'
  79.  
  80.     def _init_write(self, filename):
  81.         if filename[-3:] != '.gz':
  82.             filename = filename + '.gz'
  83.         self.filename = filename
  84.         self.crc = zlib.crc32("")
  85.         self.size = 0
  86.         self.writebuf = []
  87.         self.bufsize = 0
  88.  
  89.     def _write_gzip_header(self):
  90.         self.fileobj.write('\037\213')             # magic header
  91.         self.fileobj.write('\010')                 # compression method
  92.         fname = self.filename[:-3]
  93.         flags = 0
  94.         if fname:
  95.             flags = FNAME
  96.         self.fileobj.write(chr(flags))
  97.         write32u(self.fileobj, long(time.time()))
  98.         self.fileobj.write('\002')
  99.         self.fileobj.write('\377')
  100.         if fname:
  101.             self.fileobj.write(fname + '\000')
  102.  
  103.     def _init_read(self):
  104.         self.crc = zlib.crc32("")
  105.         self.size = 0
  106.  
  107.     def _read_gzip_header(self):
  108.         magic = self.fileobj.read(2)
  109.         if magic != '\037\213':
  110.             raise IOError, 'Not a gzipped file'
  111.         method = ord( self.fileobj.read(1) )
  112.         if method != 8:
  113.             raise IOError, 'Unknown compression method'
  114.         flag = ord( self.fileobj.read(1) )
  115.         # modtime = self.fileobj.read(4)
  116.         # extraflag = self.fileobj.read(1)
  117.         # os = self.fileobj.read(1)
  118.         self.fileobj.read(6)
  119.  
  120.         if flag & FEXTRA:
  121.             # Read & discard the extra field, if present
  122.             xlen=ord(self.fileobj.read(1))
  123.             xlen=xlen+256*ord(self.fileobj.read(1))
  124.             self.fileobj.read(xlen)
  125.         if flag & FNAME:
  126.             # Read and discard a null-terminated string containing the filename
  127.             while (1):
  128.                 s=self.fileobj.read(1)
  129.                 if not s or s=='\000': break
  130.         if flag & FCOMMENT:
  131.             # Read and discard a null-terminated string containing a comment
  132.             while (1):
  133.                 s=self.fileobj.read(1)
  134.                 if not s or s=='\000': break
  135.         if flag & FHCRC:
  136.             self.fileobj.read(2)     # Read & discard the 16-bit header CRC
  137.  
  138.  
  139.     def write(self,data):
  140.         if self.fileobj is None:
  141.             raise ValueError, "write() on closed GzipFile object"
  142.         if len(data) > 0:
  143.             self.size = self.size + len(data)
  144.             self.crc = zlib.crc32(data, self.crc)
  145.             self.fileobj.write( self.compress.compress(data) )
  146.             self.offset += len(data)
  147.  
  148.     def read(self, size=-1):
  149.         if self.extrasize <= 0 and self.fileobj is None:
  150.             return ''
  151.  
  152.         readsize = 1024
  153.         if size < 0:        # get the whole thing
  154.             try:
  155.                 while 1:
  156.                     self._read(readsize)
  157.                     readsize = readsize * 2
  158.             except EOFError:
  159.                 size = self.extrasize
  160.         else:               # just get some more of it
  161.             try:
  162.                 while size > self.extrasize:
  163.                     self._read(readsize)
  164.                     readsize = readsize * 2
  165.             except EOFError:
  166.                 if size > self.extrasize:
  167.                     size = self.extrasize
  168.  
  169.         chunk = self.extrabuf[:size]
  170.         self.extrabuf = self.extrabuf[size:]
  171.         self.extrasize = self.extrasize - size
  172.  
  173.         self.offset += size
  174.         return chunk
  175.  
  176.     def _unread(self, buf):
  177.         self.extrabuf = buf + self.extrabuf
  178.         self.extrasize = len(buf) + self.extrasize
  179.         self.offset -= len(buf)
  180.  
  181.     def _read(self, size=1024):
  182.         if self.fileobj is None: raise EOFError, "Reached EOF"
  183.  
  184.         if self._new_member:
  185.             # If the _new_member flag is set, we have to
  186.             # jump to the next member, if there is one.
  187.             #
  188.             # First, check if we're at the end of the file;
  189.             # if so, it's time to stop; no more members to read.
  190.             pos = self.fileobj.tell()   # Save current position
  191.             self.fileobj.seek(0, 2)     # Seek to end of file
  192.             if pos == self.fileobj.tell():
  193.                 raise EOFError, "Reached EOF"
  194.             else:
  195.                 self.fileobj.seek( pos ) # Return to original position
  196.  
  197.             self._init_read()
  198.             self._read_gzip_header()
  199.             self.decompress = zlib.decompressobj(-zlib.MAX_WBITS)
  200.             self._new_member = 0
  201.  
  202.         # Read a chunk of data from the file
  203.         buf = self.fileobj.read(size)
  204.  
  205.         # If the EOF has been reached, flush the decompression object
  206.         # and mark this object as finished.
  207.  
  208.         if buf == "":
  209.             uncompress = self.decompress.flush()
  210.             self._read_eof()
  211.             self._add_read_data( uncompress )
  212.             raise EOFError, 'Reached EOF'
  213.  
  214.         uncompress = self.decompress.decompress(buf)
  215.         self._add_read_data( uncompress )
  216.  
  217.         if self.decompress.unused_data != "":
  218.             # Ending case: we've come to the end of a member in the file,
  219.             # so seek back to the start of the unused data, finish up
  220.             # this member, and read a new gzip header.
  221.             # (The number of bytes to seek back is the length of the unused
  222.             # data, minus 8 because _read_eof() will rewind a further 8 bytes)
  223.             self.fileobj.seek( -len(self.decompress.unused_data)+8, 1)
  224.  
  225.             # Check the CRC and file size, and set the flag so we read
  226.             # a new member on the next call
  227.             self._read_eof()
  228.             self._new_member = 1
  229.  
  230.     def _add_read_data(self, data):
  231.         self.crc = zlib.crc32(data, self.crc)
  232.         self.extrabuf = self.extrabuf + data
  233.         self.extrasize = self.extrasize + len(data)
  234.         self.size = self.size + len(data)
  235.  
  236.     def _read_eof(self):
  237.         # We've read to the end of the file, so we have to rewind in order
  238.         # to reread the 8 bytes containing the CRC and the file size.
  239.         # We check the that the computed CRC and size of the
  240.         # uncompressed data matches the stored values.
  241.         self.fileobj.seek(-8, 1)
  242.         crc32 = read32(self.fileobj)
  243.         isize = read32(self.fileobj)
  244.         if crc32%0x100000000L != self.crc%0x100000000L:
  245.             raise ValueError, "CRC check failed"
  246.         elif isize != self.size:
  247.             raise ValueError, "Incorrect length of data produced"
  248.  
  249.     def close(self):
  250.         if self.mode == WRITE:
  251.             self.fileobj.write(self.compress.flush())
  252.             write32(self.fileobj, self.crc)
  253.             write32(self.fileobj, self.size)
  254.             self.fileobj = None
  255.         elif self.mode == READ:
  256.             self.fileobj = None
  257.         if self.myfileobj:
  258.             self.myfileobj.close()
  259.             self.myfileobj = None
  260.  
  261.     def __del__(self):
  262.         try:
  263.             if (self.myfileobj is None and
  264.                 self.fileobj is None):
  265.                 return
  266.         except AttributeError:
  267.             return
  268.         self.close()
  269.  
  270.     def flush(self):
  271.         self.fileobj.flush()
  272.  
  273.     def isatty(self):
  274.         return 0
  275.  
  276.     def tell(self):
  277.         return self.offset
  278.  
  279.     def rewind(self):
  280.         '''Return the uncompressed stream file position indicator to the
  281.         beginning of the file'''
  282.         if self.mode != READ:
  283.             raise IOError("Can't rewind in write mode")
  284.         self.fileobj.seek(0)
  285.         self._new_member = 1
  286.         self.extrabuf = ""
  287.         self.extrasize = 0
  288.         self.offset = 0
  289.  
  290.     def seek(self, offset):
  291.         if self.mode == WRITE:
  292.             if offset < self.offset:
  293.                 raise IOError('Negative seek in write mode')
  294.             count = offset - self.offset
  295.             for i in range(count/1024):
  296.                 self.write(1024*'\0')
  297.             self.write((count%1024)*'\0')
  298.         elif self.mode == READ:
  299.             if offset < self.offset:
  300.                 # for negative seek, rewind and do positive seek
  301.                 self.rewind()
  302.             count = offset - self.offset
  303.             for i in range(count/1024): self.read(1024)
  304.             self.read(count % 1024)
  305.  
  306.     def readline(self, size=-1):
  307.         if size < 0: size = sys.maxint
  308.         bufs = []
  309.         readsize = min(100, size)    # Read from the file in small chunks
  310.         while 1:
  311.             if size == 0:
  312.                 return "".join(bufs) # Return resulting line
  313.  
  314.             c = self.read(readsize)
  315.             i = c.find('\n')
  316.             if size is not None:
  317.                 # We set i=size to break out of the loop under two
  318.                 # conditions: 1) there's no newline, and the chunk is
  319.                 # larger than size, or 2) there is a newline, but the
  320.                 # resulting line would be longer than 'size'.
  321.                 if i==-1 and len(c) > size: i=size-1
  322.                 elif size <= i: i = size -1
  323.  
  324.             if i >= 0 or c == '':
  325.                 bufs.append(c[:i+1])    # Add portion of last chunk
  326.                 self._unread(c[i+1:])   # Push back rest of chunk
  327.                 return ''.join(bufs)    # Return resulting line
  328.  
  329.             # Append chunk to list, decrease 'size',
  330.             bufs.append(c)
  331.             size = size - len(c)
  332.             readsize = min(size, readsize * 2)
  333.  
  334.     def readlines(self, sizehint=0):
  335.         # Negative numbers result in reading all the lines
  336.         if sizehint <= 0: sizehint = sys.maxint
  337.         L = []
  338.         while sizehint > 0:
  339.             line = self.readline()
  340.             if line == "": break
  341.             L.append( line )
  342.             sizehint = sizehint - len(line)
  343.  
  344.         return L
  345.  
  346.     def writelines(self, L):
  347.         for line in L:
  348.             self.write(line)
  349.  
  350.  
  351. def _test():
  352.     # Act like gzip; with -d, act like gunzip.
  353.     # The input file is not deleted, however, nor are any other gzip
  354.     # options or features supported.
  355.     args = sys.argv[1:]
  356.     decompress = args and args[0] == "-d"
  357.     if decompress:
  358.         args = args[1:]
  359.     if not args:
  360.         args = ["-"]
  361.     for arg in args:
  362.         if decompress:
  363.             if arg == "-":
  364.                 f = GzipFile(filename="", mode="rb", fileobj=sys.stdin)
  365.                 g = sys.stdout
  366.             else:
  367.                 if arg[-3:] != ".gz":
  368.                     print "filename doesn't end in .gz:", `arg`
  369.                     continue
  370.                 f = open(arg, "rb")
  371.                 g = __builtin__.open(arg[:-3], "wb")
  372.         else:
  373.             if arg == "-":
  374.                 f = sys.stdin
  375.                 g = GzipFile(filename="", mode="wb", fileobj=sys.stdout)
  376.             else:
  377.                 f = __builtin__.open(arg, "rb")
  378.                 g = open(arg + ".gz", "wb")
  379.         while 1:
  380.             chunk = f.read(1024)
  381.             if not chunk:
  382.                 break
  383.             g.write(chunk)
  384.         if g is not sys.stdout:
  385.             g.close()
  386.         if f is not sys.stdin:
  387.             f.close()
  388.  
  389. if __name__ == '__main__':
  390.     _test()
  391.