Improve typing on Windows (#2803)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Andreas Backx · committed by GitHub · parent 4ffa1ef · Browse files · 4 files·+48 added−30 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+48 added−30 removed
- other:+48 added−30 removed
Provenance
- Commit
45f89cd- Tree
23426c0- Author
Andreas Backx <AndreasBackx@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
4ffa1ef
4 files changed+48 added−30 removed
modified:src/click/_compat.py+2 added-2 removed
536 unmodified lines537 ansi_wrapper = colorama.AnsiToWin32(stream, strip=strip)538 rv = t.cast(t.TextIO, ansi_wrapper.stream)539 _write = rv.write540 541- def _safe_write(s):541+ def _safe_write(s: str) -> int:542 try:543 return _write(s)544 except BaseException:545 ansi_wrapper.reset_all()546 raise547 548- rv.write = _safe_write548+ rv.write = _safe_write # type: ignore[method-assign]549 550 try:551 _ansi_stream_wrappers[stream] = rv552 except Exception:70 unmodified linesmodified:src/click/_termui_impl.py+3 added-4 removed
672 unmodified lines673 674 return None675 676 677-if WIN:677+if sys.platform == "win32":678 import msvcrt679 680 @contextlib.contextmanager681 def raw_terminal() -> cabc.Iterator[int]:28 unmodified lines710 # limited to the current 8-bit codepage.711 #712 # Anyway, Click doesn't claim to do this Right(tm), and using `getwch`713 # is doing the right thing in more situations than with `getch`.714- func: t.Callable[[], str]714 715 if echo:717- func = msvcrt.getwche # type: ignore716+ func = t.cast(t.Callable[[], str], msvcrt.getwche)717 else:719- func = msvcrt.getwch # type: ignore718+ func = t.cast(t.Callable[[], str], msvcrt.getwch)719 720 rv = func()721 722 if rv in ("\x00", "\xe0"):47 unmodified linesmodified:src/click/_winconsole.py+34 added-21 removed
11 unmodified lines12 import io13 import sys14 import time15 import typing as t16+from ctypes import Array17 from ctypes import byref18 from ctypes import c_char19 from ctypes import c_char_p20 from ctypes import c_int46 unmodified lines67 68 EOF = b"\x1a"69 MAX_BYTES_WRITTEN = 3276770 71+if t.TYPE_CHECKING:72+ try:73+ # Using `typing_extensions.Buffer` instead of `collections.abc`74+ # on Windows for some reason does not have `Sized` implemented.75+ from collections.abc import Buffer # type: ignore76+ except ImportError:77+ from typing_extensions import Buffer78+79 try:80 from ctypes import pythonapi81 except ImportError:82 # On PyPy we cannot get buffers so our ability to operate here is18 unmodified lines101 102 PyObject_GetBuffer = pythonapi.PyObject_GetBuffer103 PyBuffer_Release = pythonapi.PyBuffer_Release104 96- def get_buffer(obj, writable=False):105+ def get_buffer(obj: Buffer, writable: bool = False) -> Array[c_char]:106 buf = Py_buffer()98- flags = PyBUF_WRITABLE if writable else PyBUF_SIMPLE107+ flags: int = PyBUF_WRITABLE if writable else PyBUF_SIMPLE108 PyObject_GetBuffer(py_object(obj), byref(buf), flags)109 110 try:102- buffer_type = c_char * buf.len111+ buffer_type: Array[c_char] = c_char * buf.len112 return buffer_type.from_address(buf.buf)113 finally:114 PyBuffer_Release(byref(buf))115 116 117 class _WindowsConsoleRawIOBase(io.RawIOBase):109- def __init__(self, handle):118+ def __init__(self, handle: int | None) -> None:119 self.handle = handle120 112- def isatty(self):121+ def isatty(self) -> t.Literal[True]:122 super().isatty()123 return True124 125 126 class _WindowsConsoleReader(_WindowsConsoleRawIOBase):118- def readable(self):127+ def readable(self) -> t.Literal[True]:128 return True129 121- def readinto(self, b):130+ def readinto(self, b: Buffer) -> int:131 bytes_to_be_read = len(b)132 if not bytes_to_be_read:133 return 0134 elif bytes_to_be_read % 2:23 unmodified lines158 return 2 * code_units_read.value159 160 161 class _WindowsConsoleWriter(_WindowsConsoleRawIOBase):153- def writable(self):162+ def writable(self) -> t.Literal[True]:163 return True164 165 @staticmethod157- def _get_error_message(errno):166+ def _get_error_message(errno: int) -> str:167 if errno == ERROR_SUCCESS:168 return "ERROR_SUCCESS"169 elif errno == ERROR_NOT_ENOUGH_MEMORY:170 return "ERROR_NOT_ENOUGH_MEMORY"171 return f"Windows error {errno}"172 164- def write(self, b):173+ def write(self, b: Buffer) -> int:174 bytes_to_be_written = len(b)175 buf = get_buffer(b)176 code_units_to_be_written = min(bytes_to_be_written, MAX_BYTES_WRITTEN) // 2177 code_units_written = c_ulong()39 unmodified lines217 218 def isatty(self) -> bool:219 return self.buffer.isatty()220 212- def __repr__(self):221+ def __repr__(self) -> str:222 return f"<ConsoleStream name={self.name!r} encoding={self.encoding!r}>"223 224 225 def _get_text_stdin(buffer_stream: t.BinaryIO) -> t.TextIO:49 unmodified lines275 def _get_windows_console_stream(276 f: t.TextIO, encoding: str | None, errors: str | None277 ) -> t.TextIO | None:278 if (270- get_buffer is not None271- and encoding in {"utf-16-le", None}272- and errors in {"strict", None}273- and _is_console(f)279+ get_buffer is None280+ or encoding not in {"utf-16-le", None}281+ or errors not in {"strict", None}282+ or not _is_console(f)283 ):275- func = _stream_factories.get(f.fileno())276- if func is not None:277- b = getattr(f, "buffer", None)284+ return None285 286+ func = _stream_factories.get(f.fileno())279- if b is None:280- return None287+ if func is None:288+ return None289 290+ b = getattr(f, "buffer", None)291+292+ if b is None:293+ return None294+282- return func(b)295+ return func(b)modified:tox.ini+9 added-3 removed
21 unmodified lines22 23 [testenv:typing]24 deps = -r requirements/typing.txt25 commands =26- mypy27- pyright tests/typing28- pyright --verifytypes click --ignoreexternal26+ mypy --platform linux27+ mypy --platform darwin28+ mypy --platform win3229+ pyright tests/typing --pythonplatform Linux30+ pyright tests/typing --pythonplatform Darwin31+ pyright tests/typing --pythonplatform Windows32+ pyright --verifytypes click --ignoreexternal --pythonplatform Linux33+ pyright --verifytypes click --ignoreexternal --pythonplatform Darwin34+ pyright --verifytypes click --ignoreexternal --pythonplatform Windows35 36 [testenv:docs]37 deps = -r requirements/docs.txt38 commands = sphinx-build -E -W -b dirhtml docs docs/_build/dirhtml23 unmodified lines