Debian Codegraph @

src/_pytest/_py/error.py

raw
1 """create errno-specific classes for IO or os calls."""
2
3 from __future__ import annotations
4
5 from collections.abc import Callable
6 import errno
7 import os
8 import sys
9 from typing import TYPE_CHECKING
10 from typing import TypeVar
11
12
13 if TYPE_CHECKING:
14 from typing_extensions import ParamSpec
15
16 P = ParamSpec("P")
17
18 R = TypeVar("R")
19
20
21 class Error(EnvironmentError):
22 def __repr__(self) -> str:
23 return "{}.{} {!r}: {} ".format(
24 self.__class__.__module__,
25 self.__class__.__name__,
26 self.__class__.__doc__,
27 " ".join(map(str, self.args)),
28 # repr(self.args)
29 )
30
31 def __str__(self) -> str:
32 s = "[{}]: {}".format(
33 self.__class__.__doc__,
34 " ".join(map(str, self.args)),
35 )
36 return s
37
38
39 _winerrnomap = {
40 2: errno.ENOENT,
41 3: errno.ENOENT,
42 17: errno.EEXIST,
43 18: errno.EXDEV,
44 13: errno.EBUSY, # empty cd drive, but ENOMEDIUM seems unavailable
45 22: errno.ENOTDIR,
46 20: errno.ENOTDIR,
47 267: errno.ENOTDIR,
48 5: errno.EACCES, # anything better?
49 }
50
51
52 class ErrorMaker:
53 """lazily provides Exception classes for each possible POSIX errno
54 (as defined per the 'errno' module). All such instances
55 subclass EnvironmentError.
56 """
57
58 _errno2class: dict[int, type[Error]] = {}
59
60 def __getattr__(self, name: str) -> type[Error]:
61 if name[0] == "_":
62 raise AttributeError(name)
63 eno = getattr(errno, name)
64 cls = self._geterrnoclass(eno)
65 setattr(self, name, cls)
66 return cls
67
68 def _geterrnoclass(self, eno: int) -> type[Error]:
69 try:
70 return self._errno2class[eno]
71 except KeyError:
72 clsname = errno.errorcode.get(eno, f"UnknownErrno{eno}")
73 errorcls = type(
74 clsname,
75 (Error,),
76 {"__module__": "py.error", "__doc__": os.strerror(eno)},
77 )
78 self._errno2class[eno] = errorcls
79 return errorcls
80
81 def checked_call(
82 self, func: Callable[P, R], *args: P.args, **kwargs: P.kwargs
83 ) -> R:
84 """Call a function and raise an errno-exception if applicable."""
85 __tracebackhide__ = True
86 try:
87 return func(*args, **kwargs)
88 except Error:
89 raise
90 except OSError as value:
91 if not hasattr(value, "errno"):
92 raise
93 if sys.platform == "win32":
94 try:
95 # error: Invalid index type "Optional[int]" for "dict[int, int]"; expected type "int" [index]
96 # OK to ignore because we catch the KeyError below.
97 cls = self._geterrnoclass(_winerrnomap[value.errno]) # type:ignore[index]
98 except KeyError:
99 raise value
100 else:
101 # we are not on Windows, or we got a proper OSError
102 if value.errno is None:
103 cls = type(
104 "UnknownErrnoNone",
105 (Error,),
106 {"__module__": "py.error", "__doc__": None},
107 )
108 else:
109 cls = self._geterrnoclass(value.errno)
110
111 raise cls(f"{func.__name__}{args!r}")
112
113
114 _error_maker = ErrorMaker()
115 checked_call = _error_maker.checked_call
116
117
118 def __getattr__(attr: str) -> type[Error]:
119 return getattr(_error_maker, attr) # type: ignore[no-any-return]