exceptions.py 13 KB

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