candidates.py 18 KB

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