exceptions.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  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, Optional, List, Dict, Text
  8. from pip._vendor.pkg_resources import Distribution
  9. from pip._vendor.requests.models import Response, Request
  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 SubProcessError(PipError):
  63. """Raised when there is an error raised while executing a
  64. command in subprocess"""
  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: (Text, 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(NetworkConnectionError, self).__init__(
  82. error_msg, response, request)
  83. def __str__(self):
  84. # type: () -> str
  85. return str(self.error_msg)
  86. class InvalidWheelFilename(InstallationError):
  87. """Invalid wheel filename."""
  88. class UnsupportedWheel(InstallationError):
  89. """Unsupported wheel."""
  90. class MetadataInconsistent(InstallationError):
  91. """Built metadata contains inconsistent information.
  92. This is raised when the metadata contains values (e.g. name and version)
  93. that do not match the information previously obtained from sdist filename
  94. or user-supplied ``#egg=`` value.
  95. """
  96. def __init__(self, ireq, field, built):
  97. # type: (InstallRequirement, str, Any) -> None
  98. self.ireq = ireq
  99. self.field = field
  100. self.built = built
  101. def __str__(self):
  102. # type: () -> str
  103. return "Requested {} has different {} in metadata: {!r}".format(
  104. self.ireq, self.field, self.built,
  105. )
  106. class HashErrors(InstallationError):
  107. """Multiple HashError instances rolled into one for reporting"""
  108. def __init__(self):
  109. # type: () -> None
  110. self.errors = [] # type: List[HashError]
  111. def append(self, error):
  112. # type: (HashError) -> None
  113. self.errors.append(error)
  114. def __str__(self):
  115. # type: () -> str
  116. lines = []
  117. self.errors.sort(key=lambda e: e.order)
  118. for cls, errors_of_cls in groupby(self.errors, lambda e: e.__class__):
  119. lines.append(cls.head)
  120. lines.extend(e.body() for e in errors_of_cls)
  121. if lines:
  122. return '\n'.join(lines)
  123. return ''
  124. def __nonzero__(self):
  125. # type: () -> bool
  126. return bool(self.errors)
  127. def __bool__(self):
  128. # type: () -> bool
  129. return self.__nonzero__()
  130. class HashError(InstallationError):
  131. """
  132. A failure to verify a package against known-good hashes
  133. :cvar order: An int sorting hash exception classes by difficulty of
  134. recovery (lower being harder), so the user doesn't bother fretting
  135. about unpinned packages when he has deeper issues, like VCS
  136. dependencies, to deal with. Also keeps error reports in a
  137. deterministic order.
  138. :cvar head: A section heading for display above potentially many
  139. exceptions of this kind
  140. :ivar req: The InstallRequirement that triggered this error. This is
  141. pasted on after the exception is instantiated, because it's not
  142. typically available earlier.
  143. """
  144. req = None # type: Optional[InstallRequirement]
  145. head = ''
  146. order = None # type: Optional[int]
  147. def body(self):
  148. # type: () -> str
  149. """Return a summary of me for display under the heading.
  150. This default implementation simply prints a description of the
  151. triggering requirement.
  152. :param req: The InstallRequirement that provoked this error, with
  153. its link already populated by the resolver's _populate_link().
  154. """
  155. return ' {}'.format(self._requirement_name())
  156. def __str__(self):
  157. # type: () -> str
  158. return '{}\n{}'.format(self.head, self.body())
  159. def _requirement_name(self):
  160. # type: () -> str
  161. """Return a description of the requirement that triggered me.
  162. This default implementation returns long description of the req, with
  163. line numbers
  164. """
  165. return str(self.req) if self.req else 'unknown package'
  166. class VcsHashUnsupported(HashError):
  167. """A hash was provided for a version-control-system-based requirement, but
  168. we don't have a method for hashing those."""
  169. order = 0
  170. head = ("Can't verify hashes for these requirements because we don't "
  171. "have a way to hash version control repositories:")
  172. class DirectoryUrlHashUnsupported(HashError):
  173. """A hash was provided for a version-control-system-based requirement, but
  174. we don't have a method for hashing those."""
  175. order = 1
  176. head = ("Can't verify hashes for these file:// requirements because they "
  177. "point to directories:")
  178. class HashMissing(HashError):
  179. """A hash was needed for a requirement but is absent."""
  180. order = 2
  181. head = ('Hashes are required in --require-hashes mode, but they are '
  182. 'missing from some requirements. Here is a list of those '
  183. 'requirements along with the hashes their downloaded archives '
  184. 'actually had. Add lines like these to your requirements files to '
  185. 'prevent tampering. (If you did not enable --require-hashes '
  186. 'manually, note that it turns on automatically when any package '
  187. 'has a hash.)')
  188. def __init__(self, gotten_hash):
  189. # type: (str) -> None
  190. """
  191. :param gotten_hash: The hash of the (possibly malicious) archive we
  192. just downloaded
  193. """
  194. self.gotten_hash = gotten_hash
  195. def body(self):
  196. # type: () -> str
  197. # Dodge circular import.
  198. from pip._internal.utils.hashes import FAVORITE_HASH
  199. package = None
  200. if self.req:
  201. # In the case of URL-based requirements, display the original URL
  202. # seen in the requirements file rather than the package name,
  203. # so the output can be directly copied into the requirements file.
  204. package = (self.req.original_link if self.req.original_link
  205. # In case someone feeds something downright stupid
  206. # to InstallRequirement's constructor.
  207. else getattr(self.req, 'req', None))
  208. return ' {} --hash={}:{}'.format(package or 'unknown package',
  209. FAVORITE_HASH,
  210. self.gotten_hash)
  211. class HashUnpinned(HashError):
  212. """A requirement had a hash specified but was not pinned to a specific
  213. version."""
  214. order = 3
  215. head = ('In --require-hashes mode, all requirements must have their '
  216. 'versions pinned with ==. These do not:')
  217. class HashMismatch(HashError):
  218. """
  219. Distribution file hash values don't match.
  220. :ivar package_name: The name of the package that triggered the hash
  221. mismatch. Feel free to write to this after the exception is raise to
  222. improve its error message.
  223. """
  224. order = 4
  225. head = ('THESE PACKAGES DO NOT MATCH THE HASHES FROM THE REQUIREMENTS '
  226. 'FILE. If you have updated the package versions, please update '
  227. 'the hashes. Otherwise, examine the package contents carefully; '
  228. 'someone may have tampered with them.')
  229. def __init__(self, allowed, gots):
  230. # type: (Dict[str, List[str]], Dict[str, _Hash]) -> None
  231. """
  232. :param allowed: A dict of algorithm names pointing to lists of allowed
  233. hex digests
  234. :param gots: A dict of algorithm names pointing to hashes we
  235. actually got from the files under suspicion
  236. """
  237. self.allowed = allowed
  238. self.gots = gots
  239. def body(self):
  240. # type: () -> str
  241. return ' {}:\n{}'.format(self._requirement_name(),
  242. self._hash_comparison())
  243. def _hash_comparison(self):
  244. # type: () -> str
  245. """
  246. Return a comparison of actual and expected hash values.
  247. Example::
  248. Expected sha256 abcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcde
  249. or 123451234512345123451234512345123451234512345
  250. Got bcdefbcdefbcdefbcdefbcdefbcdefbcdefbcdefbcdef
  251. """
  252. def hash_then_or(hash_name):
  253. # type: (str) -> chain[str]
  254. # For now, all the decent hashes have 6-char names, so we can get
  255. # away with hard-coding space literals.
  256. return chain([hash_name], repeat(' or'))
  257. lines = [] # type: List[str]
  258. for hash_name, expecteds in iteritems(self.allowed):
  259. prefix = hash_then_or(hash_name)
  260. lines.extend((' Expected {} {}'.format(next(prefix), e))
  261. for e in expecteds)
  262. lines.append(' Got {}\n'.format(
  263. self.gots[hash_name].hexdigest()))
  264. return '\n'.join(lines)
  265. class UnsupportedPythonVersion(InstallationError):
  266. """Unsupported python version according to Requires-Python package
  267. metadata."""
  268. class ConfigurationFileCouldNotBeLoaded(ConfigurationError):
  269. """When there are errors while loading a configuration file
  270. """
  271. def __init__(self, reason="could not be loaded", fname=None, error=None):
  272. # type: (str, Optional[str], Optional[configparser.Error]) -> None
  273. super(ConfigurationFileCouldNotBeLoaded, self).__init__(error)
  274. self.reason = reason
  275. self.fname = fname
  276. self.error = error
  277. def __str__(self):
  278. # type: () -> str
  279. if self.fname is not None:
  280. message_part = " in {}.".format(self.fname)
  281. else:
  282. assert self.error is not None
  283. message_part = ".\n{}\n".format(self.error)
  284. return "Configuration file {}{}".format(self.reason, message_part)