exceptions.py 8.0 KB

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