Path: blob/main/test/lib/python3.9/site-packages/setuptools/_vendor/zipp.py
4799 views
import io1import posixpath2import zipfile3import itertools4import contextlib5import sys6import pathlib78if sys.version_info < (3, 7):9from collections import OrderedDict10else:11OrderedDict = dict121314__all__ = ['Path']151617def _parents(path):18"""19Given a path with elements separated by20posixpath.sep, generate all parents of that path.2122>>> list(_parents('b/d'))23['b']24>>> list(_parents('/b/d/'))25['/b']26>>> list(_parents('b/d/f/'))27['b/d', 'b']28>>> list(_parents('b'))29[]30>>> list(_parents(''))31[]32"""33return itertools.islice(_ancestry(path), 1, None)343536def _ancestry(path):37"""38Given a path with elements separated by39posixpath.sep, generate all elements of that path4041>>> list(_ancestry('b/d'))42['b/d', 'b']43>>> list(_ancestry('/b/d/'))44['/b/d', '/b']45>>> list(_ancestry('b/d/f/'))46['b/d/f', 'b/d', 'b']47>>> list(_ancestry('b'))48['b']49>>> list(_ancestry(''))50[]51"""52path = path.rstrip(posixpath.sep)53while path and path != posixpath.sep:54yield path55path, tail = posixpath.split(path)565758_dedupe = OrderedDict.fromkeys59"""Deduplicate an iterable in original order"""606162def _difference(minuend, subtrahend):63"""64Return items in minuend not in subtrahend, retaining order65with O(1) lookup.66"""67return itertools.filterfalse(set(subtrahend).__contains__, minuend)686970class CompleteDirs(zipfile.ZipFile):71"""72A ZipFile subclass that ensures that implied directories73are always included in the namelist.74"""7576@staticmethod77def _implied_dirs(names):78parents = itertools.chain.from_iterable(map(_parents, names))79as_dirs = (p + posixpath.sep for p in parents)80return _dedupe(_difference(as_dirs, names))8182def namelist(self):83names = super(CompleteDirs, self).namelist()84return names + list(self._implied_dirs(names))8586def _name_set(self):87return set(self.namelist())8889def resolve_dir(self, name):90"""91If the name represents a directory, return that name92as a directory (with the trailing slash).93"""94names = self._name_set()95dirname = name + '/'96dir_match = name not in names and dirname in names97return dirname if dir_match else name9899@classmethod100def make(cls, source):101"""102Given a source (filename or zipfile), return an103appropriate CompleteDirs subclass.104"""105if isinstance(source, CompleteDirs):106return source107108if not isinstance(source, zipfile.ZipFile):109return cls(_pathlib_compat(source))110111# Only allow for FastLookup when supplied zipfile is read-only112if 'r' not in source.mode:113cls = CompleteDirs114115source.__class__ = cls116return source117118119class FastLookup(CompleteDirs):120"""121ZipFile subclass to ensure implicit122dirs exist and are resolved rapidly.123"""124125def namelist(self):126with contextlib.suppress(AttributeError):127return self.__names128self.__names = super(FastLookup, self).namelist()129return self.__names130131def _name_set(self):132with contextlib.suppress(AttributeError):133return self.__lookup134self.__lookup = super(FastLookup, self)._name_set()135return self.__lookup136137138def _pathlib_compat(path):139"""140For path-like objects, convert to a filename for compatibility141on Python 3.6.1 and earlier.142"""143try:144return path.__fspath__()145except AttributeError:146return str(path)147148149class Path:150"""151A pathlib-compatible interface for zip files.152153Consider a zip file with this structure::154155.156├── a.txt157└── b158├── c.txt159└── d160└── e.txt161162>>> data = io.BytesIO()163>>> zf = zipfile.ZipFile(data, 'w')164>>> zf.writestr('a.txt', 'content of a')165>>> zf.writestr('b/c.txt', 'content of c')166>>> zf.writestr('b/d/e.txt', 'content of e')167>>> zf.filename = 'mem/abcde.zip'168169Path accepts the zipfile object itself or a filename170171>>> root = Path(zf)172173From there, several path operations are available.174175Directory iteration (including the zip file itself):176177>>> a, b = root.iterdir()178>>> a179Path('mem/abcde.zip', 'a.txt')180>>> b181Path('mem/abcde.zip', 'b/')182183name property:184185>>> b.name186'b'187188join with divide operator:189190>>> c = b / 'c.txt'191>>> c192Path('mem/abcde.zip', 'b/c.txt')193>>> c.name194'c.txt'195196Read text:197198>>> c.read_text()199'content of c'200201existence:202203>>> c.exists()204True205>>> (b / 'missing.txt').exists()206False207208Coercion to string:209210>>> import os211>>> str(c).replace(os.sep, posixpath.sep)212'mem/abcde.zip/b/c.txt'213214At the root, ``name``, ``filename``, and ``parent``215resolve to the zipfile. Note these attributes are not216valid and will raise a ``ValueError`` if the zipfile217has no filename.218219>>> root.name220'abcde.zip'221>>> str(root.filename).replace(os.sep, posixpath.sep)222'mem/abcde.zip'223>>> str(root.parent)224'mem'225"""226227__repr = "{self.__class__.__name__}({self.root.filename!r}, {self.at!r})"228229def __init__(self, root, at=""):230"""231Construct a Path from a ZipFile or filename.232233Note: When the source is an existing ZipFile object,234its type (__class__) will be mutated to a235specialized type. If the caller wishes to retain the236original type, the caller should either create a237separate ZipFile object or pass a filename.238"""239self.root = FastLookup.make(root)240self.at = at241242def open(self, mode='r', *args, pwd=None, **kwargs):243"""244Open this entry as text or binary following the semantics245of ``pathlib.Path.open()`` by passing arguments through246to io.TextIOWrapper().247"""248if self.is_dir():249raise IsADirectoryError(self)250zip_mode = mode[0]251if not self.exists() and zip_mode == 'r':252raise FileNotFoundError(self)253stream = self.root.open(self.at, zip_mode, pwd=pwd)254if 'b' in mode:255if args or kwargs:256raise ValueError("encoding args invalid for binary operation")257return stream258return io.TextIOWrapper(stream, *args, **kwargs)259260@property261def name(self):262return pathlib.Path(self.at).name or self.filename.name263264@property265def suffix(self):266return pathlib.Path(self.at).suffix or self.filename.suffix267268@property269def suffixes(self):270return pathlib.Path(self.at).suffixes or self.filename.suffixes271272@property273def stem(self):274return pathlib.Path(self.at).stem or self.filename.stem275276@property277def filename(self):278return pathlib.Path(self.root.filename).joinpath(self.at)279280def read_text(self, *args, **kwargs):281with self.open('r', *args, **kwargs) as strm:282return strm.read()283284def read_bytes(self):285with self.open('rb') as strm:286return strm.read()287288def _is_child(self, path):289return posixpath.dirname(path.at.rstrip("/")) == self.at.rstrip("/")290291def _next(self, at):292return self.__class__(self.root, at)293294def is_dir(self):295return not self.at or self.at.endswith("/")296297def is_file(self):298return self.exists() and not self.is_dir()299300def exists(self):301return self.at in self.root._name_set()302303def iterdir(self):304if not self.is_dir():305raise ValueError("Can't listdir a file")306subs = map(self._next, self.root.namelist())307return filter(self._is_child, subs)308309def __str__(self):310return posixpath.join(self.root.filename, self.at)311312def __repr__(self):313return self.__repr.format(self=self)314315def joinpath(self, *other):316next = posixpath.join(self.at, *map(_pathlib_compat, other))317return self._next(self.root.resolve_dir(next))318319__truediv__ = joinpath320321@property322def parent(self):323if not self.at:324return self.filename.parent325parent_at = posixpath.dirname(self.at.rstrip('/'))326if parent_at:327parent_at += '/'328return self._next(parent_at)329330331