zipp.py 8.2 KB

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