candidates.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591
  1. from __future__ import annotations
  2. import logging
  3. import sys
  4. from collections.abc import Iterable
  5. from typing import TYPE_CHECKING, Any, Union, cast
  6. from pip._vendor.packaging.requirements import InvalidRequirement
  7. from pip._vendor.packaging.utils import NormalizedName, canonicalize_name
  8. from pip._vendor.packaging.version import Version
  9. from pip._internal.exceptions import (
  10. FailedToPrepareCandidate,
  11. HashError,
  12. InstallationSubprocessError,
  13. InvalidInstalledPackage,
  14. MetadataInconsistent,
  15. MetadataInvalid,
  16. )
  17. from pip._internal.metadata import BaseDistribution
  18. from pip._internal.models.link import Link, links_equivalent
  19. from pip._internal.models.wheel import Wheel
  20. from pip._internal.req.constructors import (
  21. install_req_from_editable,
  22. install_req_from_line,
  23. )
  24. from pip._internal.req.req_install import InstallRequirement
  25. from pip._internal.utils.direct_url_helpers import direct_url_from_link
  26. from pip._internal.utils.misc import normalize_version_info
  27. from .base import Candidate, Requirement, format_name
  28. if TYPE_CHECKING:
  29. from .factory import Factory
  30. logger = logging.getLogger(__name__)
  31. BaseCandidate = Union[
  32. "AlreadyInstalledCandidate",
  33. "EditableCandidate",
  34. "LinkCandidate",
  35. ]
  36. # Avoid conflicting with the PyPI package "Python".
  37. REQUIRES_PYTHON_IDENTIFIER = cast(NormalizedName, "<Python from Requires-Python>")
  38. def as_base_candidate(candidate: Candidate) -> BaseCandidate | None:
  39. """The runtime version of BaseCandidate."""
  40. base_candidate_classes = (
  41. AlreadyInstalledCandidate,
  42. EditableCandidate,
  43. LinkCandidate,
  44. )
  45. if isinstance(candidate, base_candidate_classes):
  46. return candidate
  47. return None
  48. def make_install_req_from_link(
  49. link: Link, template: InstallRequirement
  50. ) -> InstallRequirement:
  51. assert not template.editable, "template is editable"
  52. if template.req:
  53. line = str(template.req)
  54. else:
  55. line = link.url
  56. ireq = install_req_from_line(
  57. line,
  58. user_supplied=template.user_supplied,
  59. comes_from=template.comes_from,
  60. isolated=template.isolated,
  61. constraint=template.constraint,
  62. hash_options=template.hash_options,
  63. config_settings=template.config_settings,
  64. )
  65. ireq.original_link = template.original_link
  66. ireq.link = link
  67. ireq.extras = template.extras
  68. return ireq
  69. def make_install_req_from_editable(
  70. link: Link, template: InstallRequirement
  71. ) -> InstallRequirement:
  72. assert template.editable, "template not editable"
  73. if template.name:
  74. req_string = f"{template.name} @ {link.url}"
  75. else:
  76. req_string = link.url
  77. ireq = install_req_from_editable(
  78. req_string,
  79. user_supplied=template.user_supplied,
  80. comes_from=template.comes_from,
  81. isolated=template.isolated,
  82. constraint=template.constraint,
  83. permit_editable_wheels=template.permit_editable_wheels,
  84. hash_options=template.hash_options,
  85. config_settings=template.config_settings,
  86. )
  87. ireq.extras = template.extras
  88. return ireq
  89. def _make_install_req_from_dist(
  90. dist: BaseDistribution, template: InstallRequirement
  91. ) -> InstallRequirement:
  92. if template.req:
  93. line = str(template.req)
  94. elif template.link:
  95. line = f"{dist.canonical_name} @ {template.link.url}"
  96. else:
  97. line = f"{dist.canonical_name}=={dist.version}"
  98. ireq = install_req_from_line(
  99. line,
  100. user_supplied=template.user_supplied,
  101. comes_from=template.comes_from,
  102. isolated=template.isolated,
  103. constraint=template.constraint,
  104. hash_options=template.hash_options,
  105. config_settings=template.config_settings,
  106. )
  107. ireq.satisfied_by = dist
  108. return ireq
  109. class _InstallRequirementBackedCandidate(Candidate):
  110. """A candidate backed by an ``InstallRequirement``.
  111. This represents a package request with the target not being already
  112. in the environment, and needs to be fetched and installed. The backing
  113. ``InstallRequirement`` is responsible for most of the leg work; this
  114. class exposes appropriate information to the resolver.
  115. :param link: The link passed to the ``InstallRequirement``. The backing
  116. ``InstallRequirement`` will use this link to fetch the distribution.
  117. :param source_link: The link this candidate "originates" from. This is
  118. different from ``link`` when the link is found in the wheel cache.
  119. ``link`` would point to the wheel cache, while this points to the
  120. found remote link (e.g. from pypi.org).
  121. """
  122. dist: BaseDistribution
  123. is_installed = False
  124. def __init__(
  125. self,
  126. link: Link,
  127. source_link: Link,
  128. ireq: InstallRequirement,
  129. factory: Factory,
  130. name: NormalizedName | None = None,
  131. version: Version | None = None,
  132. ) -> None:
  133. self._link = link
  134. self._source_link = source_link
  135. self._factory = factory
  136. self._ireq = ireq
  137. self._name = name
  138. self._version = version
  139. self.dist = self._prepare()
  140. self._hash: int | None = None
  141. def __str__(self) -> str:
  142. return f"{self.name} {self.version}"
  143. def __repr__(self) -> str:
  144. return f"{self.__class__.__name__}({str(self._link)!r})"
  145. def __hash__(self) -> int:
  146. if self._hash is not None:
  147. return self._hash
  148. self._hash = hash((self.__class__, self._link))
  149. return self._hash
  150. def __eq__(self, other: Any) -> bool:
  151. if isinstance(other, self.__class__):
  152. return links_equivalent(self._link, other._link)
  153. return False
  154. @property
  155. def source_link(self) -> Link | None:
  156. return self._source_link
  157. @property
  158. def project_name(self) -> NormalizedName:
  159. """The normalised name of the project the candidate refers to"""
  160. if self._name is None:
  161. self._name = self.dist.canonical_name
  162. return self._name
  163. @property
  164. def name(self) -> str:
  165. return self.project_name
  166. @property
  167. def version(self) -> Version:
  168. if self._version is None:
  169. self._version = self.dist.version
  170. return self._version
  171. def format_for_error(self) -> str:
  172. return (
  173. f"{self.name} {self.version} "
  174. f"(from {self._link.file_path if self._link.is_file else self._link})"
  175. )
  176. def _prepare_distribution(self) -> BaseDistribution:
  177. raise NotImplementedError("Override in subclass")
  178. def _check_metadata_consistency(self, dist: BaseDistribution) -> None:
  179. """Check for consistency of project name and version of dist."""
  180. if self._name is not None and self._name != dist.canonical_name:
  181. raise MetadataInconsistent(
  182. self._ireq,
  183. "name",
  184. self._name,
  185. dist.canonical_name,
  186. )
  187. if self._version is not None and self._version != dist.version:
  188. raise MetadataInconsistent(
  189. self._ireq,
  190. "version",
  191. str(self._version),
  192. str(dist.version),
  193. )
  194. # check dependencies are valid
  195. # TODO performance: this means we iterate the dependencies at least twice,
  196. # we may want to cache parsed Requires-Dist
  197. try:
  198. list(dist.iter_dependencies(list(dist.iter_provided_extras())))
  199. except InvalidRequirement as e:
  200. raise MetadataInvalid(self._ireq, str(e))
  201. def _prepare(self) -> BaseDistribution:
  202. try:
  203. dist = self._prepare_distribution()
  204. except HashError as e:
  205. # Provide HashError the underlying ireq that caused it. This
  206. # provides context for the resulting error message to show the
  207. # offending line to the user.
  208. e.req = self._ireq
  209. raise
  210. except InstallationSubprocessError as exc:
  211. if isinstance(self._ireq.comes_from, InstallRequirement):
  212. request_chain = self._ireq.comes_from.from_path()
  213. else:
  214. request_chain = self._ireq.comes_from
  215. if request_chain is None:
  216. request_chain = "directly requested"
  217. raise FailedToPrepareCandidate(
  218. package_name=self._ireq.name or str(self._link),
  219. requirement_chain=request_chain,
  220. failed_step=exc.command_description,
  221. )
  222. self._check_metadata_consistency(dist)
  223. return dist
  224. def iter_dependencies(self, with_requires: bool) -> Iterable[Requirement | None]:
  225. # Emit the Requires-Python requirement first to fail fast on
  226. # unsupported candidates and avoid pointless downloads/preparation.
  227. yield self._factory.make_requires_python_requirement(self.dist.requires_python)
  228. requires = self.dist.iter_dependencies() if with_requires else ()
  229. for r in requires:
  230. yield from self._factory.make_requirements_from_spec(str(r), self._ireq)
  231. def get_install_requirement(self) -> InstallRequirement | None:
  232. return self._ireq
  233. class LinkCandidate(_InstallRequirementBackedCandidate):
  234. is_editable = False
  235. def __init__(
  236. self,
  237. link: Link,
  238. template: InstallRequirement,
  239. factory: Factory,
  240. name: NormalizedName | None = None,
  241. version: Version | None = None,
  242. ) -> None:
  243. source_link = link
  244. cache_entry = factory.get_wheel_cache_entry(source_link, name)
  245. if cache_entry is not None:
  246. logger.debug("Using cached wheel link: %s", cache_entry.link)
  247. link = cache_entry.link
  248. ireq = make_install_req_from_link(link, template)
  249. assert ireq.link == link
  250. if ireq.link.is_wheel and not ireq.link.is_file:
  251. wheel = Wheel(ireq.link.filename)
  252. wheel_name = wheel.name
  253. assert name == wheel_name, f"{name!r} != {wheel_name!r} for wheel"
  254. # Version may not be present for PEP 508 direct URLs
  255. if version is not None:
  256. wheel_version = Version(wheel.version)
  257. assert (
  258. version == wheel_version
  259. ), f"{version!r} != {wheel_version!r} for wheel {name}"
  260. if cache_entry is not None:
  261. assert ireq.link.is_wheel
  262. assert ireq.link.is_file
  263. if cache_entry.persistent and template.link is template.original_link:
  264. ireq.cached_wheel_source_link = source_link
  265. if cache_entry.origin is not None:
  266. ireq.download_info = cache_entry.origin
  267. else:
  268. # Legacy cache entry that does not have origin.json.
  269. # download_info may miss the archive_info.hashes field.
  270. ireq.download_info = direct_url_from_link(
  271. source_link, link_is_in_wheel_cache=cache_entry.persistent
  272. )
  273. super().__init__(
  274. link=link,
  275. source_link=source_link,
  276. ireq=ireq,
  277. factory=factory,
  278. name=name,
  279. version=version,
  280. )
  281. def _prepare_distribution(self) -> BaseDistribution:
  282. preparer = self._factory.preparer
  283. return preparer.prepare_linked_requirement(self._ireq, parallel_builds=True)
  284. class EditableCandidate(_InstallRequirementBackedCandidate):
  285. is_editable = True
  286. def __init__(
  287. self,
  288. link: Link,
  289. template: InstallRequirement,
  290. factory: Factory,
  291. name: NormalizedName | None = None,
  292. version: Version | None = None,
  293. ) -> None:
  294. super().__init__(
  295. link=link,
  296. source_link=link,
  297. ireq=make_install_req_from_editable(link, template),
  298. factory=factory,
  299. name=name,
  300. version=version,
  301. )
  302. def _prepare_distribution(self) -> BaseDistribution:
  303. return self._factory.preparer.prepare_editable_requirement(self._ireq)
  304. class AlreadyInstalledCandidate(Candidate):
  305. is_installed = True
  306. source_link = None
  307. def __init__(
  308. self,
  309. dist: BaseDistribution,
  310. template: InstallRequirement,
  311. factory: Factory,
  312. ) -> None:
  313. self.dist = dist
  314. self._ireq = _make_install_req_from_dist(dist, template)
  315. self._factory = factory
  316. self._version = None
  317. # This is just logging some messages, so we can do it eagerly.
  318. # The returned dist would be exactly the same as self.dist because we
  319. # set satisfied_by in _make_install_req_from_dist.
  320. # TODO: Supply reason based on force_reinstall and upgrade_strategy.
  321. skip_reason = "already satisfied"
  322. factory.preparer.prepare_installed_requirement(self._ireq, skip_reason)
  323. def __str__(self) -> str:
  324. return str(self.dist)
  325. def __repr__(self) -> str:
  326. return f"{self.__class__.__name__}({self.dist!r})"
  327. def __eq__(self, other: object) -> bool:
  328. if not isinstance(other, AlreadyInstalledCandidate):
  329. return NotImplemented
  330. return self.name == other.name and self.version == other.version
  331. def __hash__(self) -> int:
  332. return hash((self.name, self.version))
  333. @property
  334. def project_name(self) -> NormalizedName:
  335. return self.dist.canonical_name
  336. @property
  337. def name(self) -> str:
  338. return self.project_name
  339. @property
  340. def version(self) -> Version:
  341. if self._version is None:
  342. self._version = self.dist.version
  343. return self._version
  344. @property
  345. def is_editable(self) -> bool:
  346. return self.dist.editable
  347. def format_for_error(self) -> str:
  348. return f"{self.name} {self.version} (Installed)"
  349. def iter_dependencies(self, with_requires: bool) -> Iterable[Requirement | None]:
  350. if not with_requires:
  351. return
  352. try:
  353. for r in self.dist.iter_dependencies():
  354. yield from self._factory.make_requirements_from_spec(str(r), self._ireq)
  355. except InvalidRequirement as exc:
  356. raise InvalidInstalledPackage(dist=self.dist, invalid_exc=exc) from None
  357. def get_install_requirement(self) -> InstallRequirement | None:
  358. return None
  359. class ExtrasCandidate(Candidate):
  360. """A candidate that has 'extras', indicating additional dependencies.
  361. Requirements can be for a project with dependencies, something like
  362. foo[extra]. The extras don't affect the project/version being installed
  363. directly, but indicate that we need additional dependencies. We model that
  364. by having an artificial ExtrasCandidate that wraps the "base" candidate.
  365. The ExtrasCandidate differs from the base in the following ways:
  366. 1. It has a unique name, of the form foo[extra]. This causes the resolver
  367. to treat it as a separate node in the dependency graph.
  368. 2. When we're getting the candidate's dependencies,
  369. a) We specify that we want the extra dependencies as well.
  370. b) We add a dependency on the base candidate.
  371. See below for why this is needed.
  372. 3. We return None for the underlying InstallRequirement, as the base
  373. candidate will provide it, and we don't want to end up with duplicates.
  374. The dependency on the base candidate is needed so that the resolver can't
  375. decide that it should recommend foo[extra1] version 1.0 and foo[extra2]
  376. version 2.0. Having those candidates depend on foo=1.0 and foo=2.0
  377. respectively forces the resolver to recognise that this is a conflict.
  378. """
  379. def __init__(
  380. self,
  381. base: BaseCandidate,
  382. extras: frozenset[str],
  383. *,
  384. comes_from: InstallRequirement | None = None,
  385. ) -> None:
  386. """
  387. :param comes_from: the InstallRequirement that led to this candidate if it
  388. differs from the base's InstallRequirement. This will often be the
  389. case in the sense that this candidate's requirement has the extras
  390. while the base's does not. Unlike the InstallRequirement backed
  391. candidates, this requirement is used solely for reporting purposes,
  392. it does not do any leg work.
  393. """
  394. self.base = base
  395. self.extras = frozenset(canonicalize_name(e) for e in extras)
  396. self._comes_from = comes_from if comes_from is not None else self.base._ireq
  397. def __str__(self) -> str:
  398. name, rest = str(self.base).split(" ", 1)
  399. return "{}[{}] {}".format(name, ",".join(self.extras), rest)
  400. def __repr__(self) -> str:
  401. return f"{self.__class__.__name__}(base={self.base!r}, extras={self.extras!r})"
  402. def __hash__(self) -> int:
  403. return hash((self.base, self.extras))
  404. def __eq__(self, other: Any) -> bool:
  405. if isinstance(other, self.__class__):
  406. return self.base == other.base and self.extras == other.extras
  407. return False
  408. @property
  409. def project_name(self) -> NormalizedName:
  410. return self.base.project_name
  411. @property
  412. def name(self) -> str:
  413. """The normalised name of the project the candidate refers to"""
  414. return format_name(self.base.project_name, self.extras)
  415. @property
  416. def version(self) -> Version:
  417. return self.base.version
  418. def format_for_error(self) -> str:
  419. return "{} [{}]".format(
  420. self.base.format_for_error(), ", ".join(sorted(self.extras))
  421. )
  422. @property
  423. def is_installed(self) -> bool:
  424. return self.base.is_installed
  425. @property
  426. def is_editable(self) -> bool:
  427. return self.base.is_editable
  428. @property
  429. def source_link(self) -> Link | None:
  430. return self.base.source_link
  431. def iter_dependencies(self, with_requires: bool) -> Iterable[Requirement | None]:
  432. factory = self.base._factory
  433. # Add a dependency on the exact base
  434. # (See note 2b in the class docstring)
  435. yield factory.make_requirement_from_candidate(self.base)
  436. if not with_requires:
  437. return
  438. # The user may have specified extras that the candidate doesn't
  439. # support. We ignore any unsupported extras here.
  440. valid_extras = self.extras.intersection(self.base.dist.iter_provided_extras())
  441. invalid_extras = self.extras.difference(self.base.dist.iter_provided_extras())
  442. for extra in sorted(invalid_extras):
  443. logger.warning(
  444. "%s %s does not provide the extra '%s'",
  445. self.base.name,
  446. self.version,
  447. extra,
  448. )
  449. for r in self.base.dist.iter_dependencies(valid_extras):
  450. yield from factory.make_requirements_from_spec(
  451. str(r),
  452. self._comes_from,
  453. valid_extras,
  454. )
  455. def get_install_requirement(self) -> InstallRequirement | None:
  456. # We don't return anything here, because we always
  457. # depend on the base candidate, and we'll get the
  458. # install requirement from that.
  459. return None
  460. class RequiresPythonCandidate(Candidate):
  461. is_installed = False
  462. source_link = None
  463. def __init__(self, py_version_info: tuple[int, ...] | None) -> None:
  464. if py_version_info is not None:
  465. version_info = normalize_version_info(py_version_info)
  466. else:
  467. version_info = sys.version_info[:3]
  468. self._version = Version(".".join(str(c) for c in version_info))
  469. # We don't need to implement __eq__() and __ne__() since there is always
  470. # only one RequiresPythonCandidate in a resolution, i.e. the host Python.
  471. # The built-in object.__eq__() and object.__ne__() do exactly what we want.
  472. def __str__(self) -> str:
  473. return f"Python {self._version}"
  474. def __repr__(self) -> str:
  475. return f"{self.__class__.__name__}({self._version!r})"
  476. @property
  477. def project_name(self) -> NormalizedName:
  478. return REQUIRES_PYTHON_IDENTIFIER
  479. @property
  480. def name(self) -> str:
  481. return REQUIRES_PYTHON_IDENTIFIER
  482. @property
  483. def version(self) -> Version:
  484. return self._version
  485. def format_for_error(self) -> str:
  486. return f"Python {self.version}"
  487. def iter_dependencies(self, with_requires: bool) -> Iterable[Requirement | None]:
  488. return ()
  489. def get_install_requirement(self) -> InstallRequirement | None:
  490. return None