m2m模型翻译
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

812 lines
32 KiB

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