Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/zipp/__init__.py: 54%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

180 statements  

1""" 

2A Path-like interface for zipfiles. 

3 

4This codebase is shared between zipfile.Path in the stdlib 

5and zipp in PyPI. See 

6https://github.com/python/importlib_metadata/wiki/Development-Methodology 

7for more detail. 

8""" 

9 

10import functools 

11import io 

12import itertools 

13import pathlib 

14import posixpath 

15import re 

16import stat 

17import zipfile 

18 

19from ._functools import none_as, save_method_args 

20from .compat.py310 import text_encoding 

21from .glob import Translator 

22 

23__all__ = ['Path'] 

24 

25 

26def _parents(path): 

27 """ 

28 Given a path with elements separated by 

29 posixpath.sep, generate all parents of that path. 

30 

31 >>> list(_parents('b/d')) 

32 ['b'] 

33 >>> list(_parents('/b/d/')) 

34 ['/b'] 

35 >>> list(_parents('b/d/f/')) 

36 ['b/d', 'b'] 

37 >>> list(_parents('b')) 

38 [] 

39 >>> list(_parents('')) 

40 [] 

41 """ 

42 return itertools.islice(_ancestry(path), 1, None) 

43 

44 

45def _ancestry(path): 

46 """ 

47 Given a path with elements separated by 

48 posixpath.sep, generate all elements of that path. 

49 

50 >>> list(_ancestry('b/d')) 

51 ['b/d', 'b'] 

52 >>> list(_ancestry('/b/d/')) 

53 ['/b/d', '/b'] 

54 >>> list(_ancestry('b/d/f/')) 

55 ['b/d/f', 'b/d', 'b'] 

56 >>> list(_ancestry('b')) 

57 ['b'] 

58 >>> list(_ancestry('')) 

59 [] 

60 

61 Multiple separators are treated like a single. 

62 

63 >>> list(_ancestry('//b//d///f//')) 

64 ['//b//d///f', '//b//d', '//b'] 

65 """ 

66 path = path.rstrip(posixpath.sep) 

67 while path.rstrip(posixpath.sep): 

68 yield path 

69 path, _tail = posixpath.split(path) 

70 

71 

72_dedupe = dict.fromkeys 

73"""Deduplicate an iterable in original order""" 

74 

75 

76def _difference(minuend, subtrahend): 

77 """ 

78 Return items in minuend not in subtrahend, retaining order 

79 with O(1) lookup. 

80 """ 

81 return itertools.filterfalse(set(subtrahend).__contains__, minuend) 

82 

83 

84class InitializedState: 

85 """ 

86 Mix-in to save the initialization state for pickling. 

87 """ 

88 

89 @save_method_args 

90 def __init__(self, *args, **kwargs): 

91 super().__init__(*args, **kwargs) 

92 

93 def __getstate__(self): 

94 return self._saved___init__.args, self._saved___init__.kwargs 

95 

96 def __setstate__(self, state): 

97 args, kwargs = state 

98 super().__init__(*args, **kwargs) 

99 

100 

101class CompleteDirs(InitializedState, zipfile.ZipFile): 

102 """ 

103 A ZipFile subclass that ensures that implied directories 

104 are always included in the namelist. 

105 

106 >>> list(CompleteDirs._implied_dirs(['foo/bar.txt', 'foo/bar/baz.txt'])) 

107 ['foo/', 'foo/bar/'] 

108 >>> list(CompleteDirs._implied_dirs(['foo/bar.txt', 'foo/bar/baz.txt', 'foo/bar/'])) 

109 ['foo/'] 

110 """ 

111 

112 @staticmethod 

113 def _implied_dirs(names): 

114 parents = itertools.chain.from_iterable(map(_parents, names)) 

115 as_dirs = (p + posixpath.sep for p in parents) 

116 return _dedupe(_difference(as_dirs, names)) 

117 

118 def namelist(self): 

119 names = super().namelist() 

120 return names + list(self._implied_dirs(names)) 

121 

122 def _name_set(self): 

123 return set(self.namelist()) 

124 

125 def resolve_dir(self, name): 

126 """ 

127 If the name represents a directory, return that name 

128 as a directory (with the trailing slash). 

129 """ 

130 names = self._name_set() 

131 dirname = name + '/' 

132 dir_match = name not in names and dirname in names 

133 return dirname if dir_match else name 

134 

135 def getinfo(self, name): 

136 """ 

137 Supplement getinfo for implied dirs. 

138 """ 

139 try: 

140 return super().getinfo(name) 

141 except KeyError: 

142 if not name.endswith('/') or name not in self._name_set(): 

143 raise 

144 return zipfile.ZipInfo(filename=name) 

145 

146 @classmethod 

147 def make(cls, source): 

