errors.py 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  1. # errors.py -- errors for dulwich
  2. # Copyright (C) 2007 James Westby <jw+debian@jameswestby.net>
  3. # Copyright (C) 2009-2012 Jelmer Vernooij <jelmer@jelmer.uk>
  4. #
  5. # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
  6. # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU
  7. # General Public License as published by the Free Software Foundation; version 2.0
  8. # or (at your option) any later version. You can redistribute it and/or
  9. # modify it under the terms of either of these two licenses.
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. #
  17. # You should have received a copy of the licenses; if not, see
  18. # <http://www.gnu.org/licenses/> for a copy of the GNU General Public License
  19. # and <http://www.apache.org/licenses/LICENSE-2.0> for a copy of the Apache
  20. # License, Version 2.0.
  21. #
  22. """Dulwich-related exception classes and utility functions."""
  23. # Please do not add more errors here, but instead add them close to the code
  24. # that raises the error.
  25. import binascii
  26. from typing import Optional, Union
  27. class ChecksumMismatch(Exception):
  28. """A checksum didn't match the expected contents."""
  29. def __init__(
  30. self,
  31. expected: Union[bytes, str],
  32. got: Union[bytes, str],
  33. extra: Optional[str] = None,
  34. ) -> None:
  35. """Initialize a ChecksumMismatch exception.
  36. Args:
  37. expected: The expected checksum value (bytes or hex string).
  38. got: The actual checksum value (bytes or hex string).
  39. extra: Optional additional error information.
  40. """
  41. if isinstance(expected, bytes) and len(expected) == 20:
  42. expected_str = binascii.hexlify(expected).decode("ascii")
  43. else:
  44. expected_str = (
  45. expected if isinstance(expected, str) else expected.decode("ascii")
  46. )
  47. if isinstance(got, bytes) and len(got) == 20:
  48. got_str = binascii.hexlify(got).decode("ascii")
  49. else:
  50. got_str = got if isinstance(got, str) else got.decode("ascii")
  51. self.expected = expected_str
  52. self.got = got_str
  53. self.extra = extra
  54. message = f"Checksum mismatch: Expected {expected_str}, got {got_str}"
  55. if self.extra is not None:
  56. message += f"; {extra}"
  57. Exception.__init__(self, message)
  58. class WrongObjectException(Exception):
  59. """Baseclass for all the _ is not a _ exceptions on objects.
  60. Do not instantiate directly.
  61. Subclasses should define a type_name attribute that indicates what
  62. was expected if they were raised.
  63. """
  64. type_name: str
  65. def __init__(self, sha: bytes, *args: object, **kwargs: object) -> None:
  66. """Initialize a WrongObjectException.
  67. Args:
  68. sha: The SHA of the object that was not of the expected type.
  69. *args: Additional positional arguments.
  70. **kwargs: Additional keyword arguments.
  71. """
  72. Exception.__init__(self, f"{sha.decode('ascii')} is not a {self.type_name}")
  73. class NotCommitError(WrongObjectException):
  74. """Indicates that the sha requested does not point to a commit."""
  75. type_name = "commit"
  76. class NotTreeError(WrongObjectException):
  77. """Indicates that the sha requested does not point to a tree."""
  78. type_name = "tree"
  79. class NotTagError(WrongObjectException):
  80. """Indicates that the sha requested does not point to a tag."""
  81. type_name = "tag"
  82. class NotBlobError(WrongObjectException):
  83. """Indicates that the sha requested does not point to a blob."""
  84. type_name = "blob"
  85. class MissingCommitError(Exception):
  86. """Indicates that a commit was not found in the repository."""
  87. def __init__(self, sha: bytes, *args: object, **kwargs: object) -> None:
  88. """Initialize a MissingCommitError.
  89. Args:
  90. sha: The SHA of the missing commit.
  91. *args: Additional positional arguments.
  92. **kwargs: Additional keyword arguments.
  93. """
  94. self.sha = sha
  95. Exception.__init__(self, f"{sha.decode('ascii')} is not in the revision store")
  96. class ObjectMissing(Exception):
  97. """Indicates that a requested object is missing."""
  98. def __init__(self, sha: bytes, *args: object, **kwargs: object) -> None:
  99. """Initialize an ObjectMissing exception.
  100. Args:
  101. sha: The SHA of the missing object.
  102. *args: Additional positional arguments.
  103. **kwargs: Additional keyword arguments.
  104. """
  105. Exception.__init__(self, f"{sha.decode('ascii')} is not in the pack")
  106. class ApplyDeltaError(Exception):
  107. """Indicates that applying a delta failed."""
  108. def __init__(self, *args: object, **kwargs: object) -> None:
  109. """Initialize an ApplyDeltaError.
  110. Args:
  111. *args: Error message and additional positional arguments.
  112. **kwargs: Additional keyword arguments.
  113. """
  114. Exception.__init__(self, *args, **kwargs)
  115. class NotGitRepository(Exception):
  116. """Indicates that no Git repository was found."""
  117. def __init__(self, *args: object, **kwargs: object) -> None:
  118. """Initialize a NotGitRepository exception.
  119. Args:
  120. *args: Error message and additional positional arguments.
  121. **kwargs: Additional keyword arguments.
  122. """
  123. Exception.__init__(self, *args, **kwargs)
  124. class GitProtocolError(Exception):
  125. """Git protocol exception."""
  126. def __init__(self, *args: object, **kwargs: object) -> None:
  127. """Initialize a GitProtocolError.
  128. Args:
  129. *args: Error message and additional positional arguments.
  130. **kwargs: Additional keyword arguments.
  131. """
  132. Exception.__init__(self, *args, **kwargs)
  133. def __eq__(self, other: object) -> bool:
  134. """Check equality between GitProtocolError instances.
  135. Args:
  136. other: The object to compare with.
  137. Returns:
  138. True if both are GitProtocolError instances with same args, False otherwise.
  139. """
  140. return isinstance(other, GitProtocolError) and self.args == other.args
  141. class SendPackError(GitProtocolError):
  142. """An error occurred during send_pack."""
  143. class HangupException(GitProtocolError):
  144. """Hangup exception."""
  145. def __init__(self, stderr_lines: Optional[list[bytes]] = None) -> None:
  146. """Initialize a HangupException.
  147. Args:
  148. stderr_lines: Optional list of stderr output lines from the remote server.
  149. """
  150. if stderr_lines:
  151. super().__init__(
  152. "\n".join(
  153. line.decode("utf-8", "surrogateescape") for line in stderr_lines
  154. )
  155. )
  156. else:
  157. super().__init__("The remote server unexpectedly closed the connection.")
  158. self.stderr_lines = stderr_lines
  159. def __eq__(self, other: object) -> bool:
  160. """Check equality between HangupException instances.
  161. Args:
  162. other: The object to compare with.
  163. Returns:
  164. True if both are HangupException instances with same stderr_lines, False otherwise.
  165. """
  166. return (
  167. isinstance(other, HangupException)
  168. and self.stderr_lines == other.stderr_lines
  169. )
  170. class UnexpectedCommandError(GitProtocolError):
  171. """Unexpected command received in a proto line."""
  172. def __init__(self, command: Optional[str]) -> None:
  173. """Initialize an UnexpectedCommandError.
  174. Args:
  175. command: The unexpected command received, or None for flush-pkt.
  176. """
  177. command_str = "flush-pkt" if command is None else f"command {command}"
  178. super().__init__(f"Protocol got unexpected {command_str}")
  179. class FileFormatException(Exception):
  180. """Base class for exceptions relating to reading git file formats."""
  181. class PackedRefsException(FileFormatException):
  182. """Indicates an error parsing a packed-refs file."""
  183. class ObjectFormatException(FileFormatException):
  184. """Indicates an error parsing an object."""
  185. class NoIndexPresent(Exception):
  186. """No index is present."""
  187. class CommitError(Exception):
  188. """An error occurred while performing a commit."""
  189. class RefFormatError(Exception):
  190. """Indicates an invalid ref name."""
  191. class HookError(Exception):
  192. """An error occurred while executing a hook."""
  193. class WorkingTreeModifiedError(Exception):
  194. """Indicates that the working tree has modifications that would be overwritten."""