base.py 24 KB

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