148 """ 

149 Given a source (filename or zipfile), return an 

150 appropriate CompleteDirs subclass. 

151 """ 

152 if isinstance(source, CompleteDirs): 

153 return source 

154 

155 if not isinstance(source, zipfile.ZipFile): 

156 return cls(source) 

157 

158 # Only allow for FastLookup when supplied zipfile is read-only 

159 source.__class__ = cls if 'r' in source.mode else CompleteDirs 

160 return source 

161 

162 @classmethod 

163 def inject(cls, zf: zipfile.ZipFile) -> zipfile.ZipFile: 

164 """ 

165 Given a writable zip file zf, inject directory entries for 

166 any directories implied by the presence of children. 

167 """ 

168 for name in cls._implied_dirs(zf.namelist()): 

169 zf.writestr(name, b"") 

170 return zf 

171 

172 

173class FastLookup(CompleteDirs): 

174 """ 

175 ZipFile subclass to ensure implicit 

176 dirs exist and are resolved rapidly. 

177 """ 

178 

179 def namelist(self): 

180 return self._namelist 

181 

182 @functools.cached_property 

183 def _namelist(self): 

184 return super().namelist() 

185 

186 def _name_set(self): 

187 return self._name_set_prop 

188 

189 @functools.cached_property 

190 def _name_set_prop(self): 

191 return super()._name_set() 

192 

193 

194def _extract_text_encoding(encoding=None, *args, **kwargs): 

195 stack_level = 3 

196 return text_encoding(encoding, stack_level), args, kwargs 

197 

198 

199class Path: 

200 """ 

201 A :class:`importlib.resources.abc.Traversable` interface for zip files. 

202 

203 Implements many of the features users enjoy from 

204 :class:`pathlib.Path`. 

205 

206 Consider a zip file with this structure:: 

207 

208 . 

209 ├── a.txt 

210 └── b 

211 ├── c.txt 

212 └── d 

213 └── e.txt 

214 

215 >>> data = io.BytesIO() 

216 >>> zf = zipfile.ZipFile(data, 'w') 

217 >>> zf.writestr('a.txt', 'content of a') 

218 >>> zf.writestr('b/c.txt', 'content of c') 

219 >>> zf.writestr('b/d/e.txt', 'content of e') 

220 >>> zf.filename = 'mem/abcde.zip' 

221 

222 Path accepts the zipfile object itself or a filename 

223 

224 >>> path = Path(zf) 

225 

226 From there, several path operations are available. 

227 

228 Directory iteration (including the zip file itself): 

229 

230 >>> a, b = path.iterdir() 

231 >>> a 

232 Path('mem/abcde.zip', 'a.txt') 

233 >>> b 

234 Path('mem/abcde.zip', 'b/') 

235 

236 name property: 

237 

238 >>> b.name 

239 'b' 

240 

241 join with divide operator: 

242 

243 >>> c = b / 'c.txt' 

244 >>> c 

245 Path('mem/abcde.zip', 'b/c.txt') 

246 >>> c.name 

247 'c.txt' 

248 

249 Read text: 

250 

251 >>> c.read_text(encoding='utf-8') 

252 'content of c' 

253 

254 existence: 

255 

256 >>> c.exists() 

257 True 

258 >>> (b / 'missing.txt').exists() 

259 False 

260 

261 Coercion to string: 

262 

263 >>> import os 

264 >>> str(c).replace(os.sep, posixpath.sep) 

265 'mem/abcde.zip/b/c.txt' 

266 

267 At the root, ``name``, ``filename``, and ``parent`` 

268 resolve to the zipfile. 

269 

270 >>> str(path) 

271 'mem/abcde.zip' 

272 >>> path.name 

273 'abcde.zip' 

274 >>> path.filename == pathlib.Path('mem/abcde.zip') 

275 True 

276 >>> str(path.parent) 

277 'mem' 

278 

279 If the zipfile has no filename, such attributes are not 

280 valid and accessing them will raise an Exception. 

281 

282 >>> zf.filename = None 

283 >>> path.name 

284 Traceback (most recent call last): 

285 ... 

286 TypeError: ... 

287 

288 >>> path.filename 

289 Traceback (most recent call last): 

290 ... 

291 TypeError: ... 

292 

293 >>> path.parent 

294 Traceback (most recent call last): 

295 ... 

296 TypeError: ... 

297 

298 # workaround python/cpython#106763 

299 >>> pass 

300 """ 

301 

302 __repr = "{self.__class__.__name__}({self.root.filename!r}, {self.at!r})" 

303 

304 def __init__(self, root, at=""): 

305 """ 

306 Construct a Path from a ZipFile or filename. 

307 

308 Note: When the source is an existing ZipFile object, 

309 its type (__class__) will be mutated to a 

310 specialized type. If the caller wishes to retain the 

311 original type, the caller should either create a 

312 separate ZipFile object or pass a filename. 

313 """ 

