exceptions.py 13 KB

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