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 collections.abc import Sequence
31from typing import Optional, Union
34class ChecksumMismatch(Exception):
35 """A checksum didn't match the expected contents."""
37 def __init__(
38 self,
39 expected: Union[bytes, str],
40 got: Union[bytes, str],
41 extra: Optional[str] = None,
42 ) -> None:
43 """Initialize a ChecksumMismatch exception.
45 Args:
46 expected: The expected checksum value (bytes or hex string).
47 got: The actual checksum value (bytes or hex string).
48 extra: Optional additional error information.
49 """
50 if isinstance(expected, bytes) and len(expected) == 20:
51 expected_str = binascii.hexlify(expected).decode("ascii")
52 else:
53 expected_str = (
54 expected if isinstance(expected, str) else expected.decode("ascii")
55 )
56 if isinstance(got, bytes) and len(got) == 20:
57 got_str = binascii.hexlify(got).decode("ascii")
58 else:
59 got_str = got if isinstance(got, str) else got.decode("ascii")
60 self.expected = expected_str
61 self.got = got_str
62 self.extra = extra
63 message = f"Checksum mismatch: Expected {expected_str}, got {got_str}"
64 if self.extra is not None:
65 message += f"; {extra}"
66 Exception.__init__(self, message)
69class WrongObjectException(Exception):
70 """Baseclass for all the _ is not a _ exceptions on objects.
72 Do not instantiate directly.
74 Subclasses should define a type_name attribute that indicates what
75 was expected if they were raised.
76 """
78 type_name: str
80 def __init__(self, sha: bytes, *args: object, **kwargs: object) -> None:
81 """Initialize a WrongObjectException.
83 Args:
84 sha: The SHA of the object that was not of the expected type.
85 *args: Additional positional arguments.
86 **kwargs: Additional keyword arguments.
87 """
88 Exception.__init__(self, f"{sha.decode('ascii')} is not a {self.type_name}")
91class NotCommitError(WrongObjectException):
92 """Indicates that the sha requested does not point to a commit."""
94 type_name = "commit"
97class NotTreeError(WrongObjectException):
98 """Indicates that the sha requested does not point to a tree."""
100 type_name = "tree"
103class NotTagError(WrongObjectException):
104 """Indicates that the sha requested does not point to a tag."""
106 type_name = "tag"
109class NotBlobError(WrongObjectException):
110 """Indicates that the sha requested does not point to a blob."""
112 type_name = "blob"
115class MissingCommitError(Exception):
116 """Indicates that a commit was not found in the repository."""
118 def __init__(self, sha: bytes, *args: object, **kwargs: object) -> None:
119 """Initialize a MissingCommitError.
121 Args:
122 sha: The SHA of the missing commit.
123 *args: Additional positional arguments.
124 **kwargs: Additional keyword arguments.
125 """
126 self.sha = sha
127 Exception.__init__(self, f"{sha.decode('ascii')} is not in the revision store")
130class ObjectMissing(Exception):
131 """Indicates that a requested object is missing."""
133 def __init__(self, sha: bytes, *args: object, **kwargs: object) -> None:
134 """Initialize an ObjectMissing exception.
136 Args:
137 sha: The SHA of the missing object.
138 *args: Additional positional arguments.
139 **kwargs: Additional keyword arguments.
140 """
141 Exception.__init__(self, f"{sha.decode('ascii')} is not in the pack")
144class ApplyDeltaError(Exception):
145 """Indicates that applying a delta failed."""
147 def __init__(self, *args: object, **kwargs: object) -> None:
148 """Initialize an ApplyDeltaError.
150 Args:
151 *args: Error message and additional positional arguments.
152 **kwargs: Additional keyword arguments.
153 """
154 Exception.__init__(self, *args, **kwargs)
157class NotGitRepository(Exception):
158 """Indicates that no Git repository was found."""
160 def __init__(self, *args: object, **kwargs: object) -> None:
161 """Initialize a NotGitRepository exception.
163 Args:
164 *args: Error message and additional positional arguments.
165 **kwargs: Additional keyword arguments.
166 """
167 Exception.__init__(self, *args, **kwargs)
170class GitProtocolError(Exception):
171 """Git protocol exception."""
173 def __init__(self, *args: object, **kwargs: object) -> None:
174 """Initialize a GitProtocolError.
176 Args:
177 *args: Error message and additional positional arguments.
178 **kwargs: Additional keyword arguments.
179 """
180 Exception.__init__(self, *args, **kwargs)
182 def __eq__(self, other: object) -> bool:
183 """Check equality between GitProtocolError instances.
185 Args:
186 other: The object to compare with.
188 Returns:
189 True if both are GitProtocolError instances with same args, False otherwise.
190 """
191 return isinstance(other, GitProtocolError) and self.args == other.args
194class SendPackError(GitProtocolError):
195 """An error occurred during send_pack."""
198class HangupException(GitProtocolError):
199 """Hangup exception."""
201 def __init__(self, stderr_lines: Optional[Sequence[bytes]] = None) -> None:
202 """Initialize a HangupException.
204 Args:
205 stderr_lines: Optional list of stderr output lines from the remote server.
206 """
207 if stderr_lines:
208 super().__init__(
209 "\n".join(
210 line.decode("utf-8", "surrogateescape") for line in stderr_lines
211 )
212 )
213 else:
214 super().__init__("The remote server unexpectedly closed the connection.")
215 self.stderr_lines = stderr_lines
217 def __eq__(self, other: object) -> bool:
218 """Check equality between HangupException instances.
220 Args:
221 other: The object to compare with.
223 Returns:
224 True if both are HangupException instances with same stderr_lines, False otherwise.
225 """
226 return (
227 isinstance(other, HangupException)
228 and self.stderr_lines == other.stderr_lines
229 )
232class UnexpectedCommandError(GitProtocolError):
233 """Unexpected command received in a proto line."""
235 def __init__(self, command: Optional[str]) -> None:
236 """Initialize an UnexpectedCommandError.
238 Args:
239 command: The unexpected command received, or None for flush-pkt.
240 """
241 command_str = "flush-pkt" if command is None else f"command {command}"
242 super().__init__(f"Protocol got unexpected {command_str}")
245class FileFormatException(Exception):
246 """Base class for exceptions relating to reading git file formats."""
249class PackedRefsException(FileFormatException):
250 """Indicates an error parsing a packed-refs file."""
253class ObjectFormatException(FileFormatException):
254 """Indicates an error parsing an object."""
257class NoIndexPresent(Exception):
258 """No index is present."""
261class CommitError(Exception):
262 """An error occurred while performing a commit."""
265class RefFormatError(Exception):
266 """Indicates an invalid ref name."""
269class HookError(Exception):
270 """An error occurred while executing a hook."""
273class WorkingTreeModifiedError(Exception):
274 """Indicates that the working tree has modifications that would be overwritten."""