Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/dulwich/errors.py: 59%
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
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#
23"""Dulwich-related exception classes and utility functions."""
26# Please do not add more errors here, but instead add them close to the code
27# that raises the error.
29import binascii
30from typing import Optional, Union
33class ChecksumMismatch(Exception):
34 """A checksum didn't match the expected contents."""
36 def __init__(
37 self,
38 expected: Union[bytes, str],
39 got: Union[bytes, str],
40 extra: Optional[str] = None,
41 ) -> None:
42 """Initialize a ChecksumMismatch exception.
44 Args:
45 expected: The expected checksum value (bytes or hex string).
46 got: The actual checksum value (bytes or hex string).
47 extra: Optional additional error information.
48 """
49 if isinstance(expected, bytes) and len(expected) == 20:
50 expected_str = binascii.hexlify(expected).decode("ascii")
51 else:
52 expected_str = (
53 expected if isinstance(expected, str) else expected.decode("ascii")
54 )
55 if isinstance(got, bytes) and len(got) == 20:
56 got_str = binascii.hexlify(got).decode("ascii")
57 else:
58 got_str = got if isinstance(got, str) else got.decode("ascii")
59 self.expected = expected_str
60 self.got = got_str
61 self.extra = extra
62 message = f"Checksum mismatch: Expected {expected_str}, got {got_str}"
63 if self.extra is not None:
64 message += f"; {extra}"
65 Exception.__init__(self, message)
68class WrongObjectException(Exception):
69 """Baseclass for all the _ is not a _ exceptions on objects.
71 Do not instantiate directly.
73 Subclasses should define a type_name attribute that indicates what
74 was expected if they were raised.
75 """
77 type_name: str
79 def __init__(self, sha: bytes, *args: object, **kwargs: object) -> None:
80 """Initialize a WrongObjectException.
82 Args:
83 sha: The SHA of the object that was not of the expected type.
84 *args: Additional positional arguments.
85 **kwargs: Additional keyword arguments.
86 """
87 Exception.__init__(self, f"{sha.decode('ascii')} is not a {self.type_name}")
90class NotCommitError(WrongObjectException):
91 """Indicates that the sha requested does not point to a commit."""
93 type_name = "commit"
96class NotTreeError(WrongObjectException):
97 """Indicates that the sha requested does not point to a tree."""
99 type_name = "tree"
102class NotTagError(WrongObjectException):
103 """Indicates that the sha requested does not point to a tag."""
105 type_name = "tag"
108class NotBlobError(WrongObjectException):
109 """Indicates that the sha requested does not point to a blob."""
111 type_name = "blob"
114class MissingCommitError(Exception):
115 """Indicates that a commit was not found in the repository."""
117 def __init__(self, sha: bytes, *args: object, **kwargs: object) -> None:
118 """Initialize a MissingCommitError.
120 Args:
121 sha: The SHA of the missing commit.
122 *args: Additional positional arguments.
123 **kwargs: Additional keyword arguments.
124 """
125 self.sha = sha
126 Exception.__init__(self, f"{sha.decode('ascii')} is not in the revision store")
129class ObjectMissing(Exception):
130 """Indicates that a requested object is missing."""
132 def __init__(self, sha: bytes, *args: object, **kwargs: object) -> None:
133 """Initialize an ObjectMissing exception.
135 Args:
136 sha: The SHA of the missing object.
137 *args: Additional positional arguments.
138 **kwargs: Additional keyword arguments.
139 """
140 Exception.__init__(self, f"{sha.decode('ascii')} is not in the pack")
143class ApplyDeltaError(Exception):
144 """Indicates that applying a delta failed."""
146 def __init__(self, *args: object, **kwargs: object) -> None:
147 """Initialize an ApplyDeltaError.
149 Args:
150 *args: Error message and additional positional arguments.
151 **kwargs: Additional keyword arguments.
152 """
153 Exception.__init__(self, *args, **kwargs)
156class NotGitRepository(Exception):
157 """Indicates that no Git repository was found."""
159 def __init__(self, *args: object, **kwargs: object) -> None:
160 """Initialize a NotGitRepository exception.
162 Args:
163 *args: Error message and additional positional arguments.
164 **kwargs: Additional keyword arguments.
165 """
166 Exception.__init__(self, *args, **kwargs)
169class GitProtocolError(Exception):
170 """Git protocol exception."""
172 def __init__(self, *args: object, **kwargs: object) -> None:
173 """Initialize a GitProtocolError.
175 Args:
176 *args: Error message and additional positional arguments.
177 **kwargs: Additional keyword arguments.
178 """
179 Exception.__init__(self, *args, **kwargs)
181 def __eq__(self, other: object) -> bool:
182 """Check equality between GitProtocolError instances.
184 Args:
185 other: The object to compare with.
187 Returns:
188 True if both are GitProtocolError instances with same args, False otherwise.
189 """
190 return isinstance(other, GitProtocolError) and self.args == other.args
193class SendPackError(GitProtocolError):
194 """An error occurred during send_pack."""
197class HangupException(GitProtocolError):
198 """Hangup exception."""
200 def __init__(self, stderr_lines: Optional[list[bytes]] = None) -> None:
201 """Initialize a HangupException.
203 Args:
204 stderr_lines: Optional list of stderr output lines from the remote server.
205 """
206 if stderr_lines:
207 super().__init__(
208 "\n".join(
209 line.decode("utf-8", "surrogateescape") for line in stderr_lines
210 )
211 )
212 else:
213 super().__init__("The remote server unexpectedly closed the connection.")
214 self.stderr_lines = stderr_lines
216 def __eq__(self, other: object) -> bool:
217 """Check equality between HangupException instances.
219 Args:
220 other: The object to compare with.
222 Returns:
223 True if both are HangupException instances with same stderr_lines, False otherwise.
224 """
225 return (
226 isinstance(other, HangupException)
227 and self.stderr_lines == other.stderr_lines
228 )
231class UnexpectedCommandError(GitProtocolError):
232 """Unexpected command received in a proto line."""
234 def __init__(self, command: Optional[str]) -> None:
235 """Initialize an UnexpectedCommandError.
237 Args:
238 command: The unexpected command received, or None for flush-pkt.
239 """
240 command_str = "flush-pkt" if command is None else f"command {command}"
241 super().__init__(f"Protocol got unexpected {command_str}")
244class FileFormatException(Exception):
245 """Base class for exceptions relating to reading git file formats."""
248class PackedRefsException(FileFormatException):
249 """Indicates an error parsing a packed-refs file."""
252class ObjectFormatException(FileFormatException):
253 """Indicates an error parsing an object."""
256class NoIndexPresent(Exception):
257 """No index is present."""
260class CommitError(Exception):
261 """An error occurred while performing a commit."""
264class RefFormatError(Exception):
265 """Indicates an invalid ref name."""
268class HookError(Exception):
269 """An error occurred while executing a hook."""
272class WorkingTreeModifiedError(Exception):
273 """Indicates that the working tree has modifications that would be overwritten."""