exceptions.py 25 KB

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