exceptions.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  1. """Exceptions used throughout package"""
  2. import configparser
  3. from itertools import chain, groupby, repeat
  4. from typing import TYPE_CHECKING, Dict, List, Optional, Union
  5. from pip._vendor.pkg_resources import Distribution
  6. from pip._vendor.requests.models import Request, Response
  7. if TYPE_CHECKING:
  8. from hashlib import _Hash
  9. from pip._internal.metadata import BaseDistribution
  10. from pip._internal.req.req_install import InstallRequirement
  11. class PipError(Exception):
  12. """Base pip exception"""
  13. class ConfigurationError(PipError):
  14. """General exception in configuration"""
  15. class InstallationError(PipError):
  16. """General exception during installation"""
  17. class UninstallationError(PipError):
  18. """General exception during uninstallation"""
  19. class NoneMetadataError(PipError):
  20. """
  21. Raised when accessing "METADATA" or "PKG-INFO" metadata for a
  22. pip._vendor.pkg_resources.Distribution object and
  23. `dist.has_metadata('METADATA')` returns True but
  24. `dist.get_metadata('METADATA')` returns None (and similarly for
  25. "PKG-INFO").
  26. """
  27. def __init__(
  28. self,
  29. dist: Union[Distribution, "BaseDistribution"],
  30. metadata_name: str,
  31. ) -> None:
  32. """
  33. :param dist: A Distribution object.
  34. :param metadata_name: The name of the metadata being accessed
  35. (can be "METADATA" or "PKG-INFO").
  36. """
  37. self.dist = dist
  38. self.metadata_name = metadata_name
  39. def __str__(self) -> str:
  40. # Use `dist` in the error message because its stringification
  41. # includes more information, like the version and location.
  42. return "None {} metadata found for distribution: {}".format(
  43. self.metadata_name,
  44. self.dist,
  45. )
  46. class UserInstallationInvalid(InstallationError):
  47. """A --user install is requested on an environment without user site."""
  48. def __str__(self) -> str:
  49. return "User base directory is not specified"
  50. class InvalidSchemeCombination(InstallationError):
  51. def __str__(self) -> str:
  52. before = ", ".join(str(a) for a in self.args[:-1])
  53. return f"Cannot set {before} and {self.args[-1]} together"
  54. class DistributionNotFound(InstallationError):
  55. """Raised when a distribution cannot be found to satisfy a requirement"""
  56. class RequirementsFileParseError(InstallationError):
  57. """Raised when a general error occurs parsing a requirements file line."""
  58. class BestVersionAlreadyInstalled(PipError):
  59. """Raised when the most up-to-date version of a package is already
  60. installed."""
  61. class BadCommand(PipError):
  62. """Raised when virtualenv or a command is not found"""
  63. class CommandError(PipError):
  64. """Raised when there is an error in command-line arguments"""
  65. class PreviousBuildDirError(PipError):
  66. """Raised when there's a previous conflicting build directory"""
  67. class NetworkConnectionError(PipError):
  68. """HTTP connection error"""
  69. def __init__(
  70. self, error_msg: str, response: Response = None, request: Request = None
  71. ) -> None:
  72. """
  73. Initialize NetworkConnectionError with `request` and `response`
  74. objects.
  75. """
  76. self.response = response
  77. self.request = request
  78. self.error_msg = error_msg
  79. if (
  80. self.response is not None
  81. and not self.request
  82. and hasattr(response, "request")
  83. ):
  84. self.request = self.response.request
  85. super().__init__(error_msg, response, request)
  86. def __str__(self) -> str:
  87. return str(self.error_msg)
  88. class InvalidWheelFilename(InstallationError):
  89. """Invalid wheel filename."""
  90. class UnsupportedWheel(InstallationError):
  91. """Unsupported wheel."""
  92. class MetadataInconsistent(InstallationError):
  93. """Built metadata contains inconsistent information.
  94. This is raised when the metadata contains values (e.g. name and version)
  95. that do not match the information previously obtained from sdist filename
  96. or user-supplied ``#egg=`` value.
  97. """
  98. def __init__(
  99. self, ireq: "InstallRequirement", field: str, f_val: str, m_val: str
  100. ) -> None:
  101. self.ireq = ireq
  102. self.field = field
  103. self.f_val = f_val
  104. self.m_val = m_val
  105. def __str__(self) -> str:
  106. template = (
  107. "Requested {} has inconsistent {}: "
  108. "filename has {!r}, but metadata has {!r}"
  109. )
  110. return template.format(self.ireq, self.field, self.f_val, self.m_val)
  111. class InstallationSubprocessError(InstallationError):
  112. """A subprocess call failed during installation."""
  113. def __init__(self, returncode: int, description: str) -> None:
  114. self.returncode = returncode
  115. self.description = description
  116. def __str__(self) -> str:
  117. return (
  118. "Command errored out with exit status {}: {} "
  119. "Check the logs for full command output."
  120. ).format(self.returncode, self.description)
  121. class HashErrors(InstallationError):
  122. """Multiple HashError instances rolled into one for reporting"""
  123. def __init__(self) -> None:
  124. self.errors: List["HashError"] = []
  125. def append(self, error: "HashError") -> None:
  126. self.errors.append(error)
  127. def __str__(self) -> str:
  128. lines = []
  129. self.errors.sort(key=lambda e: e.order)
  130. for cls, errors_of_cls in groupby(self.errors, lambda e: e.__class__):
  131. lines.append(cls.head)
  132. lines.extend(e.body() for e in errors_of_cls)
  133. if lines:
  134. return "\n".join(lines)
  135. return ""
  136. def __bool__(self) -> bool:
  137. return bool(self.errors)
  138. class HashError(InstallationError):
  139. """
  140. A failure to verify a package against known-good hashes
  141. :cvar order: An int sorting hash exception classes by difficulty of
  142. recovery (lower being harder), so the user doesn't bother fretting
  143. about unpinned packages when he has deeper issues, like VCS
  144. dependencies, to deal with. Also keeps error reports in a
  145. deterministic order.
  146. :cvar head: A section heading for display above potentially many
  147. exceptions of this kind
  148. :ivar req: The InstallRequirement that triggered this error. This is
  149. pasted on after the exception is instantiated, because it's not
  150. typically available earlier.
  151. """
  152. req: Optional["InstallRequirement"] = None
  153. head = ""
  154. order: int = -1
  155. def body(self) -> str:
  156. """Return a summary of me for display under the heading.
  157. This default implementation simply prints a description of the
  158. triggering requirement.
  159. :param req: The InstallRequirement that provoked this error, with
  160. its link already populated by the resolver's _populate_link().
  161. """
  162. return f" {self._requirement_name()}"
  163. def __str__(self) -> str:
  164. return f"{self.head}\n{self.body()}"
  165. def _requirement_name(self) -> str:
  166. """Return a description of the requirement that triggered me.
  167. This default implementation returns long description of the req, with
  168. line numbers
  169. """
  170. return str(self.req) if self.req else "unknown package"
  171. class VcsHashUnsupported(HashError):
  172. """A hash was provided for a version-control-system-based requirement, but
  173. we don't have a method for hashing those."""
  174. order = 0
  175. head = (
  176. "Can't verify hashes for these requirements because we don't "
  177. "have a way to hash version control repositories:"
  178. )
  179. class DirectoryUrlHashUnsupported(HashError):
  180. """A hash was provided for a version-control-system-based requirement, but
  181. we don't have a method for hashing those."""
  182. order = 1
  183. head = (
  184. "Can't verify hashes for these file:// requirements because they "
  185. "point to directories:"
  186. )
  187. class HashMissing(HashError):
  188. """A hash was needed for a requirement but is absent."""
  189. order = 2
  190. head = (
  191. "Hashes are required in --require-hashes mode, but they are "
  192. "missing from some requirements. Here is a list of those "
  193. "requirements along with the hashes their downloaded archives "
  194. "actually had. Add lines like these to your requirements files to "
  195. "prevent tampering. (If you did not enable --require-hashes "
  196. "manually, note that it turns on automatically when any package "
  197. "has a hash.)"
  198. )
  199. def __init__(self, gotten_hash: str) -> None:
  200. """
  201. :param gotten_hash: The hash of the (possibly malicious) archive we
  202. just downloaded
  203. """
  204. self.gotten_hash = gotten_hash
  205. def body(self) -> str:
  206. # Dodge circular import.
  207. from pip._internal.utils.hashes import FAVORITE_HASH
  208. package = None
  209. if self.req:
  210. # In the case of URL-based requirements, display the original URL
  211. # seen in the requirements file rather than the package name,
  212. # so the output can be directly copied into the requirements file.
  213. package = (
  214. self.req.original_link
  215. if self.req.original_link
  216. # In case someone feeds something downright stupid
  217. # to InstallRequirement's constructor.
  218. else getattr(self.req, "req", None)
  219. )
  220. return " {} --hash={}:{}".format(
  221. package or "unknown package", FAVORITE_HASH, self.gotten_hash
  222. )
  223. class HashUnpinned(HashError):
  224. """A requirement had a hash specified but was not pinned to a specific
  225. version."""
  226. order = 3
  227. head = (
  228. "In --require-hashes mode, all requirements must have their "
  229. "versions pinned with ==. These do not:"
  230. )
  231. class HashMismatch(HashError):
  232. """
  233. Distribution file hash values don't match.
  234. :ivar package_name: The name of the package that triggered the hash
  235. mismatch. Feel free to write to this after the exception is raise to
  236. improve its error message.
  237. """
  238. order = 4
  239. head = (
  240. "THESE PACKAGES DO NOT MATCH THE HASHES FROM THE REQUIREMENTS "
  241. "FILE. If you have updated the package versions, please update "
  242. "the hashes. Otherwise, examine the package contents carefully; "
  243. "someone may have tampered with them."
  244. )
  245. def __init__(self, allowed: Dict[str, List[str]], gots: Dict[str, "_Hash"]) -> None:
  246. """
  247. :param allowed: A dict of algorithm names pointing to lists of allowed
  248. hex digests
  249. :param gots: A dict of algorithm names pointing to hashes we
  250. actually got from the files under suspicion
  251. """
  252. self.allowed = allowed
  253. self.gots = gots
  254. def body(self) -> str:
  255. return " {}:\n{}".format(self._requirement_name(), self._hash_comparison())
  256. def _hash_comparison(self) -> str:
  257. """
  258. Return a comparison of actual and expected hash values.
  259. Example::
  260. Expected sha256 abcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcde
  261. or 123451234512345123451234512345123451234512345
  262. Got bcdefbcdefbcdefbcdefbcdefbcdefbcdefbcdefbcdef
  263. """
  264. def hash_then_or(hash_name: str) -> "chain[str]":
  265. # For now, all the decent hashes have 6-char names, so we can get
  266. # away with hard-coding space literals.
  267. return chain([hash_name], repeat(" or"))
  268. lines: List[str] = []
  269. for hash_name, expecteds in self.allowed.items():
  270. prefix = hash_then_or(hash_name)
  271. lines.extend(
  272. (" Expected {} {}".format(next(prefix), e)) for e in expecteds
  273. )
  274. lines.append(
  275. " Got {}\n".format(self.gots[hash_name].hexdigest())
  276. )
  277. return "\n".join(lines)
  278. class UnsupportedPythonVersion(InstallationError):
  279. """Unsupported python version according to Requires-Python package
  280. metadata."""
  281. class ConfigurationFileCouldNotBeLoaded(ConfigurationError):
  282. """When there are errors while loading a configuration file"""
  283. def __init__(
  284. self,
  285. reason: str = "could not be loaded",
  286. fname: Optional[str] = None,
  287. error: Optional[configparser.Error] = None,
  288. ) -> None:
  289. super().__init__(error)
  290. self.reason = reason
  291. self.fname = fname
  292. self.error = error
  293. def __str__(self) -> str:
  294. if self.fname is not None:
  295. message_part = f" in {self.fname}."
  296. else:
  297. assert self.error is not None
  298. message_part = f".\n{self.error}\n"
  299. return f"Configuration file {self.reason}{message_part}"