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."""
25__all__ = [
26 "ApplyDeltaError",
27 "ChecksumMismatch",
28 "CommitError",
29 "FileFormatException",
30 "GitProtocolError",
31 "HangupException",
32 "HookError",
33 "MissingCommitError",
34 "NoIndexPresent",
35 "NotBlobError",
36 "NotCommitError",
37 "NotGitRepository",
38 "NotTagError",
39 "NotTreeError",
40 "ObjectFormatException",
41 "ObjectMissing",
42 "PackedRefsException",
43 "RefFormatError",
44 "SendPackError",
45 "UnexpectedCommandError",
46 "WorkingTreeModifiedError",
47 "WrongObjectException",
48]
50# Please do not add more errors here, but instead add them close to the code
51# that raises the error.
53import binascii
54from collections.abc import Sequence
57class ChecksumMismatch(Exception):
58 """A checksum didn't match the expected contents."""
60 def __init__(
61 self,
62 expected: bytes | str,
63 got: bytes | str,
64 extra: str | None = None,
65 ) -> None:
66 """Initialize a ChecksumMismatch exception.
68 Args:
69 expected: The expected checksum value (bytes or hex string).
70 got: The actual checksum value (bytes or hex string).
71 extra: Optional additional error information.
72 """
73 if isinstance(expected, bytes) and len(expected) == 20:
74 expected_str = binascii.hexlify(expected).decode("ascii")
75 else:
76 expected_str = (
77 expected if isinstance(expected, str) else expected.decode("ascii")
78 )
79 if isinstance(got, bytes) and len(got) == 20:
80 got_str = binascii.hexlify(got).decode("ascii")
81 else:
82 got_str = got if isinstance(got, str) else got.decode("ascii")
83 self.expected = expected_str
84 self.got = got_str
85 self.extra = extra
86 message = f"Checksum mismatch: Expected {expected_str}, got {got_str}"
87 if self.extra is not None:
88 message += f"; {extra}"
89 Exception.__init__(self, message)
92class WrongObjectException(Exception):
93 """Baseclass for all the _ is not a _ exceptions on objects.
95 Do not instantiate directly.
97 Subclasses should define a type_name attribute that indicates what
98 was expected if they were raised.
99 """
101 type_name: str
103 def __init__(self, sha: bytes, *args: object, **kwargs: object) -> None:
104 """Initialize a WrongObjectException.
106 Args:
107 sha: The SHA of the object that was not of the expected type.
108 *args: Additional positional arguments.
109 **kwargs: Additional keyword arguments.
110 """
111 Exception.__init__(self, f"{sha.decode('ascii')} is not a {self.type_name}")
114class NotCommitError(WrongObjectException):
115 """Indicates that the sha requested does not point to a commit."""
117 type_name = "commit"
120class NotTreeError(WrongObjectException):
121 """Indicates that the sha requested does not point to a tree."""
123 type_name = "tree"
126class NotTagError(WrongObjectException):
127 """Indicates that the sha requested does not point to a tag."""
129 type_name = "tag"
132class NotBlobError(WrongObjectException):
133 """Indicates that the sha requested does not point to a blob."""
135 type_name = "blob"
138class MissingCommitError(Exception):
139 """Indicates that a commit was not found in the repository."""
141 def __init__(self, sha: bytes, *args: object, **kwargs: object) -> None:
142 """Initialize a MissingCommitError.
144 Args:
145 sha: The SHA of the missing commit.
146 *args: Additional positional arguments.
147 **kwargs: Additional keyword arguments.
148 """
149 self.sha = sha
150 Exception.__init__(self, f"{sha.decode('ascii')} is not in the revision store")
153class ObjectMissing(Exception):
154 """Indicates that a requested object is missing."""
156 def __init__(self, sha: bytes, *args: object, **kwargs: object) -> None:
157 """Initialize an ObjectMissing exception.
159 Args:
160 sha: The SHA of the missing object.
161 *args: Additional positional arguments.
162 **kwargs: Additional keyword arguments.
163 """
164 Exception.__init__(self, f"{sha.decode('ascii')} is not in the pack")
167class ApplyDeltaError(Exception):
168 """Indicates that applying a delta failed."""
170 def __init__(self, *args: object, **kwargs: object) -> None:
171 """Initialize an ApplyDeltaError.
173 Args:
174 *args: Error message and additional positional arguments.
175 **kwargs: Additional keyword arguments.
176 """
177 Exception.__init__(self, *args, **kwargs)
180class NotGitRepository(Exception):
181 """Indicates that no Git repository was found."""
183 def __init__(self, *args: object, **kwargs: object) -> None:
184 """Initialize a NotGitRepository exception.
186 Args:
187 *args: Error message and additional positional arguments.
188 **kwargs: Additional keyword arguments.
189 """
190 Exception.__init__(self, *args, **kwargs)
193class GitProtocolError(Exception):
194 """Git protocol exception."""
196 def __init__(self, *args: object, **kwargs: object) -> None:
197 """Initialize a GitProtocolError.
199 Args:
200 *args: Error message and additional positional arguments.
201 **kwargs: Additional keyword arguments.
202 """
203 Exception.__init__(self, *args, **kwargs)
205 def __eq__(self, other: object) -> bool:
206 """Check equality between GitProtocolError instances.
208 Args:
209 other: The object to compare with.
211 Returns:
212 True if both are GitProtocolError instances with same args, False otherwise.
213 """
214 return isinstance(other, GitProtocolError) and self.args == other.args
217class SendPackError(GitProtocolError):
218 """An error occurred during send_pack."""
221class HangupException(GitProtocolError):
222 """Hangup exception."""
224 def __init__(self, stderr_lines: Sequence[bytes] | None = None) -> None:
225 """Initialize a HangupException.
227 Args:
228 stderr_lines: Optional list of stderr output lines from the remote server.
229 """
230 if stderr_lines:
231 super().__init__(
232 "\n".join(
233 line.decode("utf-8", "surrogateescape") for line in stderr_lines
234 )
235 )
236 else:
237 super().__init__("The remote server unexpectedly closed the connection.")
238 self.stderr_lines = stderr_lines
240 def __eq__(self, other: object) -> bool:
241 """Check equality between HangupException instances.
243 Args:
244 other: The object to compare with.
246 Returns:
247 True if both are HangupException instances with same stderr_lines, False otherwise.
248 """
249 return (
250 isinstance(other, HangupException)
251 and self.stderr_lines == other.stderr_lines
252 )
255class UnexpectedCommandError(GitProtocolError):
256 """Unexpected command received in a proto line."""
258 def __init__(self, command: str | None) -> None:
259 """Initialize an UnexpectedCommandError.
261 Args:
262 command: The unexpected command received, or None for flush-pkt.
263 """
264 command_str = "flush-pkt" if command is None else f"command {command}"
265 super().__init__(f"Protocol got unexpected {command_str}")
268class FileFormatException(Exception):
269 """Base class for exceptions relating to reading git file formats."""
272class PackedRefsException(FileFormatException):
273 """Indicates an error parsing a packed-refs file."""
276class ObjectFormatException(FileFormatException):
277 """Indicates an error parsing an object."""
280class NoIndexPresent(Exception):
281 """No index is present."""
284class CommitError(Exception):
285 """An error occurred while performing a commit."""
288class RefFormatError(Exception):
289 """Indicates an invalid ref name."""
292class HookError(Exception):
293 """An error occurred while executing a hook."""
296class WorkingTreeModifiedError(Exception):
297 """Indicates that the working tree has modifications that would be overwritten."""