exceptions.py 26 KB

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