Debian Codegraph @

mypy/dmypy_util.py

raw
1 """Shared code between dmypy.py and dmypy_server.py.
2
3 This should be pretty lightweight and not depend on other mypy code (other than ipc).
4 """
5
6 from __future__ import annotations
7
8 import io
9 import json
10 from collections.abc import Iterable, Iterator
11 from types import TracebackType
12 from typing import Any, Final, TextIO
13
14 from mypy.ipc import IPCBase
15
16 DEFAULT_STATUS_FILE: Final = ".dmypy.json"
17
18
19 def receive(connection: IPCBase) -> Any:
20 """Receive single JSON data frame from a connection.
21
22 Raise OSError if the data received is not valid JSON or if it is
23 not a dict.
24 """
25 bdata = connection.read()
26 if not bdata:
27 raise OSError("No data received")
28 try:
29 data = json.loads(bdata)
30 except Exception as e:
31 raise OSError("Data received is not valid JSON") from e
32 if not isinstance(data, dict):
33 raise OSError(f"Data received is not a dict ({type(data)})")
34 return data
35
36
37 def send(connection: IPCBase, data: Any) -> None:
38 """Send data to a connection encoded and framed.
39
40 The data must be JSON-serializable. We assume that a single send call is a
41 single frame to be sent on the connect.
42 """
43 connection.write(json.dumps(data))
44
45
46 class WriteToConn(TextIO):
47 """Helper class to write to a connection instead of standard output."""
48
49 def __init__(self, server: IPCBase, output_key: str, isatty: bool) -> None:
50 self.server = server
51 self.output_key = output_key
52 self._isatty = isatty
53
54 def __enter__(self) -> TextIO:
55 return self
56
57 def __exit__(
58 self,
59 t: type[BaseException] | None,
60 value: BaseException | None,
61 traceback: TracebackType | None,
62 ) -> None:
63 pass
64
65 def __iter__(self) -> Iterator[str]:
66 raise io.UnsupportedOperation
67
68 def __next__(self) -> str:
69 raise io.UnsupportedOperation
70
71 def close(self) -> None:
72 pass
73
74 def fileno(self) -> int:
75 raise OSError
76
77 def flush(self) -> None:
78 pass
79
80 def isatty(self) -> bool:
81 return self._isatty
82
83 def read(self, n: int = 0) -> str:
84 raise io.UnsupportedOperation
85
86 def readable(self) -> bool:
87 return False
88
89 def readline(self, limit: int = 0) -> str:
90 raise io.UnsupportedOperation
91
92 def readlines(self, hint: int = 0) -> list[str]:
93 raise io.UnsupportedOperation
94
95 def seek(self, offset: int, whence: int = 0) -> int:
96 raise io.UnsupportedOperation
97
98 def seekable(self) -> bool:
99 return False
100
101 def tell(self) -> int:
102 raise io.UnsupportedOperation
103
104 def truncate(self, size: int | None = 0) -> int:
105 raise io.UnsupportedOperation
106
107 def write(self, output: str) -> int:
108 resp: dict[str, Any] = {self.output_key: output}
109 send(self.server, resp)
110 return len(output)
111
112 def writable(self) -> bool:
113 return True
114
115 def writelines(self, lines: Iterable[str]) -> None:
116 for s in lines:
117 self.write(s)