exceptions.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  1. """Exceptions used throughout package"""
  2. # The following comment should be removed at some point in the future.
  3. # mypy: disallow-untyped-defs=False
  4. from __future__ import absolute_import
  5. from itertools import chain, groupby, repeat
  6. from pip._vendor.six import iteritems
  7. from pip._internal.utils.typing import MYPY_CHECK_RUNNING
  8. if MYPY_CHECK_RUNNING:
  9. from typing import Optional
  10. from pip._vendor.pkg_resources import Distribution
  11. from pip._internal.req.req_install import InstallRequirement
  12. class PipError(Exception):
  13. """Base pip exception"""
  14. class ConfigurationError(PipError):
  15. """General exception in configuration"""
  16. class InstallationError(PipError):
  17. """General exception during installation"""
  18. class UninstallationError(PipError):
  19. """General exception during uninstallation"""
  20. class NoneMetadataError(PipError):
  21. """
  22. Raised when accessing "METADATA" or "PKG-INFO" metadata for a
  23. pip._vendor.pkg_resources.Distribution object and
  24. `dist.has_metadata('METADATA')` returns True but
  25. `dist.get_metadata('METADATA')` returns None (and similarly for
  26. "PKG-INFO").
  27. """
  28. def __init__(self, dist, metadata_name):
  29. # type: (Distribution, str) -> None
  30. """
  31. :param dist: A Distribution object.
  32. :param metadata_name: The name of the metadata being accessed
  33. (can be "METADATA" or "PKG-INFO").
  34. """
  35. self.dist = dist
  36. self.metadata_name = metadata_name
  37. def __str__(self):
  38. # type: () -> str
  39. # Use `dist` in the error message because its stringification
  40. # includes more information, like the version and location.
  41. return (
  42. 'None {} metadata found for distribution: {}'.format(
  43. self.metadata_name, self.dist,
  44. )
  45. )
  46. class DistributionNotFound(InstallationError):
  47. """Raised when a distribution cannot be found to satisfy a requirement"""
  48. class RequirementsFileParseError(InstallationError):
  49. """Raised when a general error occurs parsing a requirements file line."""
  50. class BestVersionAlreadyInstalled(PipError):
  51. """Raised when the most up-to-date version of a package is already
  52. installed."""
  53. class BadCommand(PipError):
  54. """Raised when virtualenv or a command is not found"""
  55. class CommandError(PipError):
  56. """Raised when there is an error in command-line arguments"""
  57. class PreviousBuildDirError(PipError):
  58. """Raised when there's a previous conflicting build directory"""
  59. class InvalidWheelFilename(InstallationError):
  60. """Invalid wheel filename."""
  61. class UnsupportedWheel(InstallationError):
  62. """Unsupported wheel."""
  63. class HashErrors(InstallationError):
  64. """Multiple HashError instances rolled into one for reporting"""
  65. def __init__(self):
  66. self.errors = []
  67. def append(self, error):
  68. self.errors.append(error)
  69. def __str__(self):
  70. lines = []
  71. self.errors.sort(key=lambda e: e.order)
  72. for cls, errors_of_cls in groupby(self.errors, lambda e: e.__class__):
  73. lines.append(cls.head)
  74. lines.extend(e.body() for e in errors_of_cls)
  75. if lines:
  76. return '\n'.join(lines)
  77. def __nonzero__(self):
  78. return bool(self.errors)
  79. def __bool__(self):
  80. return self.__nonzero__()
  81. class HashError(InstallationError):
  82. """
  83. A failure to verify a package against known-good hashes
  84. :cvar order: An int sorting hash exception classes by difficulty of
  85. recovery (lower being harder), so the user doesn't bother fretting
  86. about unpinned packages when he has deeper issues, like VCS
  87. dependencies, to deal with. Also keeps error reports in a
  88. deterministic order.
  89. :cvar head: A section heading for display above potentially many
  90. exceptions of this kind
  91. :ivar req: The InstallRequirement that triggered this error. This is
  92. pasted on after the exception is instantiated, because it's not
  93. typically available earlier.
  94. """
  95. req = None # type: Optional[InstallRequirement]
  96. head = ''
  97. def body(self):
  98. """Return a summary of me for display under the heading.
  99. This default implementation simply prints a description of the
  100. triggering requirement.
  101. :param req: The InstallRequirement that provoked this error, with
  102. its link already populated by the resolver's _populate_link().
  103. """
  104. return ' {}'.format(self._requirement_name())
  105. def __str__(self):
  106. return '{}\n{}'.format(self.head, self.body())
  107. def _requirement_name(self):
  108. """Return a description of the requirement that triggered me.
  109. This default implementation returns long description of the req, with
  110. line numbers
  111. """
  112. return str(self.req) if self.req else 'unknown package'
  113. class VcsHashUnsupported(HashError):
  114. """A hash was provided for a version-control-system-based requirement, but
  115. we don't have a method for hashing those."""
  116. order = 0
  117. head = ("Can't verify hashes for these requirements because we don't "
  118. "have a way to hash version control repositories:")
  119. class DirectoryUrlHashUnsupported(HashError):
  120. """A hash was provided for a version-control-system-based requirement, but
  121. we don't have a method for hashing those."""
  122. order = 1
  123. head = ("Can't verify hashes for these file:// requirements because they "
  124. "point to directories:")
  125. class HashMissing(HashError):
  126. """A hash was needed for a requirement but is absent."""
  127. order = 2
  128. head = ('Hashes are required in --require-hashes mode, but they are '
  129. 'missing from some requirements. Here is a list of those '
  130. 'requirements along with the hashes their downloaded archives '
  131. 'actually had. Add lines like these to your requirements files to '
  132. 'prevent tampering. (If you did not enable --require-hashes '
  133. 'manually, note that it turns on automatically when any package '
  134. 'has a hash.)')
  135. def __init__(self, gotten_hash):
  136. """
  137. :param gotten_hash: The hash of the (possibly malicious) archive we
  138. just downloaded
  139. """
  140. self.gotten_hash = gotten_hash
  141. def body(self):
  142. # Dodge circular import.
  143. from pip._internal.utils.hashes import FAVORITE_HASH
  144. package = None
  145. if self.req:
  146. # In the case of URL-based requirements, display the original URL
  147. # seen in the requirements file rather than the package name,
  148. # so the output can be directly copied into the requirements file.
  149. package = (self.req.original_link if self.req.original_link
  150. # In case someone feeds something downright stupid
  151. # to InstallRequirement's constructor.
  152. else getattr(self.req, 'req', None))
  153. return ' {} --hash={}:{}'.format(package or 'unknown package',
  154. FAVORITE_HASH,
  155. self.gotten_hash)
  156. class HashUnpinned(HashError):
  157. """A requirement had a hash specified but was not pinned to a specific
  158. version."""
  159. order = 3
  160. head = ('In --require-hashes mode, all requirements must have their '
  161. 'versions pinned with ==. These do not:')
  162. class HashMismatch(HashError):
  163. """
  164. Distribution file hash values don't match.
  165. :ivar package_name: The name of the package that triggered the hash
  166. mismatch. Feel free to write to this after the exception is raise to
  167. improve its error message.
  168. """
  169. order = 4
  170. head = ('THESE PACKAGES DO NOT MATCH THE HASHES FROM THE REQUIREMENTS '
  171. 'FILE. If you have updated the package versions, please update '
  172. 'the hashes. Otherwise, examine the package contents carefully; '
  173. 'someone may have tampered with them.')
  174. def __init__(self, allowed, gots):
  175. """
  176. :param allowed: A dict of algorithm names pointing to lists of allowed
  177. hex digests
  178. :param gots: A dict of algorithm names pointing to hashes we
  179. actually got from the files under suspicion
  180. """
  181. self.allowed = allowed
  182. self.gots = gots
  183. def body(self):
  184. return ' {}:\n{}'.format(self._requirement_name(),
  185. self._hash_comparison())
  186. def _hash_comparison(self):
  187. """
  188. Return a comparison of actual and expected hash values.
  189. Example::
  190. Expected sha256 abcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcde
  191. or 123451234512345123451234512345123451234512345
  192. Got bcdefbcdefbcdefbcdefbcdefbcdefbcdefbcdefbcdef
  193. """
  194. def hash_then_or(hash_name):
  195. # For now, all the decent hashes have 6-char names, so we can get
  196. # away with hard-coding space literals.
  197. return chain([hash_name], repeat(' or'))
  198. lines = []
  199. for hash_name, expecteds in iteritems(self.allowed):
  200. prefix = hash_then_or(hash_name)
  201. lines.extend((' Expected {} {}'.format(next(prefix), e))
  202. for e in expecteds)
  203. lines.append(' Got {}\n'.format(
  204. self.gots[hash_name].hexdigest()))
  205. return '\n'.join(lines)
  206. class UnsupportedPythonVersion(InstallationError):
  207. """Unsupported python version according to Requires-Python package
  208. metadata."""
  209. class ConfigurationFileCouldNotBeLoaded(ConfigurationError):
  210. """When there are errors while loading a configuration file
  211. """
  212. def __init__(self, reason="could not be loaded", fname=None, error=None):
  213. super(ConfigurationFileCouldNotBeLoaded, self).__init__(error)
  214. self.reason = reason
  215. self.fname = fname
  216. self.error = error
  217. def __str__(self):
  218. if self.fname is not None:
  219. message_part = " in {}.".format(self.fname)
  220. else:
  221. assert self.error is not None
  222. message_part = ".\n{}\n".format(self.error.message)
  223. return "Configuration file {}{}".format(self.reason, message_part)