candidates.py 18 KB

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