zipp.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  1. import io
  2. import posixpath
  3. import zipfile
  4. import itertools
  5. import contextlib
  6. import pathlib
  7. __all__ = ['Path']
  8. def _parents(path):
  9. """
  10. Given a path with elements separated by
  11. posixpath.sep, generate all parents of that path.
  12. >>> list(_parents('b/d'))
  13. ['b']
  14. >>> list(_parents('/b/d/'))
  15. ['/b']
  16. >>> list(_parents('b/d/f/'))
  17. ['b/d', 'b']
  18. >>> list(_parents('b'))
  19. []
  20. >>> list(_parents(''))
  21. []
  22. """
  23. return itertools.islice(_ancestry(path), 1, None)
  24. def _ancestry(path):
  25. """
  26. Given a path with elements separated by
  27. posixpath.sep, generate all elements of that path
  28. >>> list(_ancestry('b/d'))
  29. ['b/d', 'b']
  30. >>> list(_ancestry('/b/d/'))
  31. ['/b/d', '/b']
  32. >>> list(_ancestry('b/d/f/'))
  33. ['b/d/f', 'b/d', 'b']
  34. >>> list(_ancestry('b'))
  35. ['b']
  36. >>> list(_ancestry(''))
  37. []
  38. """
  39. path = path.rstrip(posixpath.sep)
  40. while path and path != posixpath.sep:
  41. yield path
  42. path, tail = posixpath.split(path)
  43. _dedupe = dict.fromkeys
  44. """Deduplicate an iterable in original order"""
  45. def _difference(minuend, subtrahend):
  46. """
  47. Return items in minuend not in subtrahend, retaining order
  48. with O(1) lookup.
  49. """
  50. return itertools.filterfalse(set(subtrahend).__contains__, minuend)
  51. class CompleteDirs(zipfile.ZipFile):
  52. """
  53. A ZipFile subclass that ensures that implied directories
  54. are always included in the namelist.
  55. """
  56. @staticmethod
  57. def _implied_dirs(names):
  58. parents = itertools.chain.from_iterable(map(_parents, names))
  59. as_dirs = (p + posixpath.sep for p in parents)
  60. return _dedupe(_difference(as_dirs, names))
  61. def namelist(self):
  62. names = super(CompleteDirs, self).namelist()
  63. return names + list(self._implied_dirs(names))
  64. def _name_set(self):
  65. return set(self.namelist())
  66. def resolve_dir(self, name):
  67. """
  68. If the name represents a directory, return that name
  69. as a directory (with the trailing slash).
  70. """
  71. names = self._name_set()
  72. dirname = name + '/'
  73. dir_match = name not in names and dirname in names
  74. return dirname if dir_match else name
  75. @classmethod
  76. def make(cls, source):
  77. """
  78. Given a source (filename or zipfile), return an
  79. appropriate CompleteDirs subclass.
  80. """
  81. if isinstance(source, CompleteDirs):
  82. return source
  83. if not isinstance(source, zipfile.ZipFile):
  84. return cls(source)
  85. # Only allow for FastLookup when supplied zipfile is read-only
  86. if 'r' not in source.mode:
  87. cls = CompleteDirs
  88. source.__class__ = cls
  89. return source
  90. class FastLookup(CompleteDirs):
  91. """
  92. ZipFile subclass to ensure implicit
  93. dirs exist and are resolved rapidly.
  94. """
  95. def namelist(self):
  96. with contextlib.suppress(AttributeError):
  97. return self.__names
  98. self.__names = super(FastLookup, self).namelist()
  99. return self.__names
  100. def _name_set(self):
  101. with contextlib.suppress(AttributeError):
  102. return self.__lookup
  103. self.__lookup = super(FastLookup, self)._name_set()
  104. return self.__lookup
  105. class Path:
  106. """
  107. A pathlib-compatible interface for zip files.
  108. Consider a zip file with this structure::
  109. .
  110. ├── a.txt
  111. └── b
  112. ├── c.txt
  113. └── d
  114. └── e.txt
  115. >>> data = io.BytesIO()
  116. >>> zf = zipfile.ZipFile(data, 'w')
  117. >>> zf.writestr('a.txt', 'content of a')
  118. >>> zf.writestr('b/c.txt', 'content of c')
  119. >>> zf.writestr('b/d/e.txt', 'content of e')
  120. >>> zf.filename = 'mem/abcde.zip'
  121. Path accepts the zipfile object itself or a filename
  122. >>> root = Path(zf)
  123. From there, several path operations are available.
  124. Directory iteration (including the zip file itself):
  125. >>> a, b = root.iterdir()
  126. >>> a
  127. Path('mem/abcde.zip', 'a.txt')
  128. >>> b
  129. Path('mem/abcde.zip', 'b/')
  130. name property:
  131. >>> b.name
  132. 'b'
  133. join with divide operator:
  134. >>> c = b / 'c.txt'
  135. >>> c
  136. Path('mem/abcde.zip', 'b/c.txt')
  137. >>> c.name
  138. 'c.txt'
  139. Read text:
  140. >>> c.read_text()
  141. 'content of c'
  142. existence:
  143. >>> c.exists()
  144. True
  145. >>> (b / 'missing.txt').exists()
  146. False
  147. Coercion to string:
  148. >>> import os
  149. >>> str(c).replace(os.sep, posixpath.sep)
  150. 'mem/abcde.zip/b/c.txt'
  151. At the root, ``name``, ``filename``, and ``parent``
  152. resolve to the zipfile. Note these attributes are not
  153. valid and will raise a ``ValueError`` if the zipfile
  154. has no filename.
  155. >>> root.name
  156. 'abcde.zip'
  157. >>> str(root.filename).replace(os.sep, posixpath.sep)
  158. 'mem/abcde.zip'
  159. >>> str(root.parent)
  160. 'mem'
  161. """
  162. __repr = "{self.__class__.__name__}({self.root.filename!r}, {self.at!r})"
  163. def __init__(self, root, at=""):
  164. """
  165. Construct a Path from a ZipFile or filename.
  166. Note: When the source is an existing ZipFile object,
  167. its type (__class__) will be mutated to a
  168. specialized type. If the caller wishes to retain the
  169. original type, the caller should either create a
  170. separate ZipFile object or pass a filename.
  171. """
  172. self.root = FastLookup.make(root)
  173. self.at = at
  174. def open(self, mode='r', *args, pwd=None, **kwargs):
  175. """
  176. Open this entry as text or binary following the semantics
  177. of ``pathlib.Path.open()`` by passing arguments through
  178. to io.TextIOWrapper().
  179. """
  180. if self.is_dir():
  181. raise IsADirectoryError(self)
  182. zip_mode = mode[0]
  183. if not self.exists() and zip_mode == 'r':
  184. raise FileNotFoundError(self)
  185. stream = self.root.open(self.at, zip_mode, pwd=pwd)
  186. if 'b' in mode:
  187. if args or kwargs:
  188. raise ValueError("encoding args invalid for binary operation")
  189. return stream
  190. return io.TextIOWrapper(stream, *args, **kwargs)
  191. @property
  192. def name(self):
  193. return pathlib.Path(self.at).name or self.filename.name
  194. @property
  195. def suffix(self):
  196. return pathlib.Path(self.at).suffix or self.filename.suffix
  197. @property
  198. def suffixes(self):
  199. return pathlib.Path(self.at).suffixes or self.filename.suffixes
  200. @property
  201. def stem(self):
  202. return pathlib.Path(self.at).stem or self.filename.stem
  203. @property
  204. def filename(self):
  205. return pathlib.Path(self.root.filename).joinpath(self.at)
  206. def read_text(self, *args, **kwargs):
  207. with self.open('r', *args, **kwargs) as strm:
  208. return strm.read()
  209. def read_bytes(self):
  210. with self.open('rb') as strm:
  211. return strm.read()
  212. def _is_child(self, path):
  213. return posixpath.dirname(path.at.rstrip("/")) == self.at.rstrip("/")
  214. def _next(self, at):
  215. return self.__class__(self.root, at)
  216. def is_dir(self):
  217. return not self.at or self.at.endswith("/")
  218. def is_file(self):
  219. return self.exists() and not self.is_dir()
  220. def exists(self):
  221. return self.at in self.root._name_set()
  222. def iterdir(self):
  223. if not self.is_dir():
  224. raise ValueError("Can't listdir a file")
  225. subs = map(self._next, self.root.namelist())
  226. return filter(self._is_child, subs)
  227. def __str__(self):
  228. return posixpath.join(self.root.filename, self.at)
  229. def __repr__(self):
  230. return self.__repr.format(self=self)
  231. def joinpath(self, *other):
  232. next = posixpath.join(self.at, *other)
  233. return self._next(self.root.resolve_dir(next))
  234. __truediv__ = joinpath
  235. @property
  236. def parent(self):
  237. if not self.at:
  238. return self.filename.parent
  239. parent_at = posixpath.dirname(self.at.rstrip('/'))
  240. if parent_at:
  241. parent_at += '/'
  242. return self._next(parent_at)