Merge pull request #451 from mitsuhiko/feature/unicode-cmd
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Added support for dealing with unicode argv on win py2
authored by Armin Ronacher · committed by Armin Ronacher · parents 7951a73, 8e768e7 · Browse files · 6 files·+332 added−2 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
6 files+332 added−2 removed
- other:+332 added−2 removed
Provenance
- Commit
de79af1- Tree
ceefaa7- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent 1
7951a73- Parent 2
8e768e7
6 files changed+332 added−2 removed
modified:click/_compat.py+37 added
165 unmodified lines166 pass167 else:168 msvcrt.setmode(fileno, os.O_BINARY)169 return f170+171+ class WindowsConsole(_FixupStream):172+ def __repr__(self):173+ return '<%s name=%r>' % (174+ self.__class__.__name__,175+ self.name,176+ )177+178+ from ._winconsole import _get_windows_console_stream179 else:180 set_binary_mode = lambda x: x181+ _get_windows_console_stream = lambda *x: None182 183 def isidentifier(x):184 return _identifier_re.search(x) is not None185 6 unmodified lines192 def get_binary_stderr():193 return set_binary_mode(sys.stderr)194 195 def get_text_stdin(encoding=None, errors=None):196+ rv = _get_windows_console_stream(sys.stdin, encoding, errors)197+ if rv is not None:198+ return rv199 return _make_text_stream(sys.stdin, encoding, errors)200 201 def get_text_stdout(encoding=None, errors=None):202+ rv = _get_windows_console_stream(sys.stdout, encoding, errors)203+ if rv is not None:204+ return rv205 return _make_text_stream(sys.stdout, encoding, errors)206 207 def get_text_stderr(encoding=None, errors=None):208+ rv = _get_windows_console_stream(sys.stderr, encoding, errors)209+ if rv is not None:210+ return rv211 return _make_text_stream(sys.stderr, encoding, errors)212 213 def filename_to_ui(value):214 if isinstance(value, bytes):299 unmodified lines514 if WIN:515 # Windows has a smaller terminal516 DEFAULT_COLUMNS = 79517 518+ def _get_argv_encoding():519+ import locale520+ return locale.getpreferredencoding()521+522+ if PY2:523+ def raw_input(prompt=''):524+ sys.stderr.flush()525+ if prompt:526+ stdout = _default_text_stdout()527+ stdout.write(prompt)528+ stdin = _default_text_stdin()529+ return stdin.readline().rstrip('\r\n')530+531 try:532 import colorama533 except ImportError:534 pass34 unmodified lines569 def get_winterm_size():570 win = colorama.win32.GetConsoleScreenBufferInfo(571 colorama.win32.STDOUT).srWindow572 return win.Right - win.Left, win.Bottom - win.Top573+else:574+ def _get_argv_encoding():575+ return getattr(sys.stdin, 'encoding', None) or get_filesystem_encoding()576 577 578 def term_len(x):579 return len(strip_ansi(x))31 unmodified lines611 return rv612 return func613 614 615+_default_text_stdin = _make_cached_stream_func(616+ lambda: sys.stdin, get_text_stdin)617 _default_text_stdout = _make_cached_stream_func(618 lambda: sys.stdout, get_text_stdout)619 _default_text_stderr = _make_cached_stream_func(620 lambda: sys.stderr, get_text_stderr)13 unmodified linesadded:click/_winconsole.py+248 added
1+# -*- coding: utf-8 -*-2+# This module is based on the excellent work by Adam Bartoš who3+# provided a lot of what went into the implementation here in4+# the discussion to issue1602 in the Python bug tracker.5+#6+# There are some general differences in regards to how this works7+# compared to the original patches as we do not need to patch8+# the entire interpreter but just work in our little world of9+# echo and prmopt.10+11+import io12+import sys13+import ctypes14+from click._compat import _NonClosingTextIOWrapper, text_type15+from ctypes import byref, POINTER, pythonapi, c_int, c_char, c_char_p, \16+ c_void_p, py_object, c_ssize_t, c_ulong, windll, WINFUNCTYPE17+from ctypes.wintypes import LPWSTR, LPCWSTR18+19+20+PY2 = sys.version_info[0] == 221+22+c_ssize_p = POINTER(c_ssize_t)23+24+PyObject_GetBuffer = pythonapi.PyObject_GetBuffer25+PyBuffer_Release = pythonapi.PyBuffer_Release26+27+kernel32 = windll.kernel3228+GetStdHandle = kernel32.GetStdHandle29+ReadConsoleW = kernel32.ReadConsoleW30+WriteConsoleW = kernel32.WriteConsoleW31+GetLastError = kernel32.GetLastError32+GetCommandLineW = WINFUNCTYPE(LPWSTR)(33+ ('GetCommandLineW', windll.kernel32))34+CommandLineToArgvW = WINFUNCTYPE(35+ POINTER(LPWSTR), LPCWSTR, POINTER(c_int))(36+ ('CommandLineToArgvW', windll.shell32))37+38+39+STDIN_HANDLE = GetStdHandle(-10)40+STDOUT_HANDLE = GetStdHandle(-11)41+STDERR_HANDLE = GetStdHandle(-12)42+43+44+PyBUF_SIMPLE = 045+PyBUF_WRITABLE = 146+47+ERROR_SUCCESS = 048+ERROR_NOT_ENOUGH_MEMORY = 849+ERROR_OPERATION_ABORTED = 99550+51+STDIN_FILENO = 052+STDOUT_FILENO = 153+STDERR_FILENO = 254+55+EOF = b'\x1a'56+MAX_BYTES_WRITTEN = 3276757+58+59+class Py_buffer(ctypes.Structure):60+ _fields_ = [61+ ('buf', c_void_p),62+ ('obj', py_object),63+ ('len', c_ssize_t),64+ ('itemsize', c_ssize_t),65+ ('readonly', c_int),66+ ('ndim', c_int),67+ ('format', c_char_p),68+ ('shape', c_ssize_p),69+ ('strides', c_ssize_p),70+ ('suboffsets', c_ssize_p),71+ ('internal', c_void_p)72+ ]73+74+ if PY2:75+ _fields_.insert(-1, ('smalltable', c_ssize_t * 2))76+77+78+def get_buffer(obj, writable=False):79+ buf = Py_buffer()80+ flags = PyBUF_WRITABLE if writable else PyBUF_SIMPLE81+ PyObject_GetBuffer(py_object(obj), byref(buf), flags)82+ try:83+ buffer_type = c_char * buf.len84+ return buffer_type.from_address(buf.buf)85+ finally:86+ PyBuffer_Release(byref(buf))87+88+89+class _WindowsConsoleRawIOBase(io.RawIOBase):90+91+ def __init__(self, handle):92+ self.handle = handle93+94+ def isatty(self):95+ super(WindowsConsoleRawIOBase, self).isatty()96+ return True97+98+99+class _WindowsConsoleReader(_WindowsConsoleRawIOBase):100+101+ def readable(self):102+ return True103+104+ def readinto(self, b):105+ bytes_to_be_read = len(b)106+ if not bytes_to_be_read:107+ return 0108+ elif bytes_to_be_read % 2:109+ raise ValueError('cannot read odd number of bytes from '110+ 'UTF-16-LE encoded console')111+112+ buffer = get_buffer(b, writable=True)113+ code_units_to_be_read = bytes_to_be_read // 2114+ code_units_read = c_ulong()115+116+ rv = ReadConsoleW(self.handle, buffer, code_units_to_be_read,117+ byref(code_units_read), None)118+ if GetLastError() == ERROR_OPERATION_ABORTED:119+ # wait for KeyboardInterrupt120+ time.sleep(0.1)121+ if not rv:122+ raise OSError('Windows error: %s' % GetLastError())123+124+ if buffer[0] == EOF:125+ return 0126+ return 2 * code_units_read.value127+128+129+class _WindowsConsoleWriter(_WindowsConsoleRawIOBase):130+131+ def writable(self):132+ return True133+134+ @staticmethod135+ def _get_error_message(errno):136+ if errno == ERROR_SUCCESS:137+ return 'ERROR_SUCCESS'138+ elif errno == ERROR_NOT_ENOUGH_MEMORY:139+ return 'ERROR_NOT_ENOUGH_MEMORY'140+ return 'Windows error %s' % errno141+142+ def write(self, b):143+ bytes_to_be_written = len(b)144+ buf = get_buffer(b)145+ code_units_to_be_written = min(bytes_to_be_written,146+ MAX_BYTES_WRITTEN) // 2147+ code_units_written = c_ulong()148+149+ WriteConsoleW(self.handle, buf, code_units_to_be_written,150+ byref(code_units_written), None)151+ bytes_written = 2 * code_units_written.value152+153+ if bytes_written == 0 and bytes_to_be_written > 0:154+ raise OSError(self._get_error_message(GetLastError()))155+ return bytes_written156+157+158+class ConsoleStream(object):159+160+ def __init__(self, text_stream, byte_stream):161+ self._text_stream = text_stream162+ self.buffer = byte_stream163+164+ @property165+ def name(self):166+ return self.buffer.name167+168+ def write(self, x):169+ if isinstance(x, text_type):170+ return self._text_stream.write(x)171+ try:172+ self.flush()173+ except Exception:174+ pass175+ return self.buffer.write(x)176+177+ def writelines(self, lines):178+ for line in lines:179+ self.write(line)180+181+ def __getattr__(self, name):182+ return getattr(self._text_stream, name)183+184+ def isatty(self):185+ return self.buffer.isatty()186+187+ def __repr__(self):188+ return '<ConsoleStream name=%r encoding=%r>' % (189+ self.name,190+ self.encoding,191+ )192+193+194+def _get_text_stdin():195+ text_stream = _NonClosingTextIOWrapper(196+ io.BufferedReader(_WindowsConsoleReader(STDIN_HANDLE)),197+ 'utf-16-le', 'strict', line_buffering=True)198+ return ConsoleStream(text_stream, sys.stdin)199+200+201+def _get_text_stdout():202+ text_stream = _NonClosingTextIOWrapper(203+ _WindowsConsoleWriter(STDOUT_HANDLE),204+ 'utf-16-le', 'strict', line_buffering=True)205+ return ConsoleStream(text_stream, sys.stdout)206+207+208+def _get_text_stderr():209+ text_stream = _NonClosingTextIOWrapper(210+ _WindowsConsoleWriter(STDERR_HANDLE),211+ 'utf-16-le', 'strict', line_buffering=True)212+ return ConsoleStream(text_stream, sys.stderr)213+214+215+def _get_windows_argv():216+ argc = c_int(0)217+ argv_unicode = CommandLineToArgvW(GetCommandLineW(), byref(argc))218+ argv = [argv_unicode[i] for i in range(0, argc.value)]219+220+ if not hasattr(sys, 'frozen'):221+ argv = argv[1:]222+ while len(argv) > 0:223+ arg = argv[0]224+ if not arg.startswith('-') or arg == '-':225+ break226+ argv = argv[1:]227+ if arg == '-m':228+ break229+ if arg == '-c':230+ argv[0] = '-c'231+ break232+233+ return argv234+235+236+_stream_factories = {237+ 0: _get_text_stdin,238+ 1: _get_text_stdout,239+ 2: _get_text_stderr,240+}241+242+243+def _get_windows_console_stream(f, encoding, errors):244+ if encoding in ('utf-16-le', None) \245+ and errors in ('strict', None):246+ func = _stream_factories.get(f.fileno())247+ if func is not None:248+ return func()modified:click/core.py+3 added-1 removed
668 unmodified lines669 else:670 _check_for_unicode_literals()671 672 if args is None:673- args = sys.argv[1:]673+ args = get_os_args()674 else:675 args = list(args)676+677 if prog_name is None:678 prog_name = make_str(os.path.basename(679 sys.argv and sys.argv[0] or __file__))680 1030 unmodified lines1711 1712 1713 # Circular dependency between decorators and core1714 from .decorators import command, group1715+from .utils import get_os_argsmodified:click/types.py+14 added-1 removed
352 unmodified lines353 :param readable: if true, a readable check is performed.354 :param resolve_path: if this is true, then the path is fully resolved355 before the value is passed onwards. This means356 that it's absolute and symlinks are resolved.357+ :param type: optionally a string type that should be used to358+ represent the path. The default is `None` which359+ means the return value will be either bytes or360+ unicode depending on what makes most sense given the361+ input data Click deals with.362 """363 envvar_list_splitter = os.path.pathsep364 365 def __init__(self, exists=False, file_okay=True, dir_okay=True,361- writable=False, readable=True, resolve_path=False):366+ writable=False, readable=True, resolve_path=False,367+ path_type=None):368 self.exists = exists369 self.file_okay = file_okay370 self.dir_okay = dir_okay371 self.writable = writable372 self.readable = readable373 self.resolve_path = resolve_path374+ self.type = path_type375 376 if self.file_okay and not self.dir_okay:377 self.name = 'file'378 self.path_type = 'File'39 unmodified lines418 self.path_type,419 filename_to_ui(value)420 ), param, ctx)421 422+ if self.type is not None and not isinstance(rv, self.type):423+ if self.type is text_type:424+ rv = rv.decode(get_filesystem_encoding())425+ else:426+ rv = rv.encode(get_filesystem_encoding())427+428 return rv429 430 431 class Tuple(CompositeParamType):105 unmodified linesmodified:click/utils.py+19 added
9 unmodified lines10 _default_text_stdout, _default_text_stderr, is_bytes, WIN11 12 if not PY2:13 from ._compat import _find_binary_writer14+ if WIN:15+ from ._winconsole import _get_windows_argv16 17 18 echo_native_types = string_types + (bytes, bytearray)19 362 unmodified lines382 f = KeepOpenFile(f)383 return f384 385 386+def get_os_args():387+ """This returns the argument part of sys.argv in the most appropriate388+ form for processing. What this means is that this return value is in389+ a format that works for Click to process but does not necessarily390+ correspond well to what's actually standard for the interpreter.391+392+ On most environments the return value is ``sys.argv[:1]`` unchanged.393+ However if you are on Windows and running Python 2 the return value394+ will actually be a list of unicode strings instead because the395+ default behavior on that platform otherwise will not be able to396+ carry all possible values that sys.argv can have.397+ """398+ if not PY2 or os.name != 'nt':399+ return sys.argv[1:]400+ return _get_windows_argv()401+402+403 def format_filename(filename, shorten=False):404 """Formats a filename for user display. The main purpose of this405 function is to ensure that the filename can be displayed at all. This406 will decode the filename to unicode if necessary in a way that it will62 unmodified linesmodified:CHANGES+11 added
20 unmodified lines21 available.22 - Click used to return byte strings on Python 2 in some unit-testing23 situations. This has been fixed to correctly return unicode strings24 now.25+- For Windows users on Python 2, Click will now handle Unicode more26+ correctly handle Unicode coming in from the system. This also has27+ the disappointing side effect that filenames will now be always28+ unicode by default in the `Path` type which means that this can29+ introduce small bugs for code not aware of this.30+- Added a `type` parameter to `Path` to force a specific string type31+ on the value.32+- For users running Python 2 the echo() and prompt() functions now work33+ with unicode in the Python windows console. For Python 3 the work34+ is delegated to the Python interpreter as general support for Unicode35+ in the console is implemented to some degree.36 37 Version 5.138 -----------39 251 unmodified lines