candidates.py 18 KB

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