_winconsole.py
This file
Path
src/click/_winconsole.py
295 lines · 8.2 KiB · Python
Last changed by
Improve typing on Windows (#2803)Andreas Backxbefore adoption45f89cd
History of this fileTake it
1# This module is based on the excellent work by Adam Bartoš who2# provided a lot of what went into the implementation here in3# the discussion to issue1602 in the Python bug tracker.4#5# There are some general differences in regards to how this works6# compared to the original patches as we do not need to patch7# the entire interpreter but just work in our little world of8# echo and prompt.9from __future__ import annotations1011import collections.abc as cabc12import io13import sys14import time15import typing as t16from ctypes import Array17from ctypes import byref18from ctypes import c_char19from ctypes import c_char_p20from ctypes import c_int21from ctypes import c_ssize_t22from ctypes import c_ulong23from ctypes import c_void_p24from ctypes import POINTER25from ctypes import py_object26from ctypes import Structure27from ctypes.wintypes import DWORD28from ctypes.wintypes import HANDLE29from ctypes.wintypes import LPCWSTR30from ctypes.wintypes import LPWSTR3132from ._compat import _NonClosingTextIOWrapper3334assert sys.platform == "win32"35import msvcrt # noqa: E40236from ctypes import windll # noqa: E40237from ctypes import WINFUNCTYPE # noqa: E4023839c_ssize_p = POINTER(c_ssize_t)4041kernel32 = windll.kernel3242GetStdHandle = kernel32.GetStdHandle43ReadConsoleW = kernel32.ReadConsoleW44WriteConsoleW = kernel32.WriteConsoleW45GetConsoleMode = kernel32.GetConsoleMode46GetLastError = kernel32.GetLastError47GetCommandLineW = WINFUNCTYPE(LPWSTR)(("GetCommandLineW", windll.kernel32))48CommandLineToArgvW = WINFUNCTYPE(POINTER(LPWSTR), LPCWSTR, POINTER(c_int))(49 ("CommandLineToArgvW", windll.shell32)50)51LocalFree = WINFUNCTYPE(c_void_p, c_void_p)(("LocalFree", windll.kernel32))5253STDIN_HANDLE = GetStdHandle(-10)54STDOUT_HANDLE = GetStdHandle(-11)55STDERR_HANDLE = GetStdHandle(-12)5657PyBUF_SIMPLE = 058PyBUF_WRITABLE = 15960ERROR_SUCCESS = 061ERROR_NOT_ENOUGH_MEMORY = 862ERROR_OPERATION_ABORTED = 9956364STDIN_FILENO = 065STDOUT_FILENO = 166STDERR_FILENO = 26768EOF = b"\x1a"69MAX_BYTES_WRITTEN = 327677071if 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 Buffer7879try:80 from ctypes import pythonapi81except ImportError:82 # On PyPy we cannot get buffers so our ability to operate here is83 # severely limited.84 get_buffer = None85else:8687 class Py_buffer(Structure):88 _fields_ = [ # noqa: RUF01289 ("buf", c_void_p),90 ("obj", py_object),91 ("len", c_ssize_t),92 ("itemsize", c_ssize_t),93 ("readonly", c_int),94 ("ndim", c_int),95 ("format", c_char_p),96 ("shape", c_ssize_p),97 ("strides", c_ssize_p),98 ("suboffsets", c_ssize_p),99 ("internal", c_void_p),100 ]101102 PyObject_GetBuffer = pythonapi.PyObject_GetBuffer103 PyBuffer_Release = pythonapi.PyBuffer_Release104105 def get_buffer(obj: Buffer, writable: bool = False) -> Array[c_char]:106 buf = Py_buffer()107 flags: int = PyBUF_WRITABLE if writable else PyBUF_SIMPLE108 PyObject_GetBuffer(py_object(obj), byref(buf), flags)109110 try:111 buffer_type: Array[c_char] = c_char * buf.len112 return buffer_type.from_address(buf.buf)113 finally:114 PyBuffer_Release(byref(buf))115116117class _WindowsConsoleRawIOBase(io.RawIOBase):118 def __init__(self, handle: int | None) -> None:119 self.handle = handle120121 def isatty(self) -> t.Literal[True]:122 super().isatty()123 return True124125126class _WindowsConsoleReader(_WindowsConsoleRawIOBase):127 def readable(self) -> t.Literal[True]:128 return True129130 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:135 raise ValueError(136 "cannot read odd number of bytes from UTF-16-LE encoded console"137 )138139 buffer = get_buffer(b, writable=True)140 code_units_to_be_read = bytes_to_be_read // 2141 code_units_read = c_ulong()142143 rv = ReadConsoleW(144 HANDLE(self.handle),145 buffer,146 code_units_to_be_read,147 byref(code_units_read),148 None,149 )150 if GetLastError() == ERROR_OPERATION_ABORTED:151 # wait for KeyboardInterrupt152 time.sleep(0.1)153 if not rv:154 raise OSError(f"Windows error: {GetLastError()}")155156 if buffer[0] == EOF:157 return 0158 return 2 * code_units_read.value159160161class _WindowsConsoleWriter(_WindowsConsoleRawIOBase):162 def writable(self) -> t.Literal[True]:163 return True164165 @staticmethod166 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}"172173 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()178179 WriteConsoleW(180 HANDLE(self.handle),181 buf,182 code_units_to_be_written,183 byref(code_units_written),184 None,185 )186 bytes_written = 2 * code_units_written.value187188 if bytes_written == 0 and bytes_to_be_written > 0:189 raise OSError(self._get_error_message(GetLastError()))190 return bytes_written191192193class ConsoleStream:194 def __init__(self, text_stream: t.TextIO, byte_stream: t.BinaryIO) -> None:195 self._text_stream = text_stream196 self.buffer = byte_stream197198 @property199 def name(self) -> str:200 return self.buffer.name201202 def write(self, x: t.AnyStr) -> int:203 if isinstance(x, str):204 return self._text_stream.write(x)205 try:206 self.flush()207 except Exception:208 pass209 return self.buffer.write(x)210211 def writelines(self, lines: cabc.Iterable[t.AnyStr]) -> None:212 for line in lines:213 self.write(line)214215 def __getattr__(self, name: str) -> t.Any:216 return getattr(self._text_stream, name)217218 def isatty(self) -> bool:219 return self.buffer.isatty()220221 def __repr__(self) -> str:222 return f"<ConsoleStream name={self.name!r} encoding={self.encoding!r}>"223224225def _get_text_stdin(buffer_stream: t.BinaryIO) -> t.TextIO:226 text_stream = _NonClosingTextIOWrapper(227 io.BufferedReader(_WindowsConsoleReader(STDIN_HANDLE)),228 "utf-16-le",229 "strict",230 line_buffering=True,231 )232 return t.cast(t.TextIO, ConsoleStream(text_stream, buffer_stream))233234235def _get_text_stdout(buffer_stream: t.BinaryIO) -> t.TextIO:236 text_stream = _NonClosingTextIOWrapper(237 io.BufferedWriter(_WindowsConsoleWriter(STDOUT_HANDLE)),238 "utf-16-le",239 "strict",240 line_buffering=True,241 )242 return t.cast(t.TextIO, ConsoleStream(text_stream, buffer_stream))243244245def _get_text_stderr(buffer_stream: t.BinaryIO) -> t.TextIO:246 text_stream = _NonClosingTextIOWrapper(247 io.BufferedWriter(_WindowsConsoleWriter(STDERR_HANDLE)),248 "utf-16-le",249 "strict",250 line_buffering=True,251 )252 return t.cast(t.TextIO, ConsoleStream(text_stream, buffer_stream))253254255_stream_factories: cabc.Mapping[int, t.Callable[[t.BinaryIO], t.TextIO]] = {256 0: _get_text_stdin,257 1: _get_text_stdout,258 2: _get_text_stderr,259}260261262def _is_console(f: t.TextIO) -> bool:263 if not hasattr(f, "fileno"):264 return False265266 try:267 fileno = f.fileno()268 except (OSError, io.UnsupportedOperation):269 return False270271 handle = msvcrt.get_osfhandle(fileno)272 return bool(GetConsoleMode(handle, byref(DWORD())))273274275def _get_windows_console_stream(276 f: t.TextIO, encoding: str | None, errors: str | None277) -> t.TextIO | None:278 if (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 ):284 return None285286 func = _stream_factories.get(f.fileno())287 if func is None:288 return None289290 b = getattr(f, "buffer", None)291292 if b is None:293 return None294295 return func(b)