exceptions.py 23 KB

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