factory.py 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856
  1. from __future__ import annotations
  2. import contextlib
  3. import functools
  4. import logging
  5. from collections.abc import Iterable, Iterator, Mapping, Sequence
  6. from typing import (
  7. TYPE_CHECKING,
  8. Callable,
  9. NamedTuple,
  10. Protocol,
  11. TypeVar,
  12. cast,
  13. )
  14. from pip._vendor.packaging.requirements import InvalidRequirement
  15. from pip._vendor.packaging.specifiers import SpecifierSet
  16. from pip._vendor.packaging.utils import NormalizedName, canonicalize_name
  17. from pip._vendor.packaging.version import InvalidVersion, Version
  18. from pip._vendor.resolvelib import ResolutionImpossible
  19. from pip._internal.cache import CacheEntry, WheelCache
  20. from pip._internal.exceptions import (
  21. DistributionNotFound,
  22. InstallationError,
  23. InvalidInstalledPackage,
  24. MetadataInconsistent,
  25. MetadataInvalid,
  26. UnsupportedPythonVersion,
  27. UnsupportedWheel,
  28. )
  29. from pip._internal.index.package_finder import PackageFinder
  30. from pip._internal.metadata import BaseDistribution, get_default_environment
  31. from pip._internal.models.link import Link
  32. from pip._internal.models.wheel import Wheel
  33. from pip._internal.operations.prepare import RequirementPreparer
  34. from pip._internal.req.constructors import (
  35. install_req_drop_extras,
  36. install_req_from_link_and_ireq,
  37. )
  38. from pip._internal.req.req_install import (
  39. InstallRequirement,
  40. check_invalid_constraint_type,
  41. )
  42. from pip._internal.resolution.base import InstallRequirementProvider
  43. from pip._internal.utils.compatibility_tags import get_supported
  44. from pip._internal.utils.hashes import Hashes
  45. from pip._internal.utils.packaging import get_requirement
  46. from pip._internal.utils.virtualenv import running_under_virtualenv
  47. from .base import Candidate, Constraint, Requirement
  48. from .candidates import (
  49. AlreadyInstalledCandidate,
  50. BaseCandidate,
  51. EditableCandidate,
  52. ExtrasCandidate,
  53. LinkCandidate,
  54. RequiresPythonCandidate,
  55. as_base_candidate,
  56. )
  57. from .found_candidates import FoundCandidates, IndexCandidateInfo
  58. from .requirements import (
  59. ExplicitRequirement,
  60. RequiresPythonRequirement,
  61. SpecifierRequirement,
  62. SpecifierWithoutExtrasRequirement,
  63. UnsatisfiableRequirement,
  64. )
  65. if TYPE_CHECKING:
  66. class ConflictCause(Protocol):
  67. requirement: RequiresPythonRequirement
  68. parent: Candidate
  69. logger = logging.getLogger(__name__)
  70. C = TypeVar("C")
  71. Cache = dict[Link, C]
  72. class CollectedRootRequirements(NamedTuple):
  73. requirements: list[Requirement]
  74. constraints: dict[str, Constraint]
  75. user_requested: dict[str, int]
  76. class Factory:
  77. def __init__(
  78. self,
  79. finder: PackageFinder,
  80. preparer: RequirementPreparer,
  81. make_install_req: InstallRequirementProvider,
  82. wheel_cache: WheelCache | None,
  83. use_user_site: bool,
  84. force_reinstall: bool,
  85. ignore_installed: bool,
  86. ignore_requires_python: bool,
  87. py_version_info: tuple[int, ...] | None = None,
  88. ) -> None:
  89. self._finder = finder
  90. self.preparer = preparer
  91. self._wheel_cache = wheel_cache
  92. self._python_candidate = RequiresPythonCandidate(py_version_info)
  93. self._make_install_req_from_spec = make_install_req
  94. self._use_user_site = use_user_site
  95. self._force_reinstall = force_reinstall
  96. self._ignore_requires_python = ignore_requires_python
  97. self._build_failures: Cache[InstallationError] = {}
  98. self._link_candidate_cache: Cache[LinkCandidate] = {}
  99. self._editable_candidate_cache: Cache[EditableCandidate] = {}
  100. self._installed_candidate_cache: dict[str, AlreadyInstalledCandidate] = {}
  101. self._extras_candidate_cache: dict[
  102. tuple[int, frozenset[NormalizedName]], ExtrasCandidate
  103. ] = {}
  104. self._supported_tags_cache = get_supported()
  105. if not ignore_installed:
  106. env = get_default_environment()
  107. self._installed_dists = {
  108. dist.canonical_name: dist
  109. for dist in env.iter_installed_distributions(local_only=False)
  110. }
  111. else:
  112. self._installed_dists = {}
  113. @property
  114. def force_reinstall(self) -> bool:
  115. return self._force_reinstall
  116. def _fail_if_link_is_unsupported_wheel(self, link: Link) -> None:
  117. if not link.is_wheel:
  118. return
  119. wheel = Wheel(link.filename)
  120. if wheel.supported(self._finder.target_python.get_unsorted_tags()):
  121. return
  122. msg = f"{link.filename} is not a supported wheel on this platform."
  123. raise UnsupportedWheel(msg)
  124. def _make_extras_candidate(
  125. self,
  126. base: BaseCandidate,
  127. extras: frozenset[str],
  128. *,
  129. comes_from: InstallRequirement | None = None,
  130. ) -> ExtrasCandidate:
  131. cache_key = (id(base), frozenset(canonicalize_name(e) for e in extras))
  132. try:
  133. candidate = self._extras_candidate_cache[cache_key]
  134. except KeyError:
  135. candidate = ExtrasCandidate(base, extras, comes_from=comes_from)
  136. self._extras_candidate_cache[cache_key] = candidate
  137. return candidate
  138. def _make_candidate_from_dist(
  139. self,
  140. dist: BaseDistribution,
  141. extras: frozenset[str],
  142. template: InstallRequirement,
  143. ) -> Candidate:
  144. try:
  145. base = self._installed_candidate_cache[dist.canonical_name]
  146. except KeyError:
  147. base = AlreadyInstalledCandidate(dist, template, factory=self)
  148. self._installed_candidate_cache[dist.canonical_name] = base
  149. if not extras:
  150. return base
  151. return self._make_extras_candidate(base, extras, comes_from=template)
  152. def _make_candidate_from_link(
  153. self,
  154. link: Link,
  155. extras: frozenset[str],
  156. template: InstallRequirement,
  157. name: NormalizedName | None,
  158. version: Version | None,
  159. ) -> Candidate | None:
  160. base: BaseCandidate | None = self._make_base_candidate_from_link(
  161. link, template, name, version
  162. )
  163. if not extras or base is None:
  164. return base
  165. return self._make_extras_candidate(base, extras, comes_from=template)
  166. def _make_base_candidate_from_link(
  167. self,
  168. link: Link,
  169. template: InstallRequirement,
  170. name: NormalizedName | None,
  171. version: Version | None,
  172. ) -> BaseCandidate | None:
  173. # TODO: Check already installed candidate, and use it if the link and
  174. # editable flag match.
  175. if link in self._build_failures:
  176. # We already tried this candidate before, and it does not build.
  177. # Don't bother trying again.
  178. return None
  179. if template.editable:
  180. if link not in self._editable_candidate_cache:
  181. try:
  182. self._editable_candidate_cache[link] = EditableCandidate(
  183. link,
  184. template,
  185. factory=self,
  186. name=name,
  187. version=version,
  188. )
  189. except (MetadataInconsistent, MetadataInvalid) as e:
  190. logger.info(
  191. "Discarding [blue underline]%s[/]: [yellow]%s[reset]",
  192. link,
  193. e,
  194. extra={"markup": True},
  195. )
  196. self._build_failures[link] = e
  197. return None
  198. return self._editable_candidate_cache[link]
  199. else:
  200. if link not in self._link_candidate_cache:
  201. try:
  202. self._link_candidate_cache[link] = LinkCandidate(
  203. link,
  204. template,
  205. factory=self,
  206. name=name,
  207. version=version,
  208. )
  209. except MetadataInconsistent as e:
  210. logger.info(
  211. "Discarding [blue underline]%s[/]: [yellow]%s[reset]",
  212. link,
  213. e,
  214. extra={"markup": True},
  215. )
  216. self._build_failures[link] = e
  217. return None
  218. return self._link_candidate_cache[link]
  219. def _iter_found_candidates(
  220. self,
  221. ireqs: Sequence[InstallRequirement],
  222. specifier: SpecifierSet,
  223. hashes: Hashes,
  224. prefers_installed: bool,
  225. incompatible_ids: set[int],
  226. ) -> Iterable[Candidate]:
  227. if not ireqs:
  228. return ()
  229. # The InstallRequirement implementation requires us to give it a
  230. # "template". Here we just choose the first requirement to represent
  231. # all of them.
  232. # Hopefully the Project model can correct this mismatch in the future.
  233. template = ireqs[0]
  234. assert template.req, "Candidates found on index must be PEP 508"
  235. name = canonicalize_name(template.req.name)
  236. extras: frozenset[str] = frozenset()
  237. for ireq in ireqs:
  238. assert ireq.req, "Candidates found on index must be PEP 508"
  239. specifier &= ireq.req.specifier
  240. hashes &= ireq.hashes(trust_internet=False)
  241. extras |= frozenset(ireq.extras)
  242. def _get_installed_candidate() -> Candidate | None:
  243. """Get the candidate for the currently-installed version."""
  244. # If --force-reinstall is set, we want the version from the index
  245. # instead, so we "pretend" there is nothing installed.
  246. if self._force_reinstall:
  247. return None
  248. try:
  249. installed_dist = self._installed_dists[name]
  250. except KeyError:
  251. return None
  252. try:
  253. # Don't use the installed distribution if its version
  254. # does not fit the current dependency graph.
  255. if not specifier.contains(installed_dist.version, prereleases=True):
  256. return None
  257. except InvalidVersion as e:
  258. raise InvalidInstalledPackage(dist=installed_dist, invalid_exc=e)
  259. candidate = self._make_candidate_from_dist(
  260. dist=installed_dist,
  261. extras=extras,
  262. template=template,
  263. )
  264. # The candidate is a known incompatibility. Don't use it.
  265. if id(candidate) in incompatible_ids:
  266. return None
  267. return candidate
  268. def iter_index_candidate_infos() -> Iterator[IndexCandidateInfo]:
  269. result = self._finder.find_best_candidate(
  270. project_name=name,
  271. specifier=specifier,
  272. hashes=hashes,
  273. )
  274. icans = result.applicable_candidates
  275. # PEP 592: Yanked releases are ignored unless the specifier
  276. # explicitly pins a version (via '==' or '===') that can be
  277. # solely satisfied by a yanked release.
  278. all_yanked = all(ican.link.is_yanked for ican in icans)
  279. def is_pinned(specifier: SpecifierSet) -> bool:
  280. for sp in specifier:
  281. if sp.operator == "===":
  282. return True
  283. if sp.operator != "==":
  284. continue
  285. if sp.version.endswith(".*"):
  286. continue
  287. return True
  288. return False
  289. pinned = is_pinned(specifier)
  290. # PackageFinder returns earlier versions first, so we reverse.
  291. for ican in reversed(icans):
  292. if not (all_yanked and pinned) and ican.link.is_yanked:
  293. continue
  294. func = functools.partial(
  295. self._make_candidate_from_link,
  296. link=ican.link,
  297. extras=extras,
  298. template=template,
  299. name=name,
  300. version=ican.version,
  301. )
  302. yield ican.version, func
  303. return FoundCandidates(
  304. iter_index_candidate_infos,
  305. _get_installed_candidate(),
  306. prefers_installed,
  307. incompatible_ids,
  308. )
  309. def _iter_explicit_candidates_from_base(
  310. self,
  311. base_requirements: Iterable[Requirement],
  312. extras: frozenset[str],
  313. ) -> Iterator[Candidate]:
  314. """Produce explicit candidates from the base given an extra-ed package.
  315. :param base_requirements: Requirements known to the resolver. The
  316. requirements are guaranteed to not have extras.
  317. :param extras: The extras to inject into the explicit requirements'
  318. candidates.
  319. """
  320. for req in base_requirements:
  321. lookup_cand, _ = req.get_candidate_lookup()
  322. if lookup_cand is None: # Not explicit.
  323. continue
  324. # We've stripped extras from the identifier, and should always
  325. # get a BaseCandidate here, unless there's a bug elsewhere.
  326. base_cand = as_base_candidate(lookup_cand)
  327. assert base_cand is not None, "no extras here"
  328. yield self._make_extras_candidate(base_cand, extras)
  329. def _iter_candidates_from_constraints(
  330. self,
  331. identifier: str,
  332. constraint: Constraint,
  333. template: InstallRequirement,
  334. ) -> Iterator[Candidate]:
  335. """Produce explicit candidates from constraints.
  336. This creates "fake" InstallRequirement objects that are basically clones
  337. of what "should" be the template, but with original_link set to link.
  338. """
  339. for link in constraint.links:
  340. self._fail_if_link_is_unsupported_wheel(link)
  341. candidate = self._make_base_candidate_from_link(
  342. link,
  343. template=install_req_from_link_and_ireq(link, template),
  344. name=canonicalize_name(identifier),
  345. version=None,
  346. )
  347. if candidate:
  348. yield candidate
  349. def find_candidates(
  350. self,
  351. identifier: str,
  352. requirements: Mapping[str, Iterable[Requirement]],
  353. incompatibilities: Mapping[str, Iterator[Candidate]],
  354. constraint: Constraint,
  355. prefers_installed: bool,
  356. is_satisfied_by: Callable[[Requirement, Candidate], bool],
  357. ) -> Iterable[Candidate]:
  358. # Collect basic lookup information from the requirements.
  359. explicit_candidates: set[Candidate] = set()
  360. ireqs: list[InstallRequirement] = []
  361. for req in requirements[identifier]:
  362. cand, ireq = req.get_candidate_lookup()
  363. if cand is not None:
  364. explicit_candidates.add(cand)
  365. if ireq is not None:
  366. ireqs.append(ireq)
  367. # If the current identifier contains extras, add requires and explicit
  368. # candidates from entries from extra-less identifier.
  369. with contextlib.suppress(InvalidRequirement):
  370. parsed_requirement = get_requirement(identifier)
  371. if parsed_requirement.name != identifier:
  372. explicit_candidates.update(
  373. self._iter_explicit_candidates_from_base(
  374. requirements.get(parsed_requirement.name, ()),
  375. frozenset(parsed_requirement.extras),
  376. ),
  377. )
  378. for req in requirements.get(parsed_requirement.name, []):
  379. _, ireq = req.get_candidate_lookup()
  380. if ireq is not None:
  381. ireqs.append(ireq)
  382. # Add explicit candidates from constraints. We only do this if there are
  383. # known ireqs, which represent requirements not already explicit. If
  384. # there are no ireqs, we're constraining already-explicit requirements,
  385. # which is handled later when we return the explicit candidates.
  386. if ireqs:
  387. try:
  388. explicit_candidates.update(
  389. self._iter_candidates_from_constraints(
  390. identifier,
  391. constraint,
  392. template=ireqs[0],
  393. ),
  394. )
  395. except UnsupportedWheel:
  396. # If we're constrained to install a wheel incompatible with the
  397. # target architecture, no candidates will ever be valid.
  398. return ()
  399. # Since we cache all the candidates, incompatibility identification
  400. # can be made quicker by comparing only the id() values.
  401. incompat_ids = {id(c) for c in incompatibilities.get(identifier, ())}
  402. # If none of the requirements want an explicit candidate, we can ask
  403. # the finder for candidates.
  404. if not explicit_candidates:
  405. return self._iter_found_candidates(
  406. ireqs,
  407. constraint.specifier,
  408. constraint.hashes,
  409. prefers_installed,
  410. incompat_ids,
  411. )
  412. return (
  413. c
  414. for c in explicit_candidates
  415. if id(c) not in incompat_ids
  416. and constraint.is_satisfied_by(c)
  417. and all(is_satisfied_by(req, c) for req in requirements[identifier])
  418. )
  419. def _make_requirements_from_install_req(
  420. self, ireq: InstallRequirement, requested_extras: Iterable[str]
  421. ) -> Iterator[Requirement]:
  422. """
  423. Returns requirement objects associated with the given InstallRequirement. In
  424. most cases this will be a single object but the following special cases exist:
  425. - the InstallRequirement has markers that do not apply -> result is empty
  426. - the InstallRequirement has both a constraint (or link) and extras
  427. -> result is split in two requirement objects: one with the constraint
  428. (or link) and one with the extra. This allows centralized constraint
  429. handling for the base, resulting in fewer candidate rejections.
  430. """
  431. if not ireq.match_markers(requested_extras):
  432. logger.info(
  433. "Ignoring %s: markers '%s' don't match your environment",
  434. ireq.name,
  435. ireq.markers,
  436. )
  437. elif not ireq.link:
  438. if ireq.extras and ireq.req is not None and ireq.req.specifier:
  439. yield SpecifierWithoutExtrasRequirement(ireq)
  440. yield SpecifierRequirement(ireq)
  441. else:
  442. self._fail_if_link_is_unsupported_wheel(ireq.link)
  443. # Always make the link candidate for the base requirement to make it
  444. # available to `find_candidates` for explicit candidate lookup for any
  445. # set of extras.
  446. # The extras are required separately via a second requirement.
  447. cand = self._make_base_candidate_from_link(
  448. ireq.link,
  449. template=install_req_drop_extras(ireq) if ireq.extras else ireq,
  450. name=canonicalize_name(ireq.name) if ireq.name else None,
  451. version=None,
  452. )
  453. if cand is None:
  454. # There's no way we can satisfy a URL requirement if the underlying
  455. # candidate fails to build. An unnamed URL must be user-supplied, so
  456. # we fail eagerly. If the URL is named, an unsatisfiable requirement
  457. # can make the resolver do the right thing, either backtrack (and
  458. # maybe find some other requirement that's buildable) or raise a
  459. # ResolutionImpossible eventually.
  460. if not ireq.name:
  461. raise self._build_failures[ireq.link]
  462. yield UnsatisfiableRequirement(canonicalize_name(ireq.name))
  463. else:
  464. # require the base from the link
  465. yield self.make_requirement_from_candidate(cand)
  466. if ireq.extras:
  467. # require the extras on top of the base candidate
  468. yield self.make_requirement_from_candidate(
  469. self._make_extras_candidate(cand, frozenset(ireq.extras))
  470. )
  471. def collect_root_requirements(
  472. self, root_ireqs: list[InstallRequirement]
  473. ) -> CollectedRootRequirements:
  474. collected = CollectedRootRequirements([], {}, {})
  475. for i, ireq in enumerate(root_ireqs):
  476. if ireq.constraint:
  477. # Ensure we only accept valid constraints
  478. problem = check_invalid_constraint_type(ireq)
  479. if problem:
  480. raise InstallationError(problem)
  481. if not ireq.match_markers():
  482. continue
  483. assert ireq.name, "Constraint must be named"
  484. name = canonicalize_name(ireq.name)
  485. if name in collected.constraints:
  486. collected.constraints[name] &= ireq
  487. else:
  488. collected.constraints[name] = Constraint.from_ireq(ireq)
  489. else:
  490. reqs = list(
  491. self._make_requirements_from_install_req(
  492. ireq,
  493. requested_extras=(),
  494. )
  495. )
  496. if not reqs:
  497. continue
  498. template = reqs[0]
  499. if ireq.user_supplied and template.name not in collected.user_requested:
  500. collected.user_requested[template.name] = i
  501. collected.requirements.extend(reqs)
  502. # Put requirements with extras at the end of the root requires. This does not
  503. # affect resolvelib's picking preference but it does affect its initial criteria
  504. # population: by putting extras at the end we enable the candidate finder to
  505. # present resolvelib with a smaller set of candidates to resolvelib, already
  506. # taking into account any non-transient constraints on the associated base. This
  507. # means resolvelib will have fewer candidates to visit and reject.
  508. # Python's list sort is stable, meaning relative order is kept for objects with
  509. # the same key.
  510. collected.requirements.sort(key=lambda r: r.name != r.project_name)
  511. return collected
  512. def make_requirement_from_candidate(
  513. self, candidate: Candidate
  514. ) -> ExplicitRequirement:
  515. return ExplicitRequirement(candidate)
  516. def make_requirements_from_spec(
  517. self,
  518. specifier: str,
  519. comes_from: InstallRequirement | None,
  520. requested_extras: Iterable[str] = (),
  521. ) -> Iterator[Requirement]:
  522. """
  523. Returns requirement objects associated with the given specifier. In most cases
  524. this will be a single object but the following special cases exist:
  525. - the specifier has markers that do not apply -> result is empty
  526. - the specifier has both a constraint and extras -> result is split
  527. in two requirement objects: one with the constraint and one with the
  528. extra. This allows centralized constraint handling for the base,
  529. resulting in fewer candidate rejections.
  530. """
  531. ireq = self._make_install_req_from_spec(specifier, comes_from)
  532. return self._make_requirements_from_install_req(ireq, requested_extras)
  533. def make_requires_python_requirement(
  534. self,
  535. specifier: SpecifierSet,
  536. ) -> Requirement | None:
  537. if self._ignore_requires_python:
  538. return None
  539. # Don't bother creating a dependency for an empty Requires-Python.
  540. if not str(specifier):
  541. return None
  542. return RequiresPythonRequirement(specifier, self._python_candidate)
  543. def get_wheel_cache_entry(self, link: Link, name: str | None) -> CacheEntry | None:
  544. """Look up the link in the wheel cache.
  545. If ``preparer.require_hashes`` is True, don't use the wheel cache,
  546. because cached wheels, always built locally, have different hashes
  547. than the files downloaded from the index server and thus throw false
  548. hash mismatches. Furthermore, cached wheels at present have
  549. nondeterministic contents due to file modification times.
  550. """
  551. if self._wheel_cache is None:
  552. return None
  553. return self._wheel_cache.get_cache_entry(
  554. link=link,
  555. package_name=name,
  556. supported_tags=self._supported_tags_cache,
  557. )
  558. def get_dist_to_uninstall(self, candidate: Candidate) -> BaseDistribution | None:
  559. # TODO: Are there more cases this needs to return True? Editable?
  560. dist = self._installed_dists.get(candidate.project_name)
  561. if dist is None: # Not installed, no uninstallation required.
  562. return None
  563. # We're installing into global site. The current installation must
  564. # be uninstalled, no matter it's in global or user site, because the
  565. # user site installation has precedence over global.
  566. if not self._use_user_site:
  567. return dist
  568. # We're installing into user site. Remove the user site installation.
  569. if dist.in_usersite:
  570. return dist
  571. # We're installing into user site, but the installed incompatible
  572. # package is in global site. We can't uninstall that, and would let
  573. # the new user installation to "shadow" it. But shadowing won't work
  574. # in virtual environments, so we error out.
  575. if running_under_virtualenv() and dist.in_site_packages:
  576. message = (
  577. f"Will not install to the user site because it will lack "
  578. f"sys.path precedence to {dist.raw_name} in {dist.location}"
  579. )
  580. raise InstallationError(message)
  581. return None
  582. def _report_requires_python_error(
  583. self, causes: Sequence[ConflictCause]
  584. ) -> UnsupportedPythonVersion:
  585. assert causes, "Requires-Python error reported with no cause"
  586. version = self._python_candidate.version
  587. if len(causes) == 1:
  588. specifier = str(causes[0].requirement.specifier)
  589. message = (
  590. f"Package {causes[0].parent.name!r} requires a different "
  591. f"Python: {version} not in {specifier!r}"
  592. )
  593. return UnsupportedPythonVersion(message)
  594. message = f"Packages require a different Python. {version} not in:"
  595. for cause in causes:
  596. package = cause.parent.format_for_error()
  597. specifier = str(cause.requirement.specifier)
  598. message += f"\n{specifier!r} (required by {package})"
  599. return UnsupportedPythonVersion(message)
  600. def _report_single_requirement_conflict(
  601. self, req: Requirement, parent: Candidate | None
  602. ) -> DistributionNotFound:
  603. if parent is None:
  604. req_disp = str(req)
  605. else:
  606. req_disp = f"{req} (from {parent.name})"
  607. cands = self._finder.find_all_candidates(req.project_name)
  608. skipped_by_requires_python = self._finder.requires_python_skipped_reasons()
  609. versions_set: set[Version] = set()
  610. yanked_versions_set: set[Version] = set()
  611. for c in cands:
  612. is_yanked = c.link.is_yanked if c.link else False
  613. if is_yanked:
  614. yanked_versions_set.add(c.version)
  615. else:
  616. versions_set.add(c.version)
  617. versions = [str(v) for v in sorted(versions_set)]
  618. yanked_versions = [str(v) for v in sorted(yanked_versions_set)]
  619. if yanked_versions:
  620. # Saying "version X is yanked" isn't entirely accurate.
  621. # https://github.com/pypa/pip/issues/11745#issuecomment-1402805842
  622. logger.critical(
  623. "Ignored the following yanked versions: %s",
  624. ", ".join(yanked_versions) or "none",
  625. )
  626. if skipped_by_requires_python:
  627. logger.critical(
  628. "Ignored the following versions that require a different python "
  629. "version: %s",
  630. "; ".join(skipped_by_requires_python) or "none",
  631. )
  632. # Check if only final releases are allowed for this package
  633. version_type = "version"
  634. if self._finder.release_control is not None:
  635. allows_pre = self._finder.release_control.allows_prereleases(
  636. canonicalize_name(req.project_name)
  637. )
  638. if allows_pre is False:
  639. version_type = "final version"
  640. logger.critical(
  641. "Could not find a %s that satisfies the requirement %s "
  642. "(from versions: %s)",
  643. version_type,
  644. req_disp,
  645. ", ".join(versions) or "none",
  646. )
  647. if str(req) == "requirements.txt":
  648. logger.info(
  649. "HINT: You are attempting to install a package literally "
  650. 'named "requirements.txt" (which cannot exist). Consider '
  651. "using the '-r' flag to install the packages listed in "
  652. "requirements.txt"
  653. )
  654. return DistributionNotFound(f"No matching distribution found for {req}")
  655. def _has_any_candidates(self, project_name: str) -> bool:
  656. """
  657. Check if there are any candidates available for the project name.
  658. """
  659. return any(
  660. self.find_candidates(
  661. project_name,
  662. requirements={project_name: []},
  663. incompatibilities={},
  664. constraint=Constraint.empty(),
  665. prefers_installed=True,
  666. is_satisfied_by=lambda r, c: True,
  667. )
  668. )
  669. def get_installation_error(
  670. self,
  671. e: ResolutionImpossible[Requirement, Candidate],
  672. constraints: dict[str, Constraint],
  673. ) -> InstallationError:
  674. assert e.causes, "Installation error reported with no cause"
  675. # If one of the things we can't solve is "we need Python X.Y",
  676. # that is what we report.
  677. requires_python_causes = [
  678. cause
  679. for cause in e.causes
  680. if isinstance(cause.requirement, RequiresPythonRequirement)
  681. and not cause.requirement.is_satisfied_by(self._python_candidate)
  682. ]
  683. if requires_python_causes:
  684. # The comprehension above makes sure all Requirement instances are
  685. # RequiresPythonRequirement, so let's cast for convenience.
  686. return self._report_requires_python_error(
  687. cast("Sequence[ConflictCause]", requires_python_causes),
  688. )
  689. # Otherwise, we have a set of causes which can't all be satisfied
  690. # at once.
  691. # The simplest case is when we have *one* cause that can't be
  692. # satisfied. We just report that case.
  693. if len(e.causes) == 1:
  694. req, parent = next(iter(e.causes))
  695. if req.name not in constraints:
  696. return self._report_single_requirement_conflict(req, parent)
  697. # OK, we now have a list of requirements that can't all be
  698. # satisfied at once.
  699. # A couple of formatting helpers
  700. def text_join(parts: list[str]) -> str:
  701. if len(parts) == 1:
  702. return parts[0]
  703. return ", ".join(parts[:-1]) + " and " + parts[-1]
  704. def describe_trigger(parent: Candidate) -> str:
  705. ireq = parent.get_install_requirement()
  706. if not ireq or not ireq.comes_from:
  707. return f"{parent.name}=={parent.version}"
  708. if isinstance(ireq.comes_from, InstallRequirement):
  709. return str(ireq.comes_from.name)
  710. return str(ireq.comes_from)
  711. triggers = set()
  712. for req, parent in e.causes:
  713. if parent is None:
  714. # This is a root requirement, so we can report it directly
  715. trigger = req.format_for_error()
  716. else:
  717. trigger = describe_trigger(parent)
  718. triggers.add(trigger)
  719. if triggers:
  720. info = text_join(sorted(triggers))
  721. else:
  722. info = "the requested packages"
  723. msg = (
  724. f"Cannot install {info} because these package versions "
  725. "have conflicting dependencies."
  726. )
  727. logger.critical(msg)
  728. msg = "\nThe conflict is caused by:"
  729. relevant_constraints = set()
  730. for req, parent in e.causes:
  731. if req.name in constraints:
  732. relevant_constraints.add(req.name)
  733. msg = msg + "\n "
  734. if parent:
  735. msg = msg + f"{parent.name} {parent.version} depends on "
  736. else:
  737. msg = msg + "The user requested "
  738. msg = msg + req.format_for_error()
  739. for key in relevant_constraints:
  740. spec = constraints[key].specifier
  741. msg += f"\n The user requested (constraint) {key}{spec}"
  742. # Check for causes that had no candidates
  743. causes = set()
  744. for req, _ in e.causes:
  745. causes.add(req.name)
  746. no_candidates = {c for c in causes if not self._has_any_candidates(c)}
  747. if no_candidates:
  748. msg = (
  749. msg
  750. + "\n\n"
  751. + "Additionally, some packages in these conflicts have no "
  752. + "matching distributions available for your environment:"
  753. + "\n "
  754. + "\n ".join(sorted(no_candidates))
  755. )
  756. msg = (
  757. msg
  758. + "\n\n"
  759. + "To fix this you could try to:\n"
  760. + "1. loosen the range of package versions you've specified\n"
  761. + "2. remove package versions to allow pip to attempt to solve "
  762. + "the dependency conflict\n"
  763. )
  764. logger.info(msg)
  765. return DistributionNotFound(
  766. "ResolutionImpossible: for help visit "
  767. "https://pip.pypa.io/en/latest/topics/dependency-resolution/"
  768. "#dealing-with-dependency-conflicts"
  769. )