1 # -*- test-case-name: twisted.test.test_paths.ZipFilePathTestCase -*-
2 # Copyright (c) Twisted Matrix Laboratories.
3 # See LICENSE for details.
6 This module contains implementations of IFilePath for zip files.
8 See the constructor for ZipArchive for use.
18 # Python 2.6 includes support for incremental unzipping of zipfiles, and
19 # thus obviates the need for ChunkingZipFile.
21 if sys.version_info[:2] >= (2, 6):
23 from zipfile import ZipFile
26 from twisted.python.zipstream import ChunkingZipFile
28 from twisted.python.filepath import IFilePath, FilePath, AbstractFilePath
30 from zope.interface import implements
32 # using FilePath here exclusively rather than os to make sure that we don't do
33 # anything OS-path-specific here.
35 ZIP_PATH_SEP = '/' # In zipfiles, "/" is universally used as the
36 # path separator, regardless of platform.
39 class ZipPath(AbstractFilePath):
41 I represent a file or directory contained within a zip file.
48 def __init__(self, archive, pathInArchive):
50 Don't construct me directly. Use ZipArchive.child().
52 @param archive: a ZipArchive instance.
54 @param pathInArchive: a ZIP_PATH_SEP-separated string.
56 self.archive = archive
57 self.pathInArchive = pathInArchive
58 # self.path pretends to be os-specific because that's the way the
59 # 'zipimport' module does it.
60 self.path = os.path.join(archive.zipfile.filename,
61 *(self.pathInArchive.split(ZIP_PATH_SEP)))
63 def __cmp__(self, other):
64 if not isinstance(other, ZipPath):
66 return cmp((self.archive, self.pathInArchive),
67 (other.archive, other.pathInArchive))
71 parts = [os.path.abspath(self.archive.path)]
72 parts.extend(self.pathInArchive.split(ZIP_PATH_SEP))
73 path = os.sep.join(parts)
74 return "ZipPath('%s')" % (path.encode('string-escape'),)
78 splitup = self.pathInArchive.split(ZIP_PATH_SEP)
81 return ZipPath(self.archive, ZIP_PATH_SEP.join(splitup[:-1]))
84 def child(self, path):
86 Return a new ZipPath representing a path in C{self.archive} which is
89 @note: Requesting the C{".."} (or other special name) child will not
90 cause L{InsecurePath} to be raised since these names do not have
91 any special meaning inside a zip archive. Be particularly
92 careful with the C{path} attribute (if you absolutely must use
93 it) as this means it may include special names with special
94 meaning outside of the context of a zip archive.
96 return ZipPath(self.archive, ZIP_PATH_SEP.join([self.pathInArchive, path]))
99 def sibling(self, path):
100 return self.parent().child(path)
102 # preauthChild = child
105 return self.isdir() or self.isfile()
108 return self.pathInArchive in self.archive.childmap
111 return self.pathInArchive in self.archive.zipfile.NameToInfo
119 return self.archive.childmap[self.pathInArchive].keys()
121 raise OSError(errno.ENOTDIR, "Leaf zip entry listed")
123 raise OSError(errno.ENOENT, "Non-existent zip entry listed")
128 Return a value similar to that returned by os.path.splitext.
130 # This happens to work out because of the fact that we use OS-specific
131 # path separators in the constructor to construct our fake 'path'
133 return os.path.splitext(self.path)
137 return self.pathInArchive.split(ZIP_PATH_SEP)[-1]
140 # XXX NOTE: This API isn't a very good idea on filepath, but it's even
141 # less meaningful here.
142 return self.parent().path
144 def open(self, mode="r"):
146 return self.archive.zipfile.open(self.pathInArchive, mode=mode)
148 # XXX oh man, is this too much hax?
149 self.archive.zipfile.mode = mode
150 return self.archive.zipfile.readfile(self.pathInArchive)
157 Retrieve this file's size.
159 @return: file size, in bytes
162 return self.archive.zipfile.NameToInfo[self.pathInArchive].file_size
164 def getAccessTime(self):
166 Retrieve this file's last access-time. This is the same as the last access
167 time for the archive.
169 @return: a number of seconds since the epoch
171 return self.archive.getAccessTime()
174 def getModificationTime(self):
176 Retrieve this file's last modification time. This is the time of
177 modification recorded in the zipfile.
179 @return: a number of seconds since the epoch.
182 self.archive.zipfile.NameToInfo[self.pathInArchive].date_time
186 def getStatusChangeTime(self):
188 Retrieve this file's last modification time. This name is provided for
189 compatibility, and returns the same value as getmtime.
191 @return: a number of seconds since the epoch.
193 return self.getModificationTime()
197 class ZipArchive(ZipPath):
198 """ I am a FilePath-like object which can wrap a zip archive as if it were a
201 archive = property(lambda self: self)
202 def __init__(self, archivePathname):
203 """Create a ZipArchive, treating the archive at archivePathname as a zip file.
205 @param archivePathname: a str, naming a path in the filesystem.
208 self.zipfile = ZipFile(archivePathname)
210 self.zipfile = ChunkingZipFile(archivePathname)
211 self.path = archivePathname
212 self.pathInArchive = ''
213 # zipfile is already wasting O(N) memory on cached ZipInfo instances,
214 # so there's no sense in trying to do this lazily or intelligently
215 self.childmap = {} # map parent: list of children
217 for name in self.zipfile.namelist():
218 name = name.split(ZIP_PATH_SEP)
219 for x in range(len(name)):
221 parent = ZIP_PATH_SEP.join(name[:-x])
222 if parent not in self.childmap:
223 self.childmap[parent] = {}
224 self.childmap[parent][child] = 1
227 def child(self, path):
229 Create a ZipPath pointing at a path within the archive.
231 @param path: a str with no path separators in it, either '/' or the
232 system path separator, if it's different.
234 return ZipPath(self, path)
238 Returns true if the underlying archive exists.
240 return FilePath(self.zipfile.filename).exists()
243 def getAccessTime(self):
245 Return the archive file's last access time.
247 return FilePath(self.zipfile.filename).getAccessTime()
250 def getModificationTime(self):
252 Return the archive file's modification time.
254 return FilePath(self.zipfile.filename).getModificationTime()
257 def getStatusChangeTime(self):
259 Return the archive file's status change time.
261 return FilePath(self.zipfile.filename).getStatusChangeTime()
265 return 'ZipArchive(%r)' % (os.path.abspath(self.path),)
268 __all__ = ['ZipArchive', 'ZipPath']