errors.py 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  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. __all__ = [
  24. "ApplyDeltaError",
  25. "ChecksumMismatch",
  26. "CommitError",
  27. "FileFormatException",
  28. "GitProtocolError",
  29. "HangupException",
  30. "HookError",
  31. "MissingCommitError",
  32. "NoIndexPresent",
  33. "NotBlobError",
  34. "NotCommitError",
  35. "NotGitRepository",
  36. "NotTagError",
  37. "NotTreeError",
  38. "ObjectFormatException",
  39. "ObjectMissing",
  40. "PackedRefsException",
  41. "RefFormatError",
  42. "SendPackError",
  43. "UnexpectedCommandError",
  44. "WorkingTreeModifiedError",
  45. "WrongObjectException",
  46. ]
  47. # Please do not add more errors here, but instead add them close to the code
  48. # that raises the error.
  49. import binascii
  50. from collections.abc import Sequence
  51. class ChecksumMismatch(Exception):
  52. """A checksum didn't match the expected contents."""
  53. def __init__(
  54. self,
  55. expected: bytes | str,
  56. got: bytes | str,
  57. extra: str | None = None,
  58. ) -> None:
  59. """Initialize a ChecksumMismatch exception.
  60. Args:
  61. expected: The expected checksum value (bytes or hex string).
  62. got: The actual checksum value (bytes or hex string).
  63. extra: Optional additional error information.
  64. """
  65. if isinstance(expected, bytes) and len(expected) in (20, 32):
  66. expected_str = binascii.hexlify(expected).decode("ascii")
  67. else:
  68. expected_str = (
  69. expected if isinstance(expected, str) else expected.decode("ascii")
  70. )
  71. if isinstance(got, bytes) and len(got) in (20, 32):
  72. got_str = binascii.hexlify(got).decode("ascii")
  73. else:
  74. got_str = got if isinstance(got, str) else got.decode("ascii")
  75. self.expected = expected_str
  76. self.got = got_str
  77. self.extra = extra
  78. message = f"Checksum mismatch: Expected {expected_str}, got {got_str}"
  79. if self.extra is not None:
  80. message += f"; {extra}"
  81. Exception.__init__(self, message)
  82. class WrongObjectException(Exception):
  83. """Baseclass for all the _ is not a _ exceptions on objects.
  84. Do not instantiate directly.
  85. Subclasses should define a type_name attribute that indicates what
  86. was expected if they were raised.
  87. """
  88. type_name: str
  89. def __init__(self, sha: bytes, *args: object, **kwargs: object) -> None:
  90. """Initialize a WrongObjectException.
  91. Args:
  92. sha: The SHA of the object that was not of the expected type.
  93. *args: Additional positional arguments.
  94. **kwargs: Additional keyword arguments.
  95. """
  96. Exception.__init__(self, f"{sha.decode('ascii')} is not a {self.type_name}")
  97. class NotCommitError(WrongObjectException):
  98. """Indicates that the sha requested does not point to a commit."""
  99. type_name = "commit"
  100. class NotTreeError(WrongObjectException):
  101. """Indicates that the sha requested does not point to a tree."""
  102. type_name = "tree"
  103. class NotTagError(WrongObjectException):
  104. """Indicates that the sha requested does not point to a tag."""
  105. type_name = "tag"
  106. class NotBlobError(WrongObjectException):
  107. """Indicates that the sha requested does not point to a blob."""
  108. type_name = "blob"
  109. class MissingCommitError(Exception):
  110. """Indicates that a commit was not found in the repository."""
  111. def __init__(self, sha: bytes, *args: object, **kwargs: object) -> None:
  112. """Initialize a MissingCommitError.
  113. Args:
  114. sha: The SHA of the missing commit.
  115. *args: Additional positional arguments.
  116. **kwargs: Additional keyword arguments.
  117. """
  118. self.sha = sha
  119. Exception.__init__(self, f"{sha.decode('ascii')} is not in the revision store")
  120. class ObjectMissing(Exception):
  121. """Indicates that a requested object is missing."""
  122. def __init__(self, sha: bytes, *args: object, **kwargs: object) -> None:
  123. """Initialize an ObjectMissing exception.
  124. Args:
  125. sha: The SHA of the missing object.
  126. *args: Additional positional arguments.
  127. **kwargs: Additional keyword arguments.
  128. """
  129. Exception.__init__(self, f"{sha.decode('ascii')} is not in the pack")
  130. class ApplyDeltaError(Exception):
  131. """Indicates that applying a delta failed."""
  132. def __init__(self, *args: object, **kwargs: object) -> None:
  133. """Initialize an ApplyDeltaError.
  134. Args:
  135. *args: Error message and additional positional arguments.
  136. **kwargs: Additional keyword arguments.
  137. """
  138. Exception.__init__(self, *args, **kwargs)
  139. class NotGitRepository(Exception):
  140. """Indicates that no Git repository was found."""
  141. def __init__(self, *args: object, **kwargs: object) -> None:
  142. """Initialize a NotGitRepository exception.
  143. Args:
  144. *args: Error message and additional positional arguments.
  145. **kwargs: Additional keyword arguments.
  146. """
  147. Exception.__init__(self, *args, **kwargs)
  148. class GitProtocolError(Exception):
  149. """Git protocol exception."""
  150. def __init__(self, *args: object, **kwargs: object) -> None:
  151. """Initialize a GitProtocolError.
  152. Args:
  153. *args: Error message and additional positional arguments.
  154. **kwargs: Additional keyword arguments.
  155. """
  156. Exception.__init__(self, *args, **kwargs)
  157. def __eq__(self, other: object) -> bool:
  158. """Check equality between GitProtocolError instances.
  159. Args:
  160. other: The object to compare with.
  161. Returns:
  162. True if both are GitProtocolError instances with same args, False otherwise.
  163. """
  164. return isinstance(other, GitProtocolError) and self.args == other.args
  165. class SendPackError(GitProtocolError):
  166. """An error occurred during send_pack."""
  167. class HangupException(GitProtocolError):
  168. """Hangup exception."""
  169. def __init__(self, stderr_lines: Sequence[bytes] | None = None) -> None:
  170. """Initialize a HangupException.
  171. Args:
  172. stderr_lines: Optional list of stderr output lines from the remote server.
  173. """
  174. if stderr_lines:
  175. super().__init__(
  176. "\n".join(
  177. line.decode("utf-8", "surrogateescape") for line in stderr_lines
  178. )
  179. )
  180. else:
  181. super().__init__("The remote server unexpectedly closed the connection.")
  182. self.stderr_lines = stderr_lines
  183. def __eq__(self, other: object) -> bool:
  184. """Check equality between HangupException instances.
  185. Args:
  186. other: The object to compare with.
  187. Returns:
  188. True if both are HangupException instances with same stderr_lines, False otherwise.
  189. """
  190. return (
  191. isinstance(other, HangupException)
  192. and self.stderr_lines == other.stderr_lines
  193. )
  194. class UnexpectedCommandError(GitProtocolError):
  195. """Unexpected command received in a proto line."""
  196. def __init__(self, command: str | None) -> None:
  197. """Initialize an UnexpectedCommandError.
  198. Args:
  199. command: The unexpected command received, or None for flush-pkt.
  200. """
  201. command_str = "flush-pkt" if command is None else f"command {command}"
  202. super().__init__(f"Protocol got unexpected {command_str}")
  203. class FileFormatException(Exception):
  204. """Base class for exceptions relating to reading git file formats."""
  205. class PackedRefsException(FileFormatException):
  206. """Indicates an error parsing a packed-refs file."""
  207. class ObjectFormatException(FileFormatException):
  208. """Indicates an error parsing an object."""
  209. class NoIndexPresent(Exception):
  210. """No index is present."""
  211. class CommitError(Exception):
  212. """An error occurred while performing a commit."""
  213. class RefFormatError(Exception):
  214. """Indicates an invalid ref name."""
  215. class HookError(Exception):
  216. """An error occurred while executing a hook."""
  217. class WorkingTreeModifiedError(Exception):
  218. """Indicates that the working tree has modifications that would be overwritten."""