exceptions.py 20 KB

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