314 self.root = FastLookup.make(root) 

315 self.at = at 

316 

317 def __eq__(self, other): 

318 """ 

319 >>> Path(zipfile.ZipFile(io.BytesIO(), 'w')) == 'foo' 

320 False 

321 """ 

322 if self.__class__ is not other.__class__: 

323 return NotImplemented 

324 return (self.root, self.at) == (other.root, other.at) 

325 

326 def __hash__(self): 

327 return hash((self.root, self.at)) 

328 

329 def open(self, mode='r', *args, pwd=None, **kwargs): 

330 """ 

331 Open this entry as text or binary following the semantics 

332 of ``pathlib.Path.open()`` by passing arguments through 

333 to io.TextIOWrapper(). 

334 """ 

335 if self.is_dir(): 

336 raise IsADirectoryError(self) 

337 zip_mode = mode[0] 

338 if zip_mode == 'r' and not self.exists(): 

339 raise FileNotFoundError(self) 

340 stream = self.root.open(self.at, zip_mode, pwd=pwd) 

341 if 'b' in mode: 

342 if args or kwargs: 

343 raise ValueError("encoding args invalid for binary operation") 

344 return stream 

345 # Text mode: 

346 encoding, args, kwargs = _extract_text_encoding(*args, **kwargs) 

347 return io.TextIOWrapper(stream, encoding, *args, **kwargs) 

348 

349 def _base(self): 

350 return pathlib.PurePosixPath(self.at) if self.at else self.filename 

351 

352 @property 

353 def name(self): 

354 return self._base().name 

355 

356 @property 

357 def suffix(self): 

358 return self._base().suffix 

359 

360 @property 

361 def suffixes(self): 

362 return self._base().suffixes 

363 

364 @property 

365 def stem(self): 

366 return self._base().stem 

367 

368 @property 

369 def filename(self): 

370 return pathlib.Path(self.root.filename).joinpath(self.at) 

371 

372 def read_text(self, *args, **kwargs): 

373 encoding, args, kwargs = _extract_text_encoding(*args, **kwargs) 

374 with self.open('r', encoding, *args, **kwargs) as strm: 

375 return strm.read() 

376 

377 def read_bytes(self): 

378 with self.open('rb') as strm: 

379 return strm.read() 

380 

381 def _is_child(self, path): 

382 return posixpath.dirname(path.at.rstrip("/")) == self.at.rstrip("/") 

383 

384 def _next(self, at): 

385 return self.__class__(self.root, at) 

386 

387 def is_dir(self): 

388 return not self.at or self.at.endswith("/") 

389 

390 def is_file(self): 

391 return self.exists() and not self.is_dir() 

392 

393 def exists(self): 

394 return self.at in self.root._name_set() 

395 

396 def iterdir(self): 

397 if not self.is_dir(): 

398 raise NotADirectoryError("Can't listdir a file") 

399 subs = map(self._next, self.root.namelist()) 

400 return filter(self._is_child, subs) 

401 

402 def match(self, path_pattern): 

403 return pathlib.PurePosixPath(self.at).match(path_pattern) 

404 

405 def is_symlink(self): 

406 """ 

407 Return whether this path is a symlink. 

408 """ 

409 info = self.root.getinfo(self.at) 

410 mode = info.external_attr >> 16 

411 return stat.S_ISLNK(mode) 

412 

413 def glob(self, pattern): 

414 if not pattern: 

415 raise ValueError(f"Unacceptable pattern: {pattern!r}") 

416 

417 prefix = re.escape(self.at) 

418 tr = Translator(seps='/') 

419 matches = re.compile(prefix + tr.translate(pattern)).fullmatch 

420 return map(self._next, filter(matches, self.root.namelist())) 

421 

422 def rglob(self, pattern): 

423 return self.glob(f'**/{pattern}') 

424 

425 def relative_to(self, other, *extra): 

426 return posixpath.relpath(str(self), str(other.joinpath(*extra))) 

427 

428 def __str__(self): 

429 root = none_as(self.root.filename, ':zipfile:') 

430 return posixpath.join(root, self.at) if self.at else root 

431 

432 def __repr__(self): 

433 return self.__repr.format(self=self) 

434 

435 def joinpath(self, *other): 

436 next = posixpath.join(self.at, *other) 

437 return self._next(self.root.resolve_dir(next)) 

438 

439 __truediv__ = joinpath 

440 

441 @property 

442 def parent(self): 

443 if not self.at: 

444 return self.filename.parent 

445 parent_at = posixpath.dirname(self.at.rstrip('/')) 

446 if parent_at: 

447 parent_at += '/' 

448 return self._next(parent_at)