base.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546
  1. import csv
  2. import email.message
  3. import json
  4. import logging
  5. import pathlib
  6. import re
  7. import zipfile
  8. from typing import (
  9. IO,
  10. TYPE_CHECKING,
  11. Collection,
  12. Container,
  13. Iterable,
  14. Iterator,
  15. List,
  16. Optional,
  17. Tuple,
  18. Union,
  19. )
  20. from pip._vendor.packaging.requirements import Requirement
  21. from pip._vendor.packaging.specifiers import InvalidSpecifier, SpecifierSet
  22. from pip._vendor.packaging.utils import NormalizedName
  23. from pip._vendor.packaging.version import LegacyVersion, Version
  24. from pip._internal.exceptions import NoneMetadataError
  25. from pip._internal.locations import site_packages, user_site
  26. from pip._internal.models.direct_url import (
  27. DIRECT_URL_METADATA_NAME,
  28. DirectUrl,
  29. DirectUrlValidationError,
  30. )
  31. from pip._internal.utils.compat import stdlib_pkgs # TODO: Move definition here.
  32. from pip._internal.utils.egg_link import (
  33. egg_link_path_from_location,
  34. egg_link_path_from_sys_path,
  35. )
  36. from pip._internal.utils.misc import is_local, normalize_path
  37. from pip._internal.utils.urls import url_to_path
  38. if TYPE_CHECKING:
  39. from typing import Protocol
  40. else:
  41. Protocol = object
  42. DistributionVersion = Union[LegacyVersion, Version]
  43. InfoPath = Union[str, pathlib.PurePosixPath]
  44. logger = logging.getLogger(__name__)
  45. class BaseEntryPoint(Protocol):
  46. @property
  47. def name(self) -> str:
  48. raise NotImplementedError()
  49. @property
  50. def value(self) -> str:
  51. raise NotImplementedError()
  52. @property
  53. def group(self) -> str:
  54. raise NotImplementedError()
  55. def _convert_installed_files_path(
  56. entry: Tuple[str, ...],
  57. info: Tuple[str, ...],
  58. ) -> str:
  59. """Convert a legacy installed-files.txt path into modern RECORD path.
  60. The legacy format stores paths relative to the info directory, while the
  61. modern format stores paths relative to the package root, e.g. the
  62. site-packages directory.
  63. :param entry: Path parts of the installed-files.txt entry.
  64. :param info: Path parts of the egg-info directory relative to package root.
  65. :returns: The converted entry.
  66. For best compatibility with symlinks, this does not use ``abspath()`` or
  67. ``Path.resolve()``, but tries to work with path parts:
  68. 1. While ``entry`` starts with ``..``, remove the equal amounts of parts
  69. from ``info``; if ``info`` is empty, start appending ``..`` instead.
  70. 2. Join the two directly.
  71. """
  72. while entry and entry[0] == "..":
  73. if not info or info[-1] == "..":
  74. info += ("..",)
  75. else:
  76. info = info[:-1]
  77. entry = entry[1:]
  78. return str(pathlib.Path(*info, *entry))
  79. class BaseDistribution(Protocol):
  80. def __repr__(self) -> str:
  81. return f"{self.raw_name} {self.version} ({self.location})"
  82. def __str__(self) -> str:
  83. return f"{self.raw_name} {self.version}"
  84. @property
  85. def location(self) -> Optional[str]:
  86. """Where the distribution is loaded from.
  87. A string value is not necessarily a filesystem path, since distributions
  88. can be loaded from other sources, e.g. arbitrary zip archives. ``None``
  89. means the distribution is created in-memory.
  90. Do not canonicalize this value with e.g. ``pathlib.Path.resolve()``. If
  91. this is a symbolic link, we want to preserve the relative path between
  92. it and files in the distribution.
  93. """
  94. raise NotImplementedError()
  95. @property
  96. def editable_project_location(self) -> Optional[str]:
  97. """The project location for editable distributions.
  98. This is the directory where pyproject.toml or setup.py is located.
  99. None if the distribution is not installed in editable mode.
  100. """
  101. # TODO: this property is relatively costly to compute, memoize it ?
  102. direct_url = self.direct_url
  103. if direct_url:
  104. if direct_url.is_local_editable():
  105. return url_to_path(direct_url.url)
  106. else:
  107. # Search for an .egg-link file by walking sys.path, as it was
  108. # done before by dist_is_editable().
  109. egg_link_path = egg_link_path_from_sys_path(self.raw_name)
  110. if egg_link_path:
  111. # TODO: get project location from second line of egg_link file
  112. # (https://github.com/pypa/pip/issues/10243)
  113. return self.location
  114. return None
  115. @property
  116. def installed_location(self) -> Optional[str]:
  117. """The distribution's "installed" location.
  118. This should generally be a ``site-packages`` directory. This is
  119. usually ``dist.location``, except for legacy develop-installed packages,
  120. where ``dist.location`` is the source code location, and this is where
  121. the ``.egg-link`` file is.
  122. The returned location is normalized (in particular, with symlinks removed).
  123. """
  124. egg_link = egg_link_path_from_location(self.raw_name)
  125. if egg_link:
  126. location = egg_link
  127. elif self.location:
  128. location = self.location
  129. else:
  130. return None
  131. return normalize_path(location)
  132. @property
  133. def info_location(self) -> Optional[str]:
  134. """Location of the .[egg|dist]-info directory or file.
  135. Similarly to ``location``, a string value is not necessarily a
  136. filesystem path. ``None`` means the distribution is created in-memory.
  137. For a modern .dist-info installation on disk, this should be something
  138. like ``{location}/{raw_name}-{version}.dist-info``.
  139. Do not canonicalize this value with e.g. ``pathlib.Path.resolve()``. If
  140. this is a symbolic link, we want to preserve the relative path between
  141. it and other files in the distribution.
  142. """
  143. raise NotImplementedError()
  144. @property
  145. def installed_by_distutils(self) -> bool:
  146. """Whether this distribution is installed with legacy distutils format.
  147. A distribution installed with "raw" distutils not patched by setuptools
  148. uses one single file at ``info_location`` to store metadata. We need to
  149. treat this specially on uninstallation.
  150. """
  151. info_location = self.info_location
  152. if not info_location:
  153. return False
  154. return pathlib.Path(info_location).is_file()
  155. @property
  156. def installed_as_egg(self) -> bool:
  157. """Whether this distribution is installed as an egg.
  158. This usually indicates the distribution was installed by (older versions
  159. of) easy_install.
  160. """
  161. location = self.location
  162. if not location:
  163. return False
  164. return location.endswith(".egg")
  165. @property
  166. def installed_with_setuptools_egg_info(self) -> bool:
  167. """Whether this distribution is installed with the ``.egg-info`` format.
  168. This usually indicates the distribution was installed with setuptools
  169. with an old pip version or with ``single-version-externally-managed``.
  170. Note that this ensure the metadata store is a directory. distutils can
  171. also installs an ``.egg-info``, but as a file, not a directory. This
  172. property is *False* for that case. Also see ``installed_by_distutils``.
  173. """
  174. info_location = self.info_location
  175. if not info_location:
  176. return False
  177. if not info_location.endswith(".egg-info"):
  178. return False
  179. return pathlib.Path(info_location).is_dir()
  180. @property
  181. def installed_with_dist_info(self) -> bool:
  182. """Whether this distribution is installed with the "modern format".
  183. This indicates a "modern" installation, e.g. storing metadata in the
  184. ``.dist-info`` directory. This applies to installations made by
  185. setuptools (but through pip, not directly), or anything using the
  186. standardized build backend interface (PEP 517).
  187. """
  188. info_location = self.info_location
  189. if not info_location:
  190. return False
  191. if not info_location.endswith(".dist-info"):
  192. return False
  193. return pathlib.Path(info_location).is_dir()
  194. @property
  195. def canonical_name(self) -> NormalizedName:
  196. raise NotImplementedError()
  197. @property
  198. def version(self) -> DistributionVersion:
  199. raise NotImplementedError()
  200. @property
  201. def setuptools_filename(self) -> str:
  202. """Convert a project name to its setuptools-compatible filename.
  203. This is a copy of ``pkg_resources.to_filename()`` for compatibility.
  204. """
  205. return self.raw_name.replace("-", "_")
  206. @property
  207. def direct_url(self) -> Optional[DirectUrl]:
  208. """Obtain a DirectUrl from this distribution.
  209. Returns None if the distribution has no `direct_url.json` metadata,
  210. or if `direct_url.json` is invalid.
  211. """
  212. try:
  213. content = self.read_text(DIRECT_URL_METADATA_NAME)
  214. except FileNotFoundError:
  215. return None
  216. try:
  217. return DirectUrl.from_json(content)
  218. except (
  219. UnicodeDecodeError,
  220. json.JSONDecodeError,
  221. DirectUrlValidationError,
  222. ) as e:
  223. logger.warning(
  224. "Error parsing %s for %s: %s",
  225. DIRECT_URL_METADATA_NAME,
  226. self.canonical_name,
  227. e,
  228. )
  229. return None
  230. @property
  231. def installer(self) -> str:
  232. try:
  233. installer_text = self.read_text("INSTALLER")
  234. except (OSError, ValueError, NoneMetadataError):
  235. return "" # Fail silently if the installer file cannot be read.
  236. for line in installer_text.splitlines():
  237. cleaned_line = line.strip()
  238. if cleaned_line:
  239. return cleaned_line
  240. return ""
  241. @property
  242. def editable(self) -> bool:
  243. return bool(self.editable_project_location)
  244. @property
  245. def local(self) -> bool:
  246. """If distribution is installed in the current virtual environment.
  247. Always True if we're not in a virtualenv.
  248. """
  249. if self.installed_location is None:
  250. return False
  251. return is_local(self.installed_location)
  252. @property
  253. def in_usersite(self) -> bool:
  254. if self.installed_location is None or user_site is None:
  255. return False
  256. return self.installed_location.startswith(normalize_path(user_site))
  257. @property
  258. def in_site_packages(self) -> bool:
  259. if self.installed_location is None or site_packages is None:
  260. return False
  261. return self.installed_location.startswith(normalize_path(site_packages))
  262. def is_file(self, path: InfoPath) -> bool:
  263. """Check whether an entry in the info directory is a file."""
  264. raise NotImplementedError()
  265. def iterdir(self, path: InfoPath) -> Iterator[pathlib.PurePosixPath]:
  266. """Iterate through a directory in the info directory.
  267. Each item yielded would be a path relative to the info directory.
  268. :raise FileNotFoundError: If ``name`` does not exist in the directory.
  269. :raise NotADirectoryError: If ``name`` does not point to a directory.
  270. """
  271. raise NotImplementedError()
  272. def read_text(self, path: InfoPath) -> str:
  273. """Read a file in the info directory.
  274. :raise FileNotFoundError: If ``name`` does not exist in the directory.
  275. :raise NoneMetadataError: If ``name`` exists in the info directory, but
  276. cannot be read.
  277. """
  278. raise NotImplementedError()
  279. def iter_entry_points(self) -> Iterable[BaseEntryPoint]:
  280. raise NotImplementedError()
  281. @property
  282. def metadata(self) -> email.message.Message:
  283. """Metadata of distribution parsed from e.g. METADATA or PKG-INFO.
  284. This should return an empty message if the metadata file is unavailable.
  285. :raises NoneMetadataError: If the metadata file is available, but does
  286. not contain valid metadata.
  287. """
  288. raise NotImplementedError()
  289. @property
  290. def metadata_version(self) -> Optional[str]:
  291. """Value of "Metadata-Version:" in distribution metadata, if available."""
  292. return self.metadata.get("Metadata-Version")
  293. @property
  294. def raw_name(self) -> str:
  295. """Value of "Name:" in distribution metadata."""
  296. # The metadata should NEVER be missing the Name: key, but if it somehow
  297. # does, fall back to the known canonical name.
  298. return self.metadata.get("Name", self.canonical_name)
  299. @property
  300. def requires_python(self) -> SpecifierSet:
  301. """Value of "Requires-Python:" in distribution metadata.
  302. If the key does not exist or contains an invalid value, an empty
  303. SpecifierSet should be returned.
  304. """
  305. value = self.metadata.get("Requires-Python")
  306. if value is None:
  307. return SpecifierSet()
  308. try:
  309. # Convert to str to satisfy the type checker; this can be a Header object.
  310. spec = SpecifierSet(str(value))
  311. except InvalidSpecifier as e:
  312. message = "Package %r has an invalid Requires-Python: %s"
  313. logger.warning(message, self.raw_name, e)
  314. return SpecifierSet()
  315. return spec
  316. def iter_dependencies(self, extras: Collection[str] = ()) -> Iterable[Requirement]:
  317. """Dependencies of this distribution.
  318. For modern .dist-info distributions, this is the collection of
  319. "Requires-Dist:" entries in distribution metadata.
  320. """
  321. raise NotImplementedError()
  322. def iter_provided_extras(self) -> Iterable[str]:
  323. """Extras provided by this distribution.
  324. For modern .dist-info distributions, this is the collection of
  325. "Provides-Extra:" entries in distribution metadata.
  326. """
  327. raise NotImplementedError()
  328. def _iter_declared_entries_from_record(self) -> Optional[Iterator[str]]:
  329. try:
  330. text = self.read_text("RECORD")
  331. except FileNotFoundError:
  332. return None
  333. # This extra Path-str cast normalizes entries.
  334. return (str(pathlib.Path(row[0])) for row in csv.reader(text.splitlines()))
  335. def _iter_declared_entries_from_legacy(self) -> Optional[Iterator[str]]:
  336. try:
  337. text = self.read_text("installed-files.txt")
  338. except FileNotFoundError:
  339. return None
  340. paths = (p for p in text.splitlines(keepends=False) if p)
  341. root = self.location
  342. info = self.info_location
  343. if root is None or info is None:
  344. return paths
  345. try:
  346. info_rel = pathlib.Path(info).relative_to(root)
  347. except ValueError: # info is not relative to root.
  348. return paths
  349. if not info_rel.parts: # info *is* root.
  350. return paths
  351. return (
  352. _convert_installed_files_path(pathlib.Path(p).parts, info_rel.parts)
  353. for p in paths
  354. )
  355. def iter_declared_entries(self) -> Optional[Iterator[str]]:
  356. """Iterate through file entires declared in this distribution.
  357. For modern .dist-info distributions, this is the files listed in the
  358. ``RECORD`` metadata file. For legacy setuptools distributions, this
  359. comes from ``installed-files.txt``, with entries normalized to be
  360. compatible with the format used by ``RECORD``.
  361. :return: An iterator for listed entries, or None if the distribution
  362. contains neither ``RECORD`` nor ``installed-files.txt``.
  363. """
  364. return (
  365. self._iter_declared_entries_from_record()
  366. or self._iter_declared_entries_from_legacy()
  367. )
  368. class BaseEnvironment:
  369. """An environment containing distributions to introspect."""
  370. @classmethod
  371. def default(cls) -> "BaseEnvironment":
  372. raise NotImplementedError()
  373. @classmethod
  374. def from_paths(cls, paths: Optional[List[str]]) -> "BaseEnvironment":
  375. raise NotImplementedError()
  376. def get_distribution(self, name: str) -> Optional["BaseDistribution"]:
  377. """Given a requirement name, return the installed distributions.
  378. The name may not be normalized. The implementation must canonicalize
  379. it for lookup.
  380. """
  381. raise NotImplementedError()
  382. def _iter_distributions(self) -> Iterator["BaseDistribution"]:
  383. """Iterate through installed distributions.
  384. This function should be implemented by subclass, but never called
  385. directly. Use the public ``iter_distribution()`` instead, which
  386. implements additional logic to make sure the distributions are valid.
  387. """
  388. raise NotImplementedError()
  389. def iter_distributions(self) -> Iterator["BaseDistribution"]:
  390. """Iterate through installed distributions."""
  391. for dist in self._iter_distributions():
  392. # Make sure the distribution actually comes from a valid Python
  393. # packaging distribution. Pip's AdjacentTempDirectory leaves folders
  394. # e.g. ``~atplotlib.dist-info`` if cleanup was interrupted. The
  395. # valid project name pattern is taken from PEP 508.
  396. project_name_valid = re.match(
  397. r"^([A-Z0-9]|[A-Z0-9][A-Z0-9._-]*[A-Z0-9])$",
  398. dist.canonical_name,
  399. flags=re.IGNORECASE,
  400. )
  401. if not project_name_valid:
  402. logger.warning(
  403. "Ignoring invalid distribution %s (%s)",
  404. dist.canonical_name,
  405. dist.location,
  406. )
  407. continue
  408. yield dist
  409. def iter_installed_distributions(
  410. self,
  411. local_only: bool = True,
  412. skip: Container[str] = stdlib_pkgs,
  413. include_editables: bool = True,
  414. editables_only: bool = False,
  415. user_only: bool = False,
  416. ) -> Iterator[BaseDistribution]:
  417. """Return a list of installed distributions.
  418. :param local_only: If True (default), only return installations
  419. local to the current virtualenv, if in a virtualenv.
  420. :param skip: An iterable of canonicalized project names to ignore;
  421. defaults to ``stdlib_pkgs``.
  422. :param include_editables: If False, don't report editables.
  423. :param editables_only: If True, only report editables.
  424. :param user_only: If True, only report installations in the user
  425. site directory.
  426. """
  427. it = self.iter_distributions()
  428. if local_only:
  429. it = (d for d in it if d.local)
  430. if not include_editables:
  431. it = (d for d in it if not d.editable)
  432. if editables_only:
  433. it = (d for d in it if d.editable)
  434. if user_only:
  435. it = (d for d in it if d.in_usersite)
  436. return (d for d in it if d.canonical_name not in skip)
  437. class Wheel(Protocol):
  438. location: str
  439. def as_zipfile(self) -> zipfile.ZipFile:
  440. raise NotImplementedError()
  441. class FilesystemWheel(Wheel):
  442. def __init__(self, location: str) -> None:
  443. self.location = location
  444. def as_zipfile(self) -> zipfile.ZipFile:
  445. return zipfile.ZipFile(self.location, allowZip64=True)
  446. class MemoryWheel(Wheel):
  447. def __init__(self, location: str, stream: IO[bytes]) -> None:
  448. self.location = location
  449. self.stream = stream
  450. def as_zipfile(self) -> zipfile.ZipFile:
  451. return zipfile.ZipFile(self.stream, allowZip64=True)