MozZipFile.py 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  1. # ***** BEGIN LICENSE BLOCK *****
  2. # Version: MPL 1.1/GPL 2.0/LGPL 2.1
  3. #
  4. # The contents of this file are subject to the Mozilla Public License Version
  5. # 1.1 (the "License"); you may not use this file except in compliance with
  6. # the License. You may obtain a copy of the License at
  7. # http://www.mozilla.org/MPL/
  8. #
  9. # Software distributed under the License is distributed on an "AS IS" basis,
  10. # WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
  11. # for the specific language governing rights and limitations under the
  12. # License.
  13. #
  14. # The Original Code is Mozilla build system.
  15. #
  16. # The Initial Developer of the Original Code is
  17. # Mozilla Foundation.
  18. # Portions created by the Initial Developer are Copyright (C) 2007
  19. # the Initial Developer. All Rights Reserved.
  20. #
  21. # Contributor(s):
  22. # Axel Hecht <axel@pike.org>
  23. #
  24. # Alternatively, the contents of this file may be used under the terms of
  25. # either the GNU General Public License Version 2 or later (the "GPL"), or
  26. # the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
  27. # in which case the provisions of the GPL or the LGPL are applicable instead
  28. # of those above. If you wish to allow use of your version of this file only
  29. # under the terms of either the GPL or the LGPL, and not to allow others to
  30. # use your version of this file under the terms of the MPL, indicate your
  31. # decision by deleting the provisions above and replace them with the notice
  32. # and other provisions required by the GPL or the LGPL. If you do not delete
  33. # the provisions above, a recipient may use your version of this file under
  34. # the terms of any one of the MPL, the GPL or the LGPL.
  35. #
  36. # ***** END LICENSE BLOCK *****
  37. import zipfile
  38. import time
  39. import binascii, struct
  40. import zlib
  41. import os
  42. from utils import lockFile
  43. class ZipFile(zipfile.ZipFile):
  44. """ Class with methods to open, read, write, close, list zip files.
  45. Subclassing zipfile.ZipFile to allow for overwriting of existing
  46. entries, though only for writestr, not for write.
  47. """
  48. def __init__(self, file, mode="r", compression=zipfile.ZIP_STORED,
  49. lock = False):
  50. if lock:
  51. assert isinstance(file, basestring)
  52. self.lockfile = lockFile(file + '.lck')
  53. else:
  54. self.lockfile = None
  55. if mode == 'a' and lock:
  56. # appending to a file which doesn't exist fails, but we can't check
  57. # existence util we hold the lock
  58. if (not os.path.isfile(file)) or os.path.getsize(file) == 0:
  59. mode = 'w'
  60. zipfile.ZipFile.__init__(self, file, mode, compression)
  61. self._remove = []
  62. self.end = self.fp.tell()
  63. self.debug = 0
  64. def writestr(self, zinfo_or_arcname, bytes):
  65. """Write contents into the archive.
  66. The contents is the argument 'bytes', 'zinfo_or_arcname' is either
  67. a ZipInfo instance or the name of the file in the archive.
  68. This method is overloaded to allow overwriting existing entries.
  69. """
  70. if not isinstance(zinfo_or_arcname, zipfile.ZipInfo):
  71. zinfo = zipfile.ZipInfo(filename=zinfo_or_arcname,
  72. date_time=time.localtime(time.time()))
  73. zinfo.compress_type = self.compression
  74. # Add some standard UNIX file access permissions (-rw-r--r--).
  75. zinfo.external_attr = (0x81a4 & 0xFFFF) << 16L
  76. else:
  77. zinfo = zinfo_or_arcname
  78. # Now to the point why we overwrote this in the first place,
  79. # remember the entry numbers if we already had this entry.
  80. # Optimizations:
  81. # If the entry to overwrite is the last one, just reuse that.
  82. # If we store uncompressed and the new content has the same size
  83. # as the old, reuse the existing entry.
  84. doSeek = False # store if we need to seek to the eof after overwriting
  85. if self.NameToInfo.has_key(zinfo.filename):
  86. # Find the last ZipInfo with our name.
  87. # Last, because that's catching multiple overwrites
  88. i = len(self.filelist)
  89. while i > 0:
  90. i -= 1
  91. if self.filelist[i].filename == zinfo.filename:
  92. break
  93. zi = self.filelist[i]
  94. if ((zinfo.compress_type == zipfile.ZIP_STORED
  95. and zi.compress_size == len(bytes))
  96. or (i + 1) == len(self.filelist)):
  97. # make sure we're allowed to write, otherwise done by writestr below
  98. self._writecheck(zi)
  99. # overwrite existing entry
  100. self.fp.seek(zi.header_offset)
  101. if (i + 1) == len(self.filelist):
  102. # this is the last item in the file, just truncate
  103. self.fp.truncate()
  104. else:
  105. # we need to move to the end of the file afterwards again
  106. doSeek = True
  107. # unhook the current zipinfo, the writestr of our superclass
  108. # will add a new one
  109. self.filelist.pop(i)
  110. self.NameToInfo.pop(zinfo.filename)
  111. else:
  112. # Couldn't optimize, sadly, just remember the old entry for removal
  113. self._remove.append(self.filelist.pop(i))
  114. zipfile.ZipFile.writestr(self, zinfo, bytes)
  115. self.filelist.sort(lambda l, r: cmp(l.header_offset, r.header_offset))
  116. if doSeek:
  117. self.fp.seek(self.end)
  118. self.end = self.fp.tell()
  119. def close(self):
  120. """Close the file, and for mode "w" and "a" write the ending
  121. records.
  122. Overwritten to compact overwritten entries.
  123. """
  124. if not self._remove:
  125. # we don't have anything special to do, let's just call base
  126. r = zipfile.ZipFile.close(self)
  127. self.lockfile = None
  128. return r
  129. if self.fp.mode != 'r+b':
  130. # adjust file mode if we originally just wrote, now we rewrite
  131. self.fp.close()
  132. self.fp = open(self.filename, 'r+b')
  133. all = map(lambda zi: (zi, True), self.filelist) + \
  134. map(lambda zi: (zi, False), self._remove)
  135. all.sort(lambda l, r: cmp(l[0].header_offset, r[0].header_offset))
  136. # empty _remove for multiple closes
  137. self._remove = []
  138. lengths = [all[i+1][0].header_offset - all[i][0].header_offset
  139. for i in xrange(len(all)-1)]
  140. lengths.append(self.end - all[-1][0].header_offset)
  141. to_pos = 0
  142. for (zi, keep), length in zip(all, lengths):
  143. if not keep:
  144. continue
  145. oldoff = zi.header_offset
  146. # python <= 2.4 has file_offset
  147. if hasattr(zi, 'file_offset'):
  148. zi.file_offset = zi.file_offset + to_pos - oldoff
  149. zi.header_offset = to_pos
  150. self.fp.seek(oldoff)
  151. content = self.fp.read(length)
  152. self.fp.seek(to_pos)
  153. self.fp.write(content)
  154. to_pos += length
  155. self.fp.truncate()
  156. zipfile.ZipFile.close(self)
  157. self.lockfile = None