base.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688
  1. import csv
  2. import email.message
  3. import functools
  4. import json
  5. import logging
  6. import pathlib
  7. import re
  8. import zipfile
  9. from typing import (
  10. IO,
  11. TYPE_CHECKING,
  12. Any,
  13. Collection,
  14. Container,
  15. Dict,
  16. Iterable,
  17. Iterator,
  18. List,
  19. NamedTuple,
  20. Optional,
  21. Tuple,
  22. Union,
  23. )
  24. from pip._vendor.packaging.requirements import Requirement
  25. from pip._vendor.packaging.specifiers import InvalidSpecifier, SpecifierSet
  26. from pip._vendor.packaging.utils import NormalizedName
  27. from pip._vendor.packaging.version import LegacyVersion, Version
  28. from pip._internal.exceptions import NoneMetadataError
  29. from pip._internal.locations import site_packages, user_site
  30. from pip._internal.models.direct_url import (
  31. DIRECT_URL_METADATA_NAME,
  32. DirectUrl,
  33. DirectUrlValidationError,
  34. )
  35. from pip._internal.utils.compat import stdlib_pkgs # TODO: Move definition here.
  36. from pip._internal.utils.egg_link import egg_link_path_from_sys_path
  37. from pip._internal.utils.misc import is_local, normalize_path
  38. from pip._internal.utils.packaging import safe_extra
  39. from pip._internal.utils.urls import url_to_path
  40. from ._json import msg_to_json
  41. if TYPE_CHECKING:
  42. from typing import Protocol
  43. else:
  44. Protocol = object
  45. DistributionVersion = Union[LegacyVersion, Version]
  46. InfoPath = Union[str, pathlib.PurePath]
  47. logger = logging.getLogger(__name__)
  48. class BaseEntryPoint(Protocol):
  49. @property
  50. def name(self) -> str:
  51. raise NotImplementedError()
  52. @property
  53. def value(self) -> str:
  54. raise NotImplementedError()
  55. @property
  56. def group(self) -> str:
  57. raise NotImplementedError()
  58. def _convert_installed_files_path(
  59. entry: Tuple[str, ...],
  60. info: Tuple[str, ...],
  61. ) -> str:
  62. """Convert a legacy installed-files.txt path into modern RECORD path.
  63. The legacy format stores paths relative to the info directory, while the
  64. modern format stores paths relative to the package root, e.g. the
  65. site-packages directory.
  66. :param entry: Path parts of the installed-files.txt entry.
  67. :param info: Path parts of the egg-info directory relative to package root.
  68. :returns: The converted entry.
  69. For best compatibility with symlinks, this does not use ``abspath()`` or
  70. ``Path.resolve()``, but tries to work with path parts:
  71. 1. While ``entry`` starts with ``..``, remove the equal amounts of parts
  72. from ``info``; if ``info`` is empty, start appending ``..`` instead.
  73. 2. Join the two directly.
  74. """
  75. while entry and entry[0] == "..":
  76. if not info or info[-1] == "..":
  77. info += ("..",)
  78. else:
  79. info = info[:-1]
  80. entry = entry[1:]
  81. return str(pathlib.Path(*info, *entry))
  82. class RequiresEntry(NamedTuple):
  83. requirement: str
  84. extra: str
  85. marker: str
  86. class BaseDistribution(Protocol):
  87. @classmethod
  88. def from_directory(cls, directory: str) -> "BaseDistribution":
  89. """Load the distribution from a metadata directory.
  90. :param directory: Path to a metadata directory, e.g. ``.dist-info``.
  91. """
  92. raise NotImplementedError()
  93. @classmethod
  94. def from_metadata_file_contents(
  95. cls,
  96. metadata_contents: bytes,
  97. filename: str,
  98. project_name: str,
  99. ) -> "BaseDistribution":
  100. """Load the distribution from the contents of a METADATA file.
  101. This is used to implement PEP 658 by generating a "shallow" dist object that can
  102. be used for resolution without downloading or building the actual dist yet.
  103. :param metadata_contents: The contents of a METADATA file.
  104. :param filename: File name for the dist with this metadata.
  105. :param project_name: Name of the project this dist represents.
  106. """
  107. raise NotImplementedError()
  108. @classmethod
  109. def from_wheel(cls, wheel: "Wheel", name: str) -> "BaseDistribution":
  110. """Load the distribution from a given wheel.
  111. :param wheel: A concrete wheel definition.
  112. :param name: File name of the wheel.
  113. :raises InvalidWheel: Whenever loading of the wheel causes a
  114. :py:exc:`zipfile.BadZipFile` exception to be thrown.
  115. :raises UnsupportedWheel: If the wheel is a valid zip, but malformed
  116. internally.
  117. """
  118. raise NotImplementedError()
  119. def __repr__(self) -> str:
  120. return f"{self.raw_name} {self.version} ({self.location})"
  121. def __str__(self) -> str:
  122. return f"{self.raw_name} {self.version}"
  123. @property
  124. def location(self) -> Optional[str]:
  125. """Where the distribution is loaded from.
  126. A string value is not necessarily a filesystem path, since distributions
  127. can be loaded from other sources, e.g. arbitrary zip archives. ``None``
  128. means the distribution is created in-memory.
  129. Do not canonicalize this value with e.g. ``pathlib.Path.resolve()``. If
  130. this is a symbolic link, we want to preserve the relative path between
  131. it and files in the distribution.
  132. """
  133. raise NotImplementedError()
  134. @property
  135. def editable_project_location(self) -> Optional[str]:
  136. """The project location for editable distributions.
  137. This is the directory where pyproject.toml or setup.py is located.
  138. None if the distribution is not installed in editable mode.
  139. """
  140. # TODO: this property is relatively costly to compute, memoize it ?
  141. direct_url = self.direct_url
  142. if direct_url:
  143. if direct_url.is_local_editable():
  144. return url_to_path(direct_url.url)
  145. else:
  146. # Search for an .egg-link file by walking sys.path, as it was
  147. # done before by dist_is_editable().
  148. egg_link_path = egg_link_path_from_sys_path(self.raw_name)
  149. if egg_link_path:
  150. # TODO: get project location from second line of egg_link file
  151. # (https://github.com/pypa/pip/issues/10243)
  152. return self.location
  153. return None
  154. @property
  155. def installed_location(self) -> Optional[str]:
  156. """The distribution's "installed" location.
  157. This should generally be a ``site-packages`` directory. This is
  158. usually ``dist.location``, except for legacy develop-installed packages,
  159. where ``dist.location`` is the source code location, and this is where
  160. the ``.egg-link`` file is.
  161. The returned location is normalized (in particular, with symlinks removed).
  162. """
  163. raise NotImplementedError()
  164. @property
  165. def info_location(self) -> Optional[str]:
  166. """Location of the .[egg|dist]-info directory or file.
  167. Similarly to ``location``, a string value is not necessarily a
  168. filesystem path. ``None`` means the distribution is created in-memory.
  169. For a modern .dist-info installation on disk, this should be something
  170. like ``{location}/{raw_name}-{version}.dist-info``.
  171. Do not canonicalize this value with e.g. ``pathlib.Path.resolve()``. If
  172. this is a symbolic link, we want to preserve the relative path between
  173. it and other files in the distribution.
  174. """
  175. raise NotImplementedError()
  176. @property
  177. def installed_by_distutils(self) -> bool:
  178. """Whether this distribution is installed with legacy distutils format.
  179. A distribution installed with "raw" distutils not patched by setuptools
  180. uses one single file at ``info_location`` to store metadata. We need to
  181. treat this specially on uninstallation.
  182. """
  183. info_location = self.info_location
  184. if not info_location:
  185. return False
  186. return pathlib.Path(info_location).is_file()
  187. @property
  188. def installed_as_egg(self) -> bool:
  189. """Whether this distribution is installed as an egg.
  190. This usually indicates the distribution was installed by (older versions
  191. of) easy_install.
  192. """
  193. location = self.location
  194. if not location:
  195. return False
  196. return location.endswith(".egg")
  197. @property
  198. def installed_with_setuptools_egg_info(self) -> bool:
  199. """Whether this distribution is installed with the ``.egg-info`` format.
  200. This usually indicates the distribution was installed with setuptools
  201. with an old pip version or with ``single-version-externally-managed``.
  202. Note that this ensure the metadata store is a directory. distutils can
  203. also installs an ``.egg-info``, but as a file, not a directory. This
  204. property is *False* for that case. Also see ``installed_by_distutils``.
  205. """
  206. info_location = self.info_location
  207. if not info_location:
  208. return False
  209. if not info_location.endswith(".egg-info"):
  210. return False
  211. return pathlib.Path(info_location).is_dir()
  212. @property
  213. def installed_with_dist_info(self) -> bool:
  214. """Whether this distribution is installed with the "modern format".
  215. This indicates a "modern" installation, e.g. storing metadata in the
  216. ``.dist-info`` directory. This applies to installations made by
  217. setuptools (but through pip, not directly), or anything using the
  218. standardized build backend interface (PEP 517).
  219. """
  220. info_location = self.info_location
  221. if not info_location:
  222. return False
  223. if not info_location.endswith(".dist-info"):
  224. return False
  225. return pathlib.Path(info_location).is_dir()
  226. @property
  227. def canonical_name(self) -> NormalizedName:
  228. raise NotImplementedError()
  229. @property
  230. def version(self) -> DistributionVersion:
  231. raise NotImplementedError()
  232. @property
  233. def setuptools_filename(self) -> str:
  234. """Convert a project name to its setuptools-compatible filename.
  235. This is a copy of ``pkg_resources.to_filename()`` for compatibility.
  236. """
  237. return self.raw_name.replace("-", "_")
  238. @property
  239. def direct_url(self) -> Optional[DirectUrl]:
  240. """Obtain a DirectUrl from this distribution.
  241. Returns None if the distribution has no `direct_url.json` metadata,
  242. or if `direct_url.json` is invalid.
  243. """
  244. try:
  245. content = self.read_text(DIRECT_URL_METADATA_NAME)
  246. except FileNotFoundError:
  247. return None
  248. try:
  249. return DirectUrl.from_json(content)
  250. except (
  251. UnicodeDecodeError,
  252. json.JSONDecodeError,
  253. DirectUrlValidationError,
  254. ) as e:
  255. logger.warning(
  256. "Error parsing %s for %s: %s",
  257. DIRECT_URL_METADATA_NAME,
  258. self.canonical_name,
  259. e,
  260. )
  261. return None
  262. @property
  263. def installer(self) -> str:
  264. try:
  265. installer_text = self.read_text("INSTALLER")
  266. except (OSError, ValueError, NoneMetadataError):
  267. return "" # Fail silently if the installer file cannot be read.
  268. for line in installer_text.splitlines():
  269. cleaned_line = line.strip()
  270. if cleaned_line:
  271. return cleaned_line
  272. return ""
  273. @property
  274. def requested(self) -> bool:
  275. return self.is_file("REQUESTED")
  276. @property
  277. def editable(self) -> bool:
  278. return bool(self.editable_project_location)
  279. @property
  280. def local(self) -> bool:
  281. """If distribution is installed in the current virtual environment.
  282. Always True if we're not in a virtualenv.
  283. """
  284. if self.installed_location is None:
  285. return False
  286. return is_local(self.installed_location)
  287. @property
  288. def in_usersite(self) -> bool:
  289. if self.installed_location is None or user_site is None:
  290. return False
  291. return self.installed_location.startswith(normalize_path(user_site))
  292. @property
  293. def in_site_packages(self) -> bool:
  294. if self.installed_location is None or site_packages is None:
  295. return False
  296. return self.installed_location.startswith(normalize_path(site_packages))
  297. def is_file(self, path: InfoPath) -> bool:
  298. """Check whether an entry in the info directory is a file."""
  299. raise NotImplementedError()
  300. def iter_distutils_script_names(self) -> Iterator[str]:
  301. """Find distutils 'scripts' entries metadata.
  302. If 'scripts' is supplied in ``setup.py``, distutils records those in the
  303. installed distribution's ``scripts`` directory, a file for each script.
  304. """
  305. raise NotImplementedError()
  306. def read_text(self, path: InfoPath) -> str:
  307. """Read a file in the info directory.
  308. :raise FileNotFoundError: If ``path`` does not exist in the directory.
  309. :raise NoneMetadataError: If ``path`` exists in the info directory, but
  310. cannot be read.
  311. """
  312. raise NotImplementedError()
  313. def iter_entry_points(self) -> Iterable[BaseEntryPoint]:
  314. raise NotImplementedError()
  315. def _metadata_impl(self) -> email.message.Message:
  316. raise NotImplementedError()
  317. @functools.lru_cache(maxsize=1)
  318. def _metadata_cached(self) -> email.message.Message:
  319. # When we drop python 3.7 support, move this to the metadata property and use
  320. # functools.cached_property instead of lru_cache.
  321. metadata = self._metadata_impl()
  322. self._add_egg_info_requires(metadata)
  323. return metadata
  324. @property
  325. def metadata(self) -> email.message.Message:
  326. """Metadata of distribution parsed from e.g. METADATA or PKG-INFO.
  327. This should return an empty message if the metadata file is unavailable.
  328. :raises NoneMetadataError: If the metadata file is available, but does
  329. not contain valid metadata.
  330. """
  331. return self._metadata_cached()
  332. @property
  333. def metadata_dict(self) -> Dict[str, Any]:
  334. """PEP 566 compliant JSON-serializable representation of METADATA or PKG-INFO.
  335. This should return an empty dict if the metadata file is unavailable.
  336. :raises NoneMetadataError: If the metadata file is available, but does
  337. not contain valid metadata.
  338. """
  339. return msg_to_json(self.metadata)
  340. @property
  341. def metadata_version(self) -> Optional[str]:
  342. """Value of "Metadata-Version:" in distribution metadata, if available."""
  343. return self.metadata.get("Metadata-Version")
  344. @property
  345. def raw_name(self) -> str:
  346. """Value of "Name:" in distribution metadata."""
  347. # The metadata should NEVER be missing the Name: key, but if it somehow
  348. # does, fall back to the known canonical name.
  349. return self.metadata.get("Name", self.canonical_name)
  350. @property
  351. def requires_python(self) -> SpecifierSet:
  352. """Value of "Requires-Python:" in distribution metadata.
  353. If the key does not exist or contains an invalid value, an empty
  354. SpecifierSet should be returned.
  355. """
  356. value = self.metadata.get("Requires-Python")
  357. if value is None:
  358. return SpecifierSet()
  359. try:
  360. # Convert to str to satisfy the type checker; this can be a Header object.
  361. spec = SpecifierSet(str(value))
  362. except InvalidSpecifier as e:
  363. message = "Package %r has an invalid Requires-Python: %s"
  364. logger.warning(message, self.raw_name, e)
  365. return SpecifierSet()
  366. return spec
  367. def iter_dependencies(self, extras: Collection[str] = ()) -> Iterable[Requirement]:
  368. """Dependencies of this distribution.
  369. For modern .dist-info distributions, this is the collection of
  370. "Requires-Dist:" entries in distribution metadata.
  371. """
  372. raise NotImplementedError()
  373. def iter_provided_extras(self) -> Iterable[str]:
  374. """Extras provided by this distribution.
  375. For modern .dist-info distributions, this is the collection of
  376. "Provides-Extra:" entries in distribution metadata.
  377. """
  378. raise NotImplementedError()
  379. def _iter_declared_entries_from_record(self) -> Optional[Iterator[str]]:
  380. try:
  381. text = self.read_text("RECORD")
  382. except FileNotFoundError:
  383. return None
  384. # This extra Path-str cast normalizes entries.
  385. return (str(pathlib.Path(row[0])) for row in csv.reader(text.splitlines()))
  386. def _iter_declared_entries_from_legacy(self) -> Optional[Iterator[str]]:
  387. try:
  388. text = self.read_text("installed-files.txt")
  389. except FileNotFoundError:
  390. return None
  391. paths = (p for p in text.splitlines(keepends=False) if p)
  392. root = self.location
  393. info = self.info_location
  394. if root is None or info is None:
  395. return paths
  396. try:
  397. info_rel = pathlib.Path(info).relative_to(root)
  398. except ValueError: # info is not relative to root.
  399. return paths
  400. if not info_rel.parts: # info *is* root.
  401. return paths
  402. return (
  403. _convert_installed_files_path(pathlib.Path(p).parts, info_rel.parts)
  404. for p in paths
  405. )
  406. def iter_declared_entries(self) -> Optional[Iterator[str]]:
  407. """Iterate through file entries declared in this distribution.
  408. For modern .dist-info distributions, this is the files listed in the
  409. ``RECORD`` metadata file. For legacy setuptools distributions, this
  410. comes from ``installed-files.txt``, with entries normalized to be
  411. compatible with the format used by ``RECORD``.
  412. :return: An iterator for listed entries, or None if the distribution
  413. contains neither ``RECORD`` nor ``installed-files.txt``.
  414. """
  415. return (
  416. self._iter_declared_entries_from_record()
  417. or self._iter_declared_entries_from_legacy()
  418. )
  419. def _iter_requires_txt_entries(self) -> Iterator[RequiresEntry]:
  420. """Parse a ``requires.txt`` in an egg-info directory.
  421. This is an INI-ish format where an egg-info stores dependencies. A
  422. section name describes extra other environment markers, while each entry
  423. is an arbitrary string (not a key-value pair) representing a dependency
  424. as a requirement string (no markers).
  425. There is a construct in ``importlib.metadata`` called ``Sectioned`` that
  426. does mostly the same, but the format is currently considered private.
  427. """
  428. try:
  429. content = self.read_text("requires.txt")
  430. except FileNotFoundError:
  431. return
  432. extra = marker = "" # Section-less entries don't have markers.
  433. for line in content.splitlines():
  434. line = line.strip()
  435. if not line or line.startswith("#"): # Comment; ignored.
  436. continue
  437. if line.startswith("[") and line.endswith("]"): # A section header.
  438. extra, _, marker = line.strip("[]").partition(":")
  439. continue
  440. yield RequiresEntry(requirement=line, extra=extra, marker=marker)
  441. def _iter_egg_info_extras(self) -> Iterable[str]:
  442. """Get extras from the egg-info directory."""
  443. known_extras = {""}
  444. for entry in self._iter_requires_txt_entries():
  445. if entry.extra in known_extras:
  446. continue
  447. known_extras.add(entry.extra)
  448. yield entry.extra
  449. def _iter_egg_info_dependencies(self) -> Iterable[str]:
  450. """Get distribution dependencies from the egg-info directory.
  451. To ease parsing, this converts a legacy dependency entry into a PEP 508
  452. requirement string. Like ``_iter_requires_txt_entries()``, there is code
  453. in ``importlib.metadata`` that does mostly the same, but not do exactly
  454. what we need.
  455. Namely, ``importlib.metadata`` does not normalize the extra name before
  456. putting it into the requirement string, which causes marker comparison
  457. to fail because the dist-info format do normalize. This is consistent in
  458. all currently available PEP 517 backends, although not standardized.
  459. """
  460. for entry in self._iter_requires_txt_entries():
  461. if entry.extra and entry.marker:
  462. marker = f'({entry.marker}) and extra == "{safe_extra(entry.extra)}"'
  463. elif entry.extra:
  464. marker = f'extra == "{safe_extra(entry.extra)}"'
  465. elif entry.marker:
  466. marker = entry.marker
  467. else:
  468. marker = ""
  469. if marker:
  470. yield f"{entry.requirement} ; {marker}"
  471. else:
  472. yield entry.requirement
  473. def _add_egg_info_requires(self, metadata: email.message.Message) -> None:
  474. """Add egg-info requires.txt information to the metadata."""
  475. if not metadata.get_all("Requires-Dist"):
  476. for dep in self._iter_egg_info_dependencies():
  477. metadata["Requires-Dist"] = dep
  478. if not metadata.get_all("Provides-Extra"):
  479. for extra in self._iter_egg_info_extras():
  480. metadata["Provides-Extra"] = extra
  481. class BaseEnvironment:
  482. """An environment containing distributions to introspect."""
  483. @classmethod
  484. def default(cls) -> "BaseEnvironment":
  485. raise NotImplementedError()
  486. @classmethod
  487. def from_paths(cls, paths: Optional[List[str]]) -> "BaseEnvironment":
  488. raise NotImplementedError()
  489. def get_distribution(self, name: str) -> Optional["BaseDistribution"]:
  490. """Given a requirement name, return the installed distributions.
  491. The name may not be normalized. The implementation must canonicalize
  492. it for lookup.
  493. """
  494. raise NotImplementedError()
  495. def _iter_distributions(self) -> Iterator["BaseDistribution"]:
  496. """Iterate through installed distributions.
  497. This function should be implemented by subclass, but never called
  498. directly. Use the public ``iter_distribution()`` instead, which
  499. implements additional logic to make sure the distributions are valid.
  500. """
  501. raise NotImplementedError()
  502. def iter_all_distributions(self) -> Iterator[BaseDistribution]:
  503. """Iterate through all installed distributions without any filtering."""
  504. for dist in self._iter_distributions():
  505. # Make sure the distribution actually comes from a valid Python
  506. # packaging distribution. Pip's AdjacentTempDirectory leaves folders
  507. # e.g. ``~atplotlib.dist-info`` if cleanup was interrupted. The
  508. # valid project name pattern is taken from PEP 508.
  509. project_name_valid = re.match(
  510. r"^([A-Z0-9]|[A-Z0-9][A-Z0-9._-]*[A-Z0-9])$",
  511. dist.canonical_name,
  512. flags=re.IGNORECASE,
  513. )
  514. if not project_name_valid:
  515. logger.warning(
  516. "Ignoring invalid distribution %s (%s)",
  517. dist.canonical_name,
  518. dist.location,
  519. )
  520. continue
  521. yield dist
  522. def iter_installed_distributions(
  523. self,
  524. local_only: bool = True,
  525. skip: Container[str] = stdlib_pkgs,
  526. include_editables: bool = True,
  527. editables_only: bool = False,
  528. user_only: bool = False,
  529. ) -> Iterator[BaseDistribution]:
  530. """Return a list of installed distributions.
  531. This is based on ``iter_all_distributions()`` with additional filtering
  532. options. Note that ``iter_installed_distributions()`` without arguments
  533. is *not* equal to ``iter_all_distributions()``, since some of the
  534. configurations exclude packages by default.
  535. :param local_only: If True (default), only return installations
  536. local to the current virtualenv, if in a virtualenv.
  537. :param skip: An iterable of canonicalized project names to ignore;
  538. defaults to ``stdlib_pkgs``.
  539. :param include_editables: If False, don't report editables.
  540. :param editables_only: If True, only report editables.
  541. :param user_only: If True, only report installations in the user
  542. site directory.
  543. """
  544. it = self.iter_all_distributions()
  545. if local_only:
  546. it = (d for d in it if d.local)
  547. if not include_editables:
  548. it = (d for d in it if not d.editable)
  549. if editables_only:
  550. it = (d for d in it if d.editable)
  551. if user_only:
  552. it = (d for d in it if d.in_usersite)
  553. return (d for d in it if d.canonical_name not in skip)
  554. class Wheel(Protocol):
  555. location: str
  556. def as_zipfile(self) -> zipfile.ZipFile:
  557. raise NotImplementedError()
  558. class FilesystemWheel(Wheel):
  559. def __init__(self, location: str) -> None:
  560. self.location = location
  561. def as_zipfile(self) -> zipfile.ZipFile:
  562. return zipfile.ZipFile(self.location, allowZip64=True)
  563. class MemoryWheel(Wheel):
  564. def __init__(self, location: str, stream: IO[bytes]) -> None:
  565. self.location = location
  566. self.stream = stream
  567. def as_zipfile(self) -> zipfile.ZipFile:
  568. return zipfile.ZipFile(self.stream, allowZip64=True)