candidates.py 19 KB

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