m2m模型翻译
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

728 lines
23 KiB

7 months ago
  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 f"None {self.metadata_name} metadata found for distribution: {self.dist}"
  201. class UserInstallationInvalid(InstallationError):
  202. """A --user install is requested on an environment without user site."""
  203. def __str__(self) -> str:
  204. return "User base directory is not specified"
  205. class InvalidSchemeCombination(InstallationError):
  206. def __str__(self) -> str:
  207. before = ", ".join(str(a) for a in self.args[:-1])
  208. return f"Cannot set {before} and {self.args[-1]} together"
  209. class DistributionNotFound(InstallationError):
  210. """Raised when a distribution cannot be found to satisfy a requirement"""
  211. class RequirementsFileParseError(InstallationError):
  212. """Raised when a general error occurs parsing a requirements file line."""
  213. class BestVersionAlreadyInstalled(PipError):
  214. """Raised when the most up-to-date version of a package is already
  215. installed."""
  216. class BadCommand(PipError):
  217. """Raised when virtualenv or a command is not found"""
  218. class CommandError(PipError):
  219. """Raised when there is an error in command-line arguments"""
  220. class PreviousBuildDirError(PipError):
  221. """Raised when there's a previous conflicting build directory"""
  222. class NetworkConnectionError(PipError):
  223. """HTTP connection error"""
  224. def __init__(
  225. self,
  226. error_msg: str,
  227. response: Optional[Response] = None,
  228. request: Optional[Request] = None,
  229. ) -> None:
  230. """
  231. Initialize NetworkConnectionError with `request` and `response`
  232. objects.
  233. """
  234. self.response = response
  235. self.request = request
  236. self.error_msg = error_msg
  237. if (
  238. self.response is not None
  239. and not self.request
  240. and hasattr(response, "request")
  241. ):
  242. self.request = self.response.request
  243. super().__init__(error_msg, response, request)
  244. def __str__(self) -> str:
  245. return str(self.error_msg)
  246. class InvalidWheelFilename(InstallationError):
  247. """Invalid wheel filename."""
  248. class UnsupportedWheel(InstallationError):
  249. """Unsupported wheel."""
  250. class InvalidWheel(InstallationError):
  251. """Invalid (e.g. corrupt) wheel."""
  252. def __init__(self, location: str, name: str):
  253. self.location = location
  254. self.name = name
  255. def __str__(self) -> str:
  256. return f"Wheel '{self.name}' located at {self.location} is invalid."
  257. class MetadataInconsistent(InstallationError):
  258. """Built metadata contains inconsistent information.
  259. This is raised when the metadata contains values (e.g. name and version)
  260. that do not match the information previously obtained from sdist filename,
  261. user-supplied ``#egg=`` value, or an install requirement name.
  262. """
  263. def __init__(
  264. self, ireq: "InstallRequirement", field: str, f_val: str, m_val: str
  265. ) -> None:
  266. self.ireq = ireq
  267. self.field = field
  268. self.f_val = f_val
  269. self.m_val = m_val
  270. def __str__(self) -> str:
  271. return (
  272. f"Requested {self.ireq} has inconsistent {self.field}: "
  273. f"expected {self.f_val!r}, but metadata has {self.m_val!r}"
  274. )
  275. class InstallationSubprocessError(DiagnosticPipError, InstallationError):
  276. """A subprocess call failed."""
  277. reference = "subprocess-exited-with-error"
  278. def __init__(
  279. self,
  280. *,
  281. command_description: str,
  282. exit_code: int,
  283. output_lines: Optional[List[str]],
  284. ) -> None:
  285. if output_lines is None:
  286. output_prompt = Text("See above for output.")
  287. else:
  288. output_prompt = (
  289. Text.from_markup(f"[red][{len(output_lines)} lines of output][/]\n")
  290. + Text("".join(output_lines))
  291. + Text.from_markup(R"[red]\[end of output][/]")
  292. )
  293. super().__init__(
  294. message=(
  295. f"[green]{escape(command_description)}[/] did not run successfully.\n"
  296. f"exit code: {exit_code}"
  297. ),
  298. context=output_prompt,
  299. hint_stmt=None,
  300. note_stmt=(
  301. "This error originates from a subprocess, and is likely not a "
  302. "problem with pip."
  303. ),
  304. )
  305. self.command_description = command_description
  306. self.exit_code = exit_code
  307. def __str__(self) -> str:
  308. return f"{self.command_description} exited with {self.exit_code}"
  309. class MetadataGenerationFailed(InstallationSubprocessError, InstallationError):
  310. reference = "metadata-generation-failed"
  311. def __init__(
  312. self,
  313. *,
  314. package_details: str,
  315. ) -> None:
  316. super(InstallationSubprocessError, self).__init__(
  317. message="Encountered error while generating package metadata.",
  318. context=escape(package_details),
  319. hint_stmt="See above for details.",
  320. note_stmt="This is an issue with the package mentioned above, not pip.",
  321. )
  322. def __str__(self) -> str:
  323. return "metadata generation failed"
  324. class HashErrors(InstallationError):
  325. """Multiple HashError instances rolled into one for reporting"""
  326. def __init__(self) -> None:
  327. self.errors: List["HashError"] = []
  328. def append(self, error: "HashError") -> None:
  329. self.errors.append(error)
  330. def __str__(self) -> str:
  331. lines = []
  332. self.errors.sort(key=lambda e: e.order)
  333. for cls, errors_of_cls in groupby(self.errors, lambda e: e.__class__):
  334. lines.append(cls.head)
  335. lines.extend(e.body() for e in errors_of_cls)
  336. if lines:
  337. return "\n".join(lines)
  338. return ""
  339. def __bool__(self) -> bool:
  340. return bool(self.errors)
  341. class HashError(InstallationError):
  342. """
  343. A failure to verify a package against known-good hashes
  344. :cvar order: An int sorting hash exception classes by difficulty of
  345. recovery (lower being harder), so the user doesn't bother fretting
  346. about unpinned packages when he has deeper issues, like VCS
  347. dependencies, to deal with. Also keeps error reports in a
  348. deterministic order.
  349. :cvar head: A section heading for display above potentially many
  350. exceptions of this kind
  351. :ivar req: The InstallRequirement that triggered this error. This is
  352. pasted on after the exception is instantiated, because it's not
  353. typically available earlier.
  354. """
  355. req: Optional["InstallRequirement"] = None
  356. head = ""
  357. order: int = -1
  358. def body(self) -> str:
  359. """Return a summary of me for display under the heading.
  360. This default implementation simply prints a description of the
  361. triggering requirement.
  362. :param req: The InstallRequirement that provoked this error, with
  363. its link already populated by the resolver's _populate_link().
  364. """
  365. return f" {self._requirement_name()}"
  366. def __str__(self) -> str:
  367. return f"{self.head}\n{self.body()}"
  368. def _requirement_name(self) -> str:
  369. """Return a description of the requirement that triggered me.
  370. This default implementation returns long description of the req, with
  371. line numbers
  372. """
  373. return str(self.req) if self.req else "unknown package"
  374. class VcsHashUnsupported(HashError):
  375. """A hash was provided for a version-control-system-based requirement, but
  376. we don't have a method for hashing those."""
  377. order = 0
  378. head = (
  379. "Can't verify hashes for these requirements because we don't "
  380. "have a way to hash version control repositories:"
  381. )
  382. class DirectoryUrlHashUnsupported(HashError):
  383. """A hash was provided for a version-control-system-based requirement, but
  384. we don't have a method for hashing those."""
  385. order = 1
  386. head = (
  387. "Can't verify hashes for these file:// requirements because they "
  388. "point to directories:"
  389. )
  390. class HashMissing(HashError):
  391. """A hash was needed for a requirement but is absent."""
  392. order = 2
  393. head = (
  394. "Hashes are required in --require-hashes mode, but they are "
  395. "missing from some requirements. Here is a list of those "
  396. "requirements along with the hashes their downloaded archives "
  397. "actually had. Add lines like these to your requirements files to "
  398. "prevent tampering. (If you did not enable --require-hashes "
  399. "manually, note that it turns on automatically when any package "
  400. "has a hash.)"
  401. )
  402. def __init__(self, gotten_hash: str) -> None:
  403. """
  404. :param gotten_hash: The hash of the (possibly malicious) archive we
  405. just downloaded
  406. """
  407. self.gotten_hash = gotten_hash
  408. def body(self) -> str:
  409. # Dodge circular import.
  410. from pip._internal.utils.hashes import FAVORITE_HASH
  411. package = None
  412. if self.req:
  413. # In the case of URL-based requirements, display the original URL
  414. # seen in the requirements file rather than the package name,
  415. # so the output can be directly copied into the requirements file.
  416. package = (
  417. self.req.original_link
  418. if self.req.is_direct
  419. # In case someone feeds something downright stupid
  420. # to InstallRequirement's constructor.
  421. else getattr(self.req, "req", None)
  422. )
  423. return " {} --hash={}:{}".format(
  424. package or "unknown package", FAVORITE_HASH, self.gotten_hash
  425. )
  426. class HashUnpinned(HashError):
  427. """A requirement had a hash specified but was not pinned to a specific
  428. version."""
  429. order = 3
  430. head = (
  431. "In --require-hashes mode, all requirements must have their "
  432. "versions pinned with ==. These do not:"
  433. )
  434. class HashMismatch(HashError):
  435. """
  436. Distribution file hash values don't match.
  437. :ivar package_name: The name of the package that triggered the hash
  438. mismatch. Feel free to write to this after the exception is raise to
  439. improve its error message.
  440. """
  441. order = 4
  442. head = (
  443. "THESE PACKAGES DO NOT MATCH THE HASHES FROM THE REQUIREMENTS "
  444. "FILE. If you have updated the package versions, please update "
  445. "the hashes. Otherwise, examine the package contents carefully; "
  446. "someone may have tampered with them."
  447. )
  448. def __init__(self, allowed: Dict[str, List[str]], gots: Dict[str, "_Hash"]) -> None:
  449. """
  450. :param allowed: A dict of algorithm names pointing to lists of allowed
  451. hex digests
  452. :param gots: A dict of algorithm names pointing to hashes we
  453. actually got from the files under suspicion
  454. """
  455. self.allowed = allowed
  456. self.gots = gots
  457. def body(self) -> str:
  458. return f" {self._requirement_name()}:\n{self._hash_comparison()}"
  459. def _hash_comparison(self) -> str:
  460. """
  461. Return a comparison of actual and expected hash values.
  462. Example::
  463. Expected sha256 abcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcde
  464. or 123451234512345123451234512345123451234512345
  465. Got bcdefbcdefbcdefbcdefbcdefbcdefbcdefbcdefbcdef
  466. """
  467. def hash_then_or(hash_name: str) -> "chain[str]":
  468. # For now, all the decent hashes have 6-char names, so we can get
  469. # away with hard-coding space literals.
  470. return chain([hash_name], repeat(" or"))
  471. lines: List[str] = []
  472. for hash_name, expecteds in self.allowed.items():
  473. prefix = hash_then_or(hash_name)
  474. lines.extend((f" Expected {next(prefix)} {e}") for e in expecteds)
  475. lines.append(
  476. f" Got {self.gots[hash_name].hexdigest()}\n"
  477. )
  478. return "\n".join(lines)
  479. class UnsupportedPythonVersion(InstallationError):
  480. """Unsupported python version according to Requires-Python package
  481. metadata."""
  482. class ConfigurationFileCouldNotBeLoaded(ConfigurationError):
  483. """When there are errors while loading a configuration file"""
  484. def __init__(
  485. self,
  486. reason: str = "could not be loaded",
  487. fname: Optional[str] = None,
  488. error: Optional[configparser.Error] = None,
  489. ) -> None:
  490. super().__init__(error)
  491. self.reason = reason
  492. self.fname = fname
  493. self.error = error
  494. def __str__(self) -> str:
  495. if self.fname is not None:
  496. message_part = f" in {self.fname}."
  497. else:
  498. assert self.error is not None
  499. message_part = f".\n{self.error}\n"
  500. return f"Configuration file {self.reason}{message_part}"
  501. _DEFAULT_EXTERNALLY_MANAGED_ERROR = f"""\
  502. The Python environment under {sys.prefix} is managed externally, and may not be
  503. manipulated by the user. Please use specific tooling from the distributor of
  504. the Python installation to interact with this environment instead.
  505. """
  506. class ExternallyManagedEnvironment(DiagnosticPipError):
  507. """The current environment is externally managed.
  508. This is raised when the current environment is externally managed, as
  509. defined by `PEP 668`_. The ``EXTERNALLY-MANAGED`` configuration is checked
  510. and displayed when the error is bubbled up to the user.
  511. :param error: The error message read from ``EXTERNALLY-MANAGED``.
  512. """
  513. reference = "externally-managed-environment"
  514. def __init__(self, error: Optional[str]) -> None:
  515. if error is None:
  516. context = Text(_DEFAULT_EXTERNALLY_MANAGED_ERROR)
  517. else:
  518. context = Text(error)
  519. super().__init__(
  520. message="This environment is externally managed",
  521. context=context,
  522. note_stmt=(
  523. "If you believe this is a mistake, please contact your "
  524. "Python installation or OS distribution provider. "
  525. "You can override this, at the risk of breaking your Python "
  526. "installation or OS, by passing --break-system-packages."
  527. ),
  528. hint_stmt=Text("See PEP 668 for the detailed specification."),
  529. )
  530. @staticmethod
  531. def _iter_externally_managed_error_keys() -> Iterator[str]:
  532. # LC_MESSAGES is in POSIX, but not the C standard. The most common
  533. # platform that does not implement this category is Windows, where
  534. # using other categories for console message localization is equally
  535. # unreliable, so we fall back to the locale-less vendor message. This
  536. # can always be re-evaluated when a vendor proposes a new alternative.
  537. try:
  538. category = locale.LC_MESSAGES
  539. except AttributeError:
  540. lang: Optional[str] = None
  541. else:
  542. lang, _ = locale.getlocale(category)
  543. if lang is not None:
  544. yield f"Error-{lang}"
  545. for sep in ("-", "_"):
  546. before, found, _ = lang.partition(sep)
  547. if not found:
  548. continue
  549. yield f"Error-{before}"
  550. yield "Error"
  551. @classmethod
  552. def from_config(
  553. cls,
  554. config: Union[pathlib.Path, str],
  555. ) -> "ExternallyManagedEnvironment":
  556. parser = configparser.ConfigParser(interpolation=None)
  557. try:
  558. parser.read(config, encoding="utf-8")
  559. section = parser["externally-managed"]
  560. for key in cls._iter_externally_managed_error_keys():
  561. with contextlib.suppress(KeyError):
  562. return cls(section[key])
  563. except KeyError:
  564. pass
  565. except (OSError, UnicodeDecodeError, configparser.ParsingError):
  566. from pip._internal.utils._log import VERBOSE
  567. exc_info = logger.isEnabledFor(VERBOSE)
  568. logger.warning("Failed to read %s", config, exc_info=exc_info)
  569. return cls(None)