~sschwarzer/ftputil

ftputil/ftputil/error.py -rw-r--r-- 5.6 KiB
77f2ca24Stefan Schwarzer Move item "Push to repository" a month ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
# Copyright (C) 2003-2021, Stefan Schwarzer <sschwarzer@sschwarzer.net>
# and ftputil contributors (see `doc/contributors.txt`)
# See the file LICENSE for licensing terms.

"""
ftputil.error - exception classes and wrappers
"""

# pylint: disable=too-many-ancestors

import ftplib

import ftputil.path_encoding
import ftputil.tool
import ftputil.version


# You _can_ import these with `from ftputil.error import *`, - but it's _not_
# recommended.
__all__ = [
    "CommandNotImplementedError",
    "FTPIOError",
    "FTPOSError",
    "InaccessibleLoginDirError",
    "InternalError",
    "KeepAliveError",
    "NoEncodingError",
    "ParserError",
    "PermanentError",
    "RootDirError",
    "SyncError",
    "TemporaryError",
    "TimeShiftError",
]


class FTPError(Exception):
    """
    General ftputil error class.
    """

    def __init__(self, *args, original_error=None):
        super().__init__(*args)
        # `strerror`
        self.strerror = ""
        if original_error is not None:
            try:
                self.strerror = str(original_error)
            except Exception:
                # Consume all errors. If the `str` call fails, it's more
                # appropriate to ignore `original_error` than to raise an
                # exception while instantiating `FTPError`.
                pass
        elif args:
            # Assume the first argument is a string. It may be a byte string
            # though.
            try:
                self.strerror = ftputil.tool.as_str(
                    args[0], ftputil.path_encoding.DEFAULT_ENCODING
                )
            except TypeError:
                # `args[0]` isn't `str` or `bytes`.
                pass
        # `errno`
        self.errno = None
        try:
            self.errno = int(self.strerror[:3])
        except ValueError:
            # `int()` argument couldn't be converted to an integer.
            pass
        # `file_name`
        self.file_name = None

    def __str__(self):
        return "{}\nDebugging info: {}".format(
            self.strerror, ftputil.version.version_info
        )


# Internal errors are those that have more to do with the inner workings of
# ftputil than with errors on the server side.
class InternalError(FTPError):
    """Internal error."""

    pass


class RootDirError(InternalError):
    """Raised for generic stat calls on the remote root directory."""

    pass


class InaccessibleLoginDirError(InternalError):
    """May be raised if the login directory isn't accessible."""

    pass


class TimeShiftError(InternalError):
    """Raised for invalid time shift values."""

    pass


class ParserError(InternalError):
    """Raised if a line of a remote directory can't be parsed."""

    pass


class CacheMissError(InternalError):
    """Raised if a path isn't found in the cache."""

    pass


class NoEncodingError(InternalError):
    """Raised if session instances don't specify an encoding."""

    pass


# Currently not used
class KeepAliveError(InternalError):
    """Raised if the keep-alive feature failed."""

    pass


class FTPOSError(FTPError, OSError):
    """Generic FTP error related to `OSError`."""

    pass


class TemporaryError(FTPOSError):
    """Raised for temporary FTP errors (4xx)."""

    pass


class PermanentError(FTPOSError):
    """Raised for permanent FTP errors (5xx)."""

    pass


class CommandNotImplementedError(PermanentError):
    """Raised if the server doesn't implement a certain feature (502)."""

    pass


class RecursiveLinksError(PermanentError):
    """Raised if an infinite link structure is detected."""

    pass


# Currently not used
class SyncError(PermanentError):
    """Raised for problems specific to syncing directories."""

    pass


class FtplibErrorToFTPOSError:
    """
    Context manager to convert `ftplib` exceptions to exceptions derived from
    `FTPOSError`.
    """

    def __enter__(self):
        pass

    def __exit__(self, exc_type, exc_value, traceback):
        if exc_type is None:
            # No exception
            return
        if isinstance(exc_value, ftplib.error_temp):
            raise TemporaryError(
                *exc_value.args, original_error=exc_value
            ) from exc_value
        elif isinstance(exc_value, ftplib.error_perm):
            # If `exc_value.args[0]` is present, assume it's a byte or unicode
            # string.
            if exc_value.args and ftputil.tool.as_str(
                exc_value.args[0], ftputil.path_encoding.DEFAULT_ENCODING
            ).startswith("502"):
                raise CommandNotImplementedError(
                    *exc_value.args, original_error=exc_value
                ) from exc_value
            else:
                raise PermanentError(
                    *exc_value.args, original_error=exc_value
                ) from exc_value
        elif isinstance(exc_value, ftplib.all_errors):
            raise FTPOSError(*exc_value.args, original_error=exc_value) from exc_value
        else:
            raise


ftplib_error_to_ftp_os_error = FtplibErrorToFTPOSError()


class FTPIOError(FTPError, IOError):
    """Generic FTP error related to `IOError`."""

    pass


class FtplibErrorToFTPIOError:
    """
    Context manager to convert `ftplib` exceptions to `FTPIOError` exceptions.
    """

    def __enter__(self):
        pass

    def __exit__(self, exc_type, exc_value, traceback):
        if exc_type is None:
            # No exception
            return
        if isinstance(exc_value, ftplib.all_errors):
            raise FTPIOError(*exc_value.args, original_error=exc_value) from exc_value
        else:
            raise


ftplib_error_to_ftp_io_error = FtplibErrorToFTPIOError()