exceptions.py 31 KB

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