exceptions.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881
  1. """Exceptions used throughout package.
  2. This module MUST NOT try to import from anything within `pip._internal` to
  3. operate. This is expected to be importable from any/all files within the
  4. subpackage and, thus, should not depend on them.
  5. """
  6. from __future__ import annotations
  7. import configparser
  8. import contextlib
  9. import locale
  10. import logging
  11. import pathlib
  12. import re
  13. import sys
  14. from collections.abc import Iterator
  15. from itertools import chain, groupby, repeat
  16. from typing import TYPE_CHECKING, Literal
  17. from pip._vendor.packaging.requirements import InvalidRequirement
  18. from pip._vendor.packaging.version import InvalidVersion
  19. from pip._vendor.rich.console import Console, ConsoleOptions, RenderResult
  20. from pip._vendor.rich.markup import escape
  21. from pip._vendor.rich.text import Text
  22. if TYPE_CHECKING:
  23. from hashlib import _Hash
  24. from pip._vendor.requests.models import Request, Response
  25. from pip._internal.metadata import BaseDistribution
  26. from pip._internal.network.download import _FileDownload
  27. from pip._internal.req.req_install import InstallRequirement
  28. logger = logging.getLogger(__name__)
  29. #
  30. # Scaffolding
  31. #
  32. def _is_kebab_case(s: str) -> bool:
  33. return re.match(r"^[a-z]+(-[a-z]+)*$", s) is not None
  34. def _prefix_with_indent(
  35. s: Text | str,
  36. console: Console,
  37. *,
  38. prefix: str,
  39. indent: str,
  40. ) -> Text:
  41. if isinstance(s, Text):
  42. text = s
  43. else:
  44. text = console.render_str(s)
  45. return console.render_str(prefix, overflow="ignore") + console.render_str(
  46. f"\n{indent}", overflow="ignore"
  47. ).join(text.split(allow_blank=True))
  48. class PipError(Exception):
  49. """The base pip error."""
  50. class DiagnosticPipError(PipError):
  51. """An error, that presents diagnostic information to the user.
  52. This contains a bunch of logic, to enable pretty presentation of our error
  53. messages. Each error gets a unique reference. Each error can also include
  54. additional context, a hint and/or a note -- which are presented with the
  55. main error message in a consistent style.
  56. This is adapted from the error output styling in `sphinx-theme-builder`.
  57. """
  58. reference: str
  59. def __init__(
  60. self,
  61. *,
  62. kind: Literal["error", "warning"] = "error",
  63. reference: str | None = None,
  64. message: str | Text,
  65. context: str | Text | None,
  66. hint_stmt: str | Text | None,
  67. note_stmt: str | Text | None = None,
  68. link: str | None = None,
  69. ) -> None:
  70. # Ensure a proper reference is provided.
  71. if reference is None:
  72. assert hasattr(self, "reference"), "error reference not provided!"
  73. reference = self.reference
  74. assert _is_kebab_case(reference), "error reference must be kebab-case!"
  75. self.kind = kind
  76. self.reference = reference
  77. self.message = message
  78. self.context = context
  79. self.note_stmt = note_stmt
  80. self.hint_stmt = hint_stmt
  81. self.link = link
  82. super().__init__(f"<{self.__class__.__name__}: {self.reference}>")
  83. def __repr__(self) -> str:
  84. return (
  85. f"<{self.__class__.__name__}("
  86. f"reference={self.reference!r}, "
  87. f"message={self.message!r}, "
  88. f"context={self.context!r}, "
  89. f"note_stmt={self.note_stmt!r}, "
  90. f"hint_stmt={self.hint_stmt!r}"
  91. ")>"
  92. )
  93. def __rich_console__(
  94. self,
  95. console: Console,
  96. options: ConsoleOptions,
  97. ) -> RenderResult:
  98. colour = "red" if self.kind == "error" else "yellow"
  99. yield f"[{colour} bold]{self.kind}[/]: [bold]{self.reference}[/]"
  100. yield ""
  101. if not options.ascii_only:
  102. # Present the main message, with relevant context indented.
  103. if self.context is not None:
  104. yield _prefix_with_indent(
  105. self.message,
  106. console,
  107. prefix=f"[{colour}]×[/] ",
  108. indent=f"[{colour}]│[/] ",
  109. )
  110. yield _prefix_with_indent(
  111. self.context,
  112. console,
  113. prefix=f"[{colour}]╰─>[/] ",
  114. indent=f"[{colour}] [/] ",
  115. )
  116. else:
  117. yield _prefix_with_indent(
  118. self.message,
  119. console,
  120. prefix="[red]×[/] ",
  121. indent=" ",
  122. )
  123. else:
  124. yield self.message
  125. if self.context is not None:
  126. yield ""
  127. yield self.context
  128. if self.note_stmt is not None or self.hint_stmt is not None:
  129. yield ""
  130. if self.note_stmt is not None:
  131. yield _prefix_with_indent(
  132. self.note_stmt,
  133. console,
  134. prefix="[magenta bold]note[/]: ",
  135. indent=" ",
  136. )
  137. if self.hint_stmt is not None:
  138. yield _prefix_with_indent(
  139. self.hint_stmt,
  140. console,
  141. prefix="[cyan bold]hint[/]: ",
  142. indent=" ",
  143. )
  144. if self.link is not None:
  145. yield ""
  146. yield f"Link: {self.link}"
  147. #
  148. # Actual Errors
  149. #
  150. class ConfigurationError(PipError):
  151. """General exception in configuration"""
  152. class InstallationError(PipError):
  153. """General exception during installation"""
  154. class MissingPyProjectBuildRequires(DiagnosticPipError):
  155. """Raised when pyproject.toml has `build-system`, but no `build-system.requires`."""
  156. reference = "missing-pyproject-build-system-requires"
  157. def __init__(self, *, package: str) -> None:
  158. super().__init__(
  159. message=f"Can not process {escape(package)}",
  160. context=Text(
  161. "This package has an invalid pyproject.toml file.\n"
  162. "The [build-system] table is missing the mandatory `requires` key."
  163. ),
  164. note_stmt="This is an issue with the package mentioned above, not pip.",
  165. hint_stmt=Text("See PEP 518 for the detailed specification."),
  166. )
  167. class InvalidPyProjectBuildRequires(DiagnosticPipError):
  168. """Raised when pyproject.toml an invalid `build-system.requires`."""
  169. reference = "invalid-pyproject-build-system-requires"
  170. def __init__(self, *, package: str, reason: str) -> None:
  171. super().__init__(
  172. message=f"Can not process {escape(package)}",
  173. context=Text(
  174. "This package has an invalid `build-system.requires` key in "
  175. f"pyproject.toml.\n{reason}"
  176. ),
  177. note_stmt="This is an issue with the package mentioned above, not pip.",
  178. hint_stmt=Text("See PEP 518 for the detailed specification."),
  179. )
  180. class NoneMetadataError(PipError):
  181. """Raised when accessing a Distribution's "METADATA" or "PKG-INFO".
  182. This signifies an inconsistency, when the Distribution claims to have
  183. the metadata file (if not, raise ``FileNotFoundError`` instead), but is
  184. not actually able to produce its content. This may be due to permission
  185. errors.
  186. """
  187. def __init__(
  188. self,
  189. dist: BaseDistribution,
  190. metadata_name: str,
  191. ) -> None:
  192. """
  193. :param dist: A Distribution object.
  194. :param metadata_name: The name of the metadata being accessed
  195. (can be "METADATA" or "PKG-INFO").
  196. """
  197. self.dist = dist
  198. self.metadata_name = metadata_name
  199. def __str__(self) -> str:
  200. # Use `dist` in the error message because its stringification
  201. # includes more information, like the version and location.
  202. return f"None {self.metadata_name} metadata found for distribution: {self.dist}"
  203. class UserInstallationInvalid(InstallationError):
  204. """A --user install is requested on an environment without user site."""
  205. def __str__(self) -> str:
  206. return "User base directory is not specified"
  207. class InvalidSchemeCombination(InstallationError):
  208. def __str__(self) -> str:
  209. before = ", ".join(str(a) for a in self.args[:-1])
  210. return f"Cannot set {before} and {self.args[-1]} together"
  211. class DistributionNotFound(InstallationError):
  212. """Raised when a distribution cannot be found to satisfy a requirement"""
  213. class RequirementsFileParseError(InstallationError):
  214. """Raised when a general error occurs parsing a requirements file line."""
  215. class BestVersionAlreadyInstalled(PipError):
  216. """Raised when the most up-to-date version of a package is already
  217. installed."""
  218. class BadCommand(PipError):
  219. """Raised when virtualenv or a command is not found"""
  220. class CommandError(PipError):
  221. """Raised when there is an error in command-line arguments"""
  222. class PreviousBuildDirError(PipError):
  223. """Raised when there's a previous conflicting build directory"""
  224. class NetworkConnectionError(PipError):
  225. """HTTP connection error"""
  226. def __init__(
  227. self,
  228. error_msg: str,
  229. response: Response | None = None,
  230. request: Request | None = None,
  231. ) -> None:
  232. """
  233. Initialize NetworkConnectionError with `request` and `response`
  234. objects.
  235. """
  236. self.response = response
  237. self.request = request
  238. self.error_msg = error_msg
  239. if (
  240. self.response is not None
  241. and not self.request
  242. and hasattr(response, "request")
  243. ):
  244. self.request = self.response.request
  245. super().__init__(error_msg, response, request)
  246. def __str__(self) -> str:
  247. return str(self.error_msg)
  248. class InvalidWheelFilename(InstallationError):
  249. """Invalid wheel filename."""
  250. class UnsupportedWheel(InstallationError):
  251. """Unsupported wheel."""
  252. class InvalidWheel(InstallationError):
  253. """Invalid (e.g. corrupt) wheel."""
  254. def __init__(self, location: str, name: str):
  255. self.location = location
  256. self.name = name
  257. def __str__(self) -> str:
  258. return f"Wheel '{self.name}' located at {self.location} is invalid."
  259. class MetadataInconsistent(InstallationError):
  260. """Built metadata contains inconsistent information.
  261. This is raised when the metadata contains values (e.g. name and version)
  262. that do not match the information previously obtained from sdist filename,
  263. user-supplied ``#egg=`` value, or an install requirement name.
  264. """
  265. def __init__(
  266. self, ireq: InstallRequirement, field: str, f_val: str, m_val: str
  267. ) -> None:
  268. self.ireq = ireq
  269. self.field = field
  270. self.f_val = f_val
  271. self.m_val = m_val
  272. def __str__(self) -> str:
  273. return (
  274. f"Requested {self.ireq} has inconsistent {self.field}: "
  275. f"expected {self.f_val!r}, but metadata has {self.m_val!r}"
  276. )
  277. class MetadataInvalid(InstallationError):
  278. """Metadata is invalid."""
  279. def __init__(self, ireq: InstallRequirement, error: str) -> None:
  280. self.ireq = ireq
  281. self.error = error
  282. def __str__(self) -> str:
  283. return f"Requested {self.ireq} has invalid metadata: {self.error}"
  284. class InstallationSubprocessError(DiagnosticPipError, InstallationError):
  285. """A subprocess call failed."""
  286. reference = "subprocess-exited-with-error"
  287. def __init__(
  288. self,
  289. *,
  290. command_description: str,
  291. exit_code: int,
  292. output_lines: list[str] | None,
  293. ) -> None:
  294. if output_lines is None:
  295. output_prompt = Text("See above for output.")
  296. else:
  297. output_prompt = (
  298. Text.from_markup(f"[red][{len(output_lines)} lines of output][/]\n")
  299. + Text("".join(output_lines))
  300. + Text.from_markup(R"[red]\[end of output][/]")
  301. )
  302. super().__init__(
  303. message=(
  304. f"[green]{escape(command_description)}[/] did not run successfully.\n"
  305. f"exit code: {exit_code}"
  306. ),
  307. context=output_prompt,
  308. hint_stmt=None,
  309. note_stmt=(
  310. "This error originates from a subprocess, and is likely not a "
  311. "problem with pip."
  312. ),
  313. )
  314. self.command_description = command_description
  315. self.exit_code = exit_code
  316. def __str__(self) -> str:
  317. return f"{self.command_description} exited with {self.exit_code}"
  318. class MetadataGenerationFailed(InstallationSubprocessError, InstallationError):
  319. reference = "metadata-generation-failed"
  320. def __init__(
  321. self,
  322. *,
  323. package_details: str,
  324. ) -> None:
  325. super(InstallationSubprocessError, self).__init__(
  326. message="Encountered error while generating package metadata.",
  327. context=escape(package_details),
  328. hint_stmt="See above for details.",
  329. note_stmt="This is an issue with the package mentioned above, not pip.",
  330. )
  331. def __str__(self) -> str:
  332. return "metadata generation failed"
  333. class HashErrors(InstallationError):
  334. """Multiple HashError instances rolled into one for reporting"""
  335. def __init__(self) -> None:
  336. self.errors: list[HashError] = []
  337. def append(self, error: HashError) -> None:
  338. self.errors.append(error)
  339. def __str__(self) -> str:
  340. lines = []
  341. self.errors.sort(key=lambda e: e.order)
  342. for cls, errors_of_cls in groupby(self.errors, lambda e: e.__class__):
  343. lines.append(cls.head)
  344. lines.extend(e.body() for e in errors_of_cls)
  345. if lines:
  346. return "\n".join(lines)
  347. return ""
  348. def __bool__(self) -> bool:
  349. return bool(self.errors)
  350. class HashError(InstallationError):
  351. """
  352. A failure to verify a package against known-good hashes
  353. :cvar order: An int sorting hash exception classes by difficulty of
  354. recovery (lower being harder), so the user doesn't bother fretting
  355. about unpinned packages when he has deeper issues, like VCS
  356. dependencies, to deal with. Also keeps error reports in a
  357. deterministic order.
  358. :cvar head: A section heading for display above potentially many
  359. exceptions of this kind
  360. :ivar req: The InstallRequirement that triggered this error. This is
  361. pasted on after the exception is instantiated, because it's not
  362. typically available earlier.
  363. """
  364. req: InstallRequirement | None = None
  365. head = ""
  366. order: int = -1
  367. def body(self) -> str:
  368. """Return a summary of me for display under the heading.
  369. This default implementation simply prints a description of the
  370. triggering requirement.
  371. :param req: The InstallRequirement that provoked this error, with
  372. its link already populated by the resolver's _populate_link().
  373. """
  374. return f" {self._requirement_name()}"
  375. def __str__(self) -> str:
  376. return f"{self.head}\n{self.body()}"
  377. def _requirement_name(self) -> str:
  378. """Return a description of the requirement that triggered me.
  379. This default implementation returns long description of the req, with
  380. line numbers
  381. """
  382. return str(self.req) if self.req else "unknown package"
  383. class VcsHashUnsupported(HashError):
  384. """A hash was provided for a version-control-system-based requirement, but
  385. we don't have a method for hashing those."""
  386. order = 0
  387. head = (
  388. "Can't verify hashes for these requirements because we don't "
  389. "have a way to hash version control repositories:"
  390. )
  391. class DirectoryUrlHashUnsupported(HashError):
  392. """A hash was provided for a version-control-system-based requirement, but
  393. we don't have a method for hashing those."""
  394. order = 1
  395. head = (
  396. "Can't verify hashes for these file:// requirements because they "
  397. "point to directories:"
  398. )
  399. class HashMissing(HashError):
  400. """A hash was needed for a requirement but is absent."""
  401. order = 2
  402. head = (
  403. "Hashes are required in --require-hashes mode, but they are "
  404. "missing from some requirements. Here is a list of those "
  405. "requirements along with the hashes their downloaded archives "
  406. "actually had. Add lines like these to your requirements files to "
  407. "prevent tampering. (If you did not enable --require-hashes "
  408. "manually, note that it turns on automatically when any package "
  409. "has a hash.)"
  410. )
  411. def __init__(self, gotten_hash: str) -> None:
  412. """
  413. :param gotten_hash: The hash of the (possibly malicious) archive we
  414. just downloaded
  415. """
  416. self.gotten_hash = gotten_hash
  417. def body(self) -> str:
  418. # Dodge circular import.
  419. from pip._internal.utils.hashes import FAVORITE_HASH
  420. package = None
  421. if self.req:
  422. # In the case of URL-based requirements, display the original URL
  423. # seen in the requirements file rather than the package name,
  424. # so the output can be directly copied into the requirements file.
  425. package = (
  426. self.req.original_link
  427. if self.req.is_direct
  428. # In case someone feeds something downright stupid
  429. # to InstallRequirement's constructor.
  430. else getattr(self.req, "req", None)
  431. )
  432. return " {} --hash={}:{}".format(
  433. package or "unknown package", FAVORITE_HASH, self.gotten_hash
  434. )
  435. class HashUnpinned(HashError):
  436. """A requirement had a hash specified but was not pinned to a specific
  437. version."""
  438. order = 3
  439. head = (
  440. "In --require-hashes mode, all requirements must have their "
  441. "versions pinned with ==. These do not:"
  442. )
  443. class HashMismatch(HashError):
  444. """
  445. Distribution file hash values don't match.
  446. :ivar package_name: The name of the package that triggered the hash
  447. mismatch. Feel free to write to this after the exception is raise to
  448. improve its error message.
  449. """
  450. order = 4
  451. head = (
  452. "THESE PACKAGES DO NOT MATCH THE HASHES FROM THE REQUIREMENTS "
  453. "FILE. If you have updated the package versions, please update "
  454. "the hashes. Otherwise, examine the package contents carefully; "
  455. "someone may have tampered with them."
  456. )
  457. def __init__(self, allowed: dict[str, list[str]], gots: dict[str, _Hash]) -> None:
  458. """
  459. :param allowed: A dict of algorithm names pointing to lists of allowed
  460. hex digests
  461. :param gots: A dict of algorithm names pointing to hashes we
  462. actually got from the files under suspicion
  463. """
  464. self.allowed = allowed
  465. self.gots = gots
  466. def body(self) -> str:
  467. return f" {self._requirement_name()}:\n{self._hash_comparison()}"
  468. def _hash_comparison(self) -> str:
  469. """
  470. Return a comparison of actual and expected hash values.
  471. Example::
  472. Expected sha256 abcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcde
  473. or 123451234512345123451234512345123451234512345
  474. Got bcdefbcdefbcdefbcdefbcdefbcdefbcdefbcdefbcdef
  475. """
  476. def hash_then_or(hash_name: str) -> chain[str]:
  477. # For now, all the decent hashes have 6-char names, so we can get
  478. # away with hard-coding space literals.
  479. return chain([hash_name], repeat(" or"))
  480. lines: list[str] = []
  481. for hash_name, expecteds in self.allowed.items():
  482. prefix = hash_then_or(hash_name)
  483. lines.extend((f" Expected {next(prefix)} {e}") for e in expecteds)
  484. lines.append(
  485. f" Got {self.gots[hash_name].hexdigest()}\n"
  486. )
  487. return "\n".join(lines)
  488. class UnsupportedPythonVersion(InstallationError):
  489. """Unsupported python version according to Requires-Python package
  490. metadata."""
  491. class ConfigurationFileCouldNotBeLoaded(ConfigurationError):
  492. """When there are errors while loading a configuration file"""
  493. def __init__(
  494. self,
  495. reason: str = "could not be loaded",
  496. fname: str | None = None,
  497. error: configparser.Error | None = None,
  498. ) -> None:
  499. super().__init__(error)
  500. self.reason = reason
  501. self.fname = fname
  502. self.error = error
  503. def __str__(self) -> str:
  504. if self.fname is not None:
  505. message_part = f" in {self.fname}."
  506. else:
  507. assert self.error is not None
  508. message_part = f".\n{self.error}\n"
  509. return f"Configuration file {self.reason}{message_part}"
  510. _DEFAULT_EXTERNALLY_MANAGED_ERROR = f"""\
  511. The Python environment under {sys.prefix} is managed externally, and may not be
  512. manipulated by the user. Please use specific tooling from the distributor of
  513. the Python installation to interact with this environment instead.
  514. """
  515. class ExternallyManagedEnvironment(DiagnosticPipError):
  516. """The current environment is externally managed.
  517. This is raised when the current environment is externally managed, as
  518. defined by `PEP 668`_. The ``EXTERNALLY-MANAGED`` configuration is checked
  519. and displayed when the error is bubbled up to the user.
  520. :param error: The error message read from ``EXTERNALLY-MANAGED``.
  521. """
  522. reference = "externally-managed-environment"
  523. def __init__(self, error: str | None) -> None:
  524. if error is None:
  525. context = Text(_DEFAULT_EXTERNALLY_MANAGED_ERROR)
  526. else:
  527. context = Text(error)
  528. super().__init__(
  529. message="This environment is externally managed",
  530. context=context,
  531. note_stmt=(
  532. "If you believe this is a mistake, please contact your "
  533. "Python installation or OS distribution provider. "
  534. "You can override this, at the risk of breaking your Python "
  535. "installation or OS, by passing --break-system-packages."
  536. ),
  537. hint_stmt=Text("See PEP 668 for the detailed specification."),
  538. )
  539. @staticmethod
  540. def _iter_externally_managed_error_keys() -> Iterator[str]:
  541. # LC_MESSAGES is in POSIX, but not the C standard. The most common
  542. # platform that does not implement this category is Windows, where
  543. # using other categories for console message localization is equally
  544. # unreliable, so we fall back to the locale-less vendor message. This
  545. # can always be re-evaluated when a vendor proposes a new alternative.
  546. try:
  547. category = locale.LC_MESSAGES
  548. except AttributeError:
  549. lang: str | None = None
  550. else:
  551. lang, _ = locale.getlocale(category)
  552. if lang is not None:
  553. yield f"Error-{lang}"
  554. for sep in ("-", "_"):
  555. before, found, _ = lang.partition(sep)
  556. if not found:
  557. continue
  558. yield f"Error-{before}"
  559. yield "Error"
  560. @classmethod
  561. def from_config(
  562. cls,
  563. config: pathlib.Path | str,
  564. ) -> ExternallyManagedEnvironment:
  565. parser = configparser.ConfigParser(interpolation=None)
  566. try:
  567. parser.read(config, encoding="utf-8")
  568. section = parser["externally-managed"]
  569. for key in cls._iter_externally_managed_error_keys():
  570. with contextlib.suppress(KeyError):
  571. return cls(section[key])
  572. except KeyError:
  573. pass
  574. except (OSError, UnicodeDecodeError, configparser.ParsingError):
  575. from pip._internal.utils._log import VERBOSE
  576. exc_info = logger.isEnabledFor(VERBOSE)
  577. logger.warning("Failed to read %s", config, exc_info=exc_info)
  578. return cls(None)
  579. class UninstallMissingRecord(DiagnosticPipError):
  580. reference = "uninstall-no-record-file"
  581. def __init__(self, *, distribution: BaseDistribution) -> None:
  582. installer = distribution.installer
  583. if not installer or installer == "pip":
  584. dep = f"{distribution.raw_name}=={distribution.version}"
  585. hint = Text.assemble(
  586. "You might be able to recover from this via: ",
  587. (f"pip install --force-reinstall --no-deps {dep}", "green"),
  588. )
  589. else:
  590. hint = Text(
  591. f"The package was installed by {installer}. "
  592. "You should check if it can uninstall the package."
  593. )
  594. super().__init__(
  595. message=Text(f"Cannot uninstall {distribution}"),
  596. context=(
  597. "The package's contents are unknown: "
  598. f"no RECORD file was found for {distribution.raw_name}."
  599. ),
  600. hint_stmt=hint,
  601. )
  602. class LegacyDistutilsInstall(DiagnosticPipError):
  603. reference = "uninstall-distutils-installed-package"
  604. def __init__(self, *, distribution: BaseDistribution) -> None:
  605. super().__init__(
  606. message=Text(f"Cannot uninstall {distribution}"),
  607. context=(
  608. "It is a distutils installed project and thus we cannot accurately "
  609. "determine which files belong to it which would lead to only a partial "
  610. "uninstall."
  611. ),
  612. hint_stmt=None,
  613. )
  614. class InvalidInstalledPackage(DiagnosticPipError):
  615. reference = "invalid-installed-package"
  616. def __init__(
  617. self,
  618. *,
  619. dist: BaseDistribution,
  620. invalid_exc: InvalidRequirement | InvalidVersion,
  621. ) -> None:
  622. installed_location = dist.installed_location
  623. if isinstance(invalid_exc, InvalidRequirement):
  624. invalid_type = "requirement"
  625. else:
  626. invalid_type = "version"
  627. super().__init__(
  628. message=Text(
  629. f"Cannot process installed package {dist} "
  630. + (f"in {installed_location!r} " if installed_location else "")
  631. + f"because it has an invalid {invalid_type}:\n{invalid_exc.args[0]}"
  632. ),
  633. context=(
  634. "Starting with pip 24.1, packages with invalid "
  635. f"{invalid_type}s can not be processed."
  636. ),
  637. hint_stmt="To proceed this package must be uninstalled.",
  638. )
  639. class IncompleteDownloadError(DiagnosticPipError):
  640. """Raised when the downloader receives fewer bytes than advertised
  641. in the Content-Length header."""
  642. reference = "incomplete-download"
  643. def __init__(self, download: _FileDownload) -> None:
  644. # Dodge circular import.
  645. from pip._internal.utils.misc import format_size
  646. assert download.size is not None
  647. download_status = (
  648. f"{format_size(download.bytes_received)}/{format_size(download.size)}"
  649. )
  650. if download.reattempts:
  651. retry_status = f"after {download.reattempts + 1} attempts "
  652. hint = "Use --resume-retries to configure resume attempt limit."
  653. else:
  654. # Download retrying is not enabled.
  655. retry_status = ""
  656. hint = "Consider using --resume-retries to enable download resumption."
  657. message = Text(
  658. f"Download failed {retry_status}because not enough bytes "
  659. f"were received ({download_status})"
  660. )
  661. super().__init__(
  662. message=message,
  663. context=f"URL: {download.link.redacted_url}",
  664. hint_stmt=hint,
  665. note_stmt="This is an issue with network connectivity, not pip.",
  666. )
  667. class ResolutionTooDeepError(DiagnosticPipError):
  668. """Raised when the dependency resolver exceeds the maximum recursion depth."""
  669. reference = "resolution-too-deep"
  670. def __init__(self) -> None:
  671. super().__init__(
  672. message="Dependency resolution exceeded maximum depth",
  673. context=(
  674. "Pip cannot resolve the current dependencies as the dependency graph "
  675. "is too complex for pip to solve efficiently."
  676. ),
  677. hint_stmt=(
  678. "Try adding lower bounds to constrain your dependencies, "
  679. "for example: 'package>=2.0.0' instead of just 'package'. "
  680. ),
  681. link="https://pip.pypa.io/en/stable/topics/dependency-resolution/#handling-resolution-too-deep-errors",
  682. )
  683. class InstallWheelBuildError(DiagnosticPipError):
  684. reference = "failed-wheel-build-for-install"
  685. def __init__(self, failed: list[InstallRequirement]) -> None:
  686. super().__init__(
  687. message=(
  688. "Failed to build installable wheels for some "
  689. "pyproject.toml based projects"
  690. ),
  691. context=", ".join(r.name for r in failed), # type: ignore
  692. hint_stmt=None,
  693. )