factory.py 27 KB

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