You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

exceptions.py 8.9KB

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