Skip to content
Myr

Merge branch 'master' into feature/parameter_autocompletion

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Claudio Bandera · committed by Claudio Bandera · parents 8e18d48, 07a4f18 · Browse files · 26 files+815 added−109 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

26 files+815 added−109 removed

  • tests:+44 added−23 removed
  • other:+771 added−86 removed

26 files+815 added−109 removed

added:.ci/appveyor.yml+50 added
added:.ci/run_with_env.cmd+47 added
1:: To build extensions for 64 bit Python 3, we need to configure environment2:: variables to use the MSVC 2010 C++ compilers from GRMSDKX_EN_DVD.iso of:3:: MS Windows SDK for Windows 7 and .NET Framework 4 (SDK v7.1)4::5:: To build extensions for 64 bit Python 2, we need to configure environment6:: variables to use the MSVC 2008 C++ compilers from GRMSDKX_EN_DVD.iso of:7:: MS Windows SDK for Windows 7 and .NET Framework 3.5 (SDK v7.0)8::9:: 32 bit builds do not require specific environment configurations.10::11:: Note: this script needs to be run with the /E:ON and /V:ON flags for the12:: cmd interpreter, at least for (SDK v7.0)13::14:: More details at:15:: https://github.com/cython/cython/wiki/64BitCythonExtensionsOnWindows16:: http://stackoverflow.com/a/13751649/16374017::18:: Author: Olivier Grisel19:: License: CC0 1.0 Universal: http://creativecommons.org/publicdomain/zero/1.0/20@ECHO OFF2122SET COMMAND_TO_RUN=%*23SET WIN_SDK_ROOT=C:\Program Files\Microsoft SDKs\Windows2425SET MAJOR_PYTHON_VERSION="%PYTHON_VERSION:~0,1%"26IF %MAJOR_PYTHON_VERSION% == "2" (27 SET WINDOWS_SDK_VERSION="v7.0"28) ELSE IF %MAJOR_PYTHON_VERSION% == "3" (29 SET WINDOWS_SDK_VERSION="v7.1"30) ELSE (31 ECHO Unsupported Python version: "%MAJOR_PYTHON_VERSION%"32 EXIT 133)3435IF "%PYTHON_ARCH%"=="64" (36 ECHO Configuring Windows SDK %WINDOWS_SDK_VERSION% for Python %MAJOR_PYTHON_VERSION% on a 64 bit architecture37 SET DISTUTILS_USE_SDK=138 SET MSSdk=139 "%WIN_SDK_ROOT%\%WINDOWS_SDK_VERSION%\Setup\WindowsSdkVer.exe" -q -version:%WINDOWS_SDK_VERSION%40 "%WIN_SDK_ROOT%\%WINDOWS_SDK_VERSION%\Bin\SetEnv.cmd" /x64 /release41 ECHO Executing: %COMMAND_TO_RUN%42 call %COMMAND_TO_RUN% || EXIT 143) ELSE (44 ECHO Using default MSVC build environment for 32 bit architecture45 ECHO Executing: %COMMAND_TO_RUN%46 call %COMMAND_TO_RUN% || EXIT 147)
modified:click/__init__.py+2 added-2 removed
30 unmodified lines
31 STRING, INT, FLOAT, BOOL, UUID, UNPROCESSED3233# Utilities34from .utils import echo, get_binary_stream, get_text_stream, open_file, \35 format_filename, get_app_dir35 format_filename, get_app_dir, get_os_args3637# Terminal functions38from .termui import prompt, confirm, get_terminal_size, echo_via_pager, \39 progressbar, clear, style, unstyle, secho, edit, launch, getchar, \
28 unmodified lines
68 'INT', 'FLOAT', 'BOOL', 'UUID', 'UNPROCESSED',6970 # Utilities71 'echo', 'get_binary_stream', 'get_text_stream', 'open_file',72 'format_filename', 'get_app_dir',72 'format_filename', 'get_app_dir', 'get_os_args',7374 # Terminal functions75 'prompt', 'confirm', 'get_terminal_size', 'echo_via_pager',76 'progressbar', 'clear', 'style', 'unstyle', 'secho', 'edit', 'launch',
20 unmodified lines
modified:click/_compat.py+55 added-37 removed
3 unmodified lines
4import sys5import codecs6from weakref import WeakKeyDictionary78import click8109PY2 = sys.version_info[0] == 210WIN = sys.platform.startswith('win')11DEFAULT_COLUMNS = 80121314_ansi_re = re.compile('\033\[((?:\d|;)*)([a-zA-Z])')151619def _find_unicode_literals_frame():20 import __future__21 frm = sys._getframe(1)22 idx = 123 while frm is not None:24 if frm.f_globals.get('__name__', '').startswith('click.'):25 frm = frm.f_back26 idx += 127 elif frm.f_code.co_flags & __future__.unicode_literals.compiler_flag:28 return idx29 else:30 break31 return 0323334def _check_for_unicode_literals():35 if not __debug__:36 return37 if not PY2 or click.disable_unicode_literals_warning:38 return39 bad_frame = _find_unicode_literals_frame()40 if bad_frame <= 0:41 return42 from warnings import warn43 warn(Warning('Click detected the use of the unicode_literals '44 '__future__ import. This is heavily discouraged '45 'because it can introduce subtle bugs in your '46 'code. You should instead use explicit u"" literals '47 'for your unicode strings. For more information see '48 'http://click.pocoo.org/python3/'),49 stacklevel=bad_frame)505117def get_filesystem_encoding():18 return sys.getfilesystemencoding() or sys.getdefaultencoding()1920
135 unmodified lines
156 # An option would be to do what Python 3 does and to open the file as157 # binary only, patch it back to the system, and then use a wrapper158 # stream that converts newlines. It's not quite clear what's the159 # correct option here.160 #161 # This code also lives in _winconsole for the fallback to the console162 # emulation stream.163 if WIN:164 import msvcrt165 def set_binary_mode(f):166 try:
18 unmodified lines
185 def get_binary_stderr():186 return set_binary_mode(sys.stderr)187188 def get_text_stdin(encoding=None, errors=None):189 rv = _get_windows_console_stream(sys.stdin, encoding, errors)190 if rv is not None:191 return rv192 return _make_text_stream(sys.stdin, encoding, errors)193194 def get_text_stdout(encoding=None, errors=None):195 rv = _get_windows_console_stream(sys.stdout, encoding, errors)196 if rv is not None:197 return rv198 return _make_text_stream(sys.stdout, encoding, errors)199200 def get_text_stderr(encoding=None, errors=None):201 rv = _get_windows_console_stream(sys.stderr, encoding, errors)202 if rv is not None:203 return rv204 return _make_text_stream(sys.stderr, encoding, errors)205206 def filename_to_ui(value):207 if isinstance(value, bytes):
161 unmodified lines
369 'stream for sys.stderr.')370 return writer371372 def get_text_stdin(encoding=None, errors=None):373 rv = _get_windows_console_stream(sys.stdin, encoding, errors)374 if rv is not None:375 return rv376 return _force_correct_text_reader(sys.stdin, encoding, errors)377378 def get_text_stdout(encoding=None, errors=None):379 rv = _get_windows_console_stream(sys.stdout, encoding, errors)380 if rv is not None:381 return rv382 return _force_correct_text_writer(sys.stdout, encoding, errors)383384 def get_text_stderr(encoding=None, errors=None):385 rv = _get_windows_console_stream(sys.stderr, encoding, errors)386 if rv is not None:387 return rv388 return _force_correct_text_writer(sys.stderr, encoding, errors)389390 def filename_to_ui(value):391 if isinstance(value, bytes):
65 unmodified lines
457 return _AtomicFile(f, tmp_filename, filename), True458459460# Used in a destructor call, needs extra protection from interpreter cleanup.461if hasattr(os, 'replace'):462 _replace = os.replace463 _can_replace = True464else:475_rename = os.rename465 _replace = os.rename466 _can_replace = not WIN467468469class _AtomicFile(object):470
10 unmodified lines
481 def close(self, delete=False):482 if self.closed:483 return484 self._f.close()485 if not _can_replace:486 try:487 os.remove(self._real_filename)488 except OSError:489 pass494 _rename(self._tmp_filename, self._real_filename)490 _replace(self._tmp_filename, self._real_filename)491 self.closed = True492493 def __getattr__(self, name):494 return getattr(self._f, name)
31 unmodified lines
526if WIN:527 # Windows has a smaller terminal528 DEFAULT_COLUMNS = 79529530 from ._winconsole import _get_windows_console_stream531532 def _get_argv_encoding():533 import locale534 return locale.getpreferredencoding()535536 if PY2:537 def raw_input(prompt=''):538 sys.stderr.flush()539 if prompt:540 stdout = _default_text_stdout()541 stdout.write(prompt)542 stdin = _default_text_stdin()543 return stdin.readline().rstrip('\r\n')544545 try:546 import colorama547 except ImportError:548 pass
34 unmodified lines
583 def get_winterm_size():584 win = colorama.win32.GetConsoleScreenBufferInfo(585 colorama.win32.STDOUT).srWindow586 return win.Right - win.Left, win.Bottom - win.Top587else:588 def _get_argv_encoding():589 return getattr(sys.stdin, 'encoding', None) or get_filesystem_encoding()590591 _get_windows_console_stream = lambda *x: None592593594def term_len(x):595 return len(strip_ansi(x))596597
22 unmodified lines
620 return rv621 return func622623624_default_text_stdin = _make_cached_stream_func(625 lambda: sys.stdin, get_text_stdin)626_default_text_stdout = _make_cached_stream_func(627 lambda: sys.stdout, get_text_stdout)628_default_text_stderr = _make_cached_stream_func(629 lambda: sys.stderr, get_text_stderr)
13 unmodified lines
modified:click/_termui_impl.py+12 added-1 removed
127 unmodified lines
128 return 0.0129130 def format_eta(self):131 if self.eta_known:132 return time.strftime('%H:%M:%S', time.gmtime(self.eta + 1))132 t = self.eta + 1133 seconds = t % 60134 t /= 60135 minutes = t % 60136 t /= 60137 hours = t % 24138 t /= 24139 if t > 0:140 days = t141 return '%dd %02d:%02d:%02d' % (days, hours, minutes, seconds)142 else:143 return '%02d:%02d:%02d' % (hours, minutes, seconds)144 return ''145146 def format_pos(self):147 pos = str(self.pos)
398 unmodified lines
added:click/_unicodefun.py+114 added
1import os2import sys3import codecs45from ._compat import PY2678# If someone wants to vendor click, we want to ensure the9# correct package is discovered. Ideally we could use a10# relative import here but unfortunately Python does not11# support that.12click = sys.modules[__name__.rsplit('.', 1)[0]]131415def _find_unicode_literals_frame():16 import __future__17 frm = sys._getframe(1)18 idx = 119 while frm is not None:20 if frm.f_globals.get('__name__', '').startswith('click.'):21 frm = frm.f_back22 idx += 123 elif frm.f_code.co_flags & __future__.unicode_literals.compiler_flag:24 return idx25 else:26 break27 return 0282930def _check_for_unicode_literals():31 if not __debug__:32 return33 if not PY2 or click.disable_unicode_literals_warning:34 return35 bad_frame = _find_unicode_literals_frame()36 if bad_frame <= 0:37 return38 from warnings import warn39 warn(Warning('Click detected the use of the unicode_literals '40 '__future__ import. This is heavily discouraged '41 'because it can introduce subtle bugs in your '42 'code. You should instead use explicit u"" literals '43 'for your unicode strings. For more information see '44 'http://click.pocoo.org/python3/'),45 stacklevel=bad_frame)464748def _verify_python3_env():49 """Ensures that the environment is good for unicode on Python 3."""50 if PY2:51 return52 try:53 import locale54 fs_enc = codecs.lookup(locale.getpreferredencoding()).name55 except Exception:56 fs_enc = 'ascii'57 if fs_enc != 'ascii':58 return5960 extra = ''61 if os.name == 'posix':62 import subprocess63 rv = subprocess.Popen(['locale', '-a'], stdout=subprocess.PIPE,64 stderr=subprocess.PIPE).communicate()[0]65 good_locales = set()66 has_c_utf8 = False67 for line in rv.splitlines():68 locale = line.strip()69 if locale.lower().endswith(('.utf-8', '.utf8')):70 good_locales.add(locale)71 if locale.lower() in ('c.utf8', 'c.utf-8'):72 has_c_utf8 = True7374 extra += '\n\n'75 if not good_locales:76 extra += (77 'Additional information: on this system no suitable UTF-8\n'78 'locales were discovered. This most likely requires resolving\n'79 'by reconfiguring the locale system.'80 )81 elif has_c_utf8:82 extra += (83 'This system supports the C.UTF-8 locale which is recommended.\n'84 'You might be able to resolve your issue by exporting the\n'85 'following environment variables:\n\n'86 ' export LC_ALL=C.UTF-8\n'87 ' export LANG=C.UTF-8'88 )89 else:90 extra += (91 'This system lists a couple of UTF-8 supporting locales that\n'92 'you can pick from. The following suitable locales where\n'93 'discovered: %s'94 ) % ', '.join(sorted(good_locales))9596 bad_locale = None97 for locale in os.environ.get('LC_ALL'), os.environ.get('LANG'):98 if locale and locale.lower().endswith(('.utf-8', '.utf8')):99 bad_locale = locale100 if locale is not None:101 break102 if bad_locale is not None:103 extra += (104 '\n\nClick discovered that you exported a UTF-8 locale\n'105 'but the locale system could not pick up from it because\n'106 'it does not exist. The exported locale is "%s" but it\n'107 'is not supported'108 ) % bad_locale109110 raise RuntimeError('Click will abort further execution because Python 3 '111 'was configured to use ASCII as encoding for the '112 'environment. Either run this under Python 2 or '113 'consult http://click.pocoo.org/python3/ for '114 'mitigation steps.' + extra)
added:click/_winconsole.py+264 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.1011import io12import os13import sys14import zlib15import time16import ctypes17import msvcrt18from click._compat import _NonClosingTextIOWrapper, text_type, PY219from ctypes import byref, POINTER, pythonapi, c_int, c_char, c_char_p, \20 c_void_p, py_object, c_ssize_t, c_ulong, windll, WINFUNCTYPE21from ctypes.wintypes import LPWSTR, LPCWSTR222324c_ssize_p = POINTER(c_ssize_t)2526PyObject_GetBuffer = pythonapi.PyObject_GetBuffer27PyBuffer_Release = pythonapi.PyBuffer_Release2829kernel32 = windll.kernel3230GetStdHandle = kernel32.GetStdHandle31ReadConsoleW = kernel32.ReadConsoleW32WriteConsoleW = kernel32.WriteConsoleW33GetLastError = kernel32.GetLastError34GetCommandLineW = WINFUNCTYPE(LPWSTR)(35 ('GetCommandLineW', windll.kernel32))36CommandLineToArgvW = WINFUNCTYPE(37 POINTER(LPWSTR), LPCWSTR, POINTER(c_int))(38 ('CommandLineToArgvW', windll.shell32))394041STDIN_HANDLE = GetStdHandle(-10)42STDOUT_HANDLE = GetStdHandle(-11)43STDERR_HANDLE = GetStdHandle(-12)444546PyBUF_SIMPLE = 047PyBUF_WRITABLE = 14849ERROR_SUCCESS = 050ERROR_NOT_ENOUGH_MEMORY = 851ERROR_OPERATION_ABORTED = 9955253STDIN_FILENO = 054STDOUT_FILENO = 155STDERR_FILENO = 25657EOF = b'\x1a'58MAX_BYTES_WRITTEN = 32767596061class Py_buffer(ctypes.Structure):62 _fields_ = [63 ('buf', c_void_p),64 ('obj', py_object),65 ('len', c_ssize_t),66 ('itemsize', c_ssize_t),67 ('readonly', c_int),68 ('ndim', c_int),69 ('format', c_char_p),70 ('shape', c_ssize_p),71 ('strides', c_ssize_p),72 ('suboffsets', c_ssize_p),73 ('internal', c_void_p)74 ]7576 if PY2:77 _fields_.insert(-1, ('smalltable', c_ssize_t * 2))787980def get_buffer(obj, writable=False):81 buf = Py_buffer()82 flags = PyBUF_WRITABLE if writable else PyBUF_SIMPLE83 PyObject_GetBuffer(py_object(obj), byref(buf), flags)84 try:85 buffer_type = c_char * buf.len86 return buffer_type.from_address(buf.buf)87 finally:88 PyBuffer_Release(byref(buf))899091class _WindowsConsoleRawIOBase(io.RawIOBase):9293 def __init__(self, handle):94 self.handle = handle9596 def isatty(self):97 io.RawIOBase.isatty(self)98 return True99100101class _WindowsConsoleReader(_WindowsConsoleRawIOBase):102103 def readable(self):104 return True105106 def readinto(self, b):107 bytes_to_be_read = len(b)108 if not bytes_to_be_read:109 return 0110 elif bytes_to_be_read % 2:111 raise ValueError('cannot read odd number of bytes from '112 'UTF-16-LE encoded console')113114 buffer = get_buffer(b, writable=True)115 code_units_to_be_read = bytes_to_be_read // 2116 code_units_read = c_ulong()117118 rv = ReadConsoleW(self.handle, buffer, code_units_to_be_read,119 byref(code_units_read), None)120 if GetLastError() == ERROR_OPERATION_ABORTED:121 # wait for KeyboardInterrupt122 time.sleep(0.1)123 if not rv:124 raise OSError('Windows error: %s' % GetLastError())125126 if buffer[0] == EOF:127 return 0128 return 2 * code_units_read.value129130131class _WindowsConsoleWriter(_WindowsConsoleRawIOBase):132133 def writable(self):134 return True135136 @staticmethod137 def _get_error_message(errno):138 if errno == ERROR_SUCCESS:139 return 'ERROR_SUCCESS'140 elif errno == ERROR_NOT_ENOUGH_MEMORY:141 return 'ERROR_NOT_ENOUGH_MEMORY'142 return 'Windows error %s' % errno143144 def write(self, b):145 bytes_to_be_written = len(b)146 buf = get_buffer(b)147 code_units_to_be_written = min(bytes_to_be_written,148 MAX_BYTES_WRITTEN) // 2149 code_units_written = c_ulong()150151 WriteConsoleW(self.handle, buf, code_units_to_be_written,152 byref(code_units_written), None)153 bytes_written = 2 * code_units_written.value154155 if bytes_written == 0 and bytes_to_be_written > 0:156 raise OSError(self._get_error_message(GetLastError()))157 return bytes_written158159160class ConsoleStream(object):161162 def __init__(self, text_stream, byte_stream):163 self._text_stream = text_stream164 self.buffer = byte_stream165166 @property167 def name(self):168 return self.buffer.name169170 def write(self, x):171 if isinstance(x, text_type):172 return self._text_stream.write(x)173 try:174 self.flush()175 except Exception:176 pass177 return self.buffer.write(x)178179 def writelines(self, lines):180 for line in lines:181 self.write(line)182183 def __getattr__(self, name):184 return getattr(self._text_stream, name)185186 def isatty(self):187 return self.buffer.isatty()188189 def __repr__(self):190 return '<ConsoleStream name=%r encoding=%r>' % (191 self.name,192 self.encoding,193 )194195196def _get_text_stdin(buffer_stream):197 text_stream = _NonClosingTextIOWrapper(198 io.BufferedReader(_WindowsConsoleReader(STDIN_HANDLE)),199 'utf-16-le', 'strict', line_buffering=True)200 return ConsoleStream(text_stream, buffer_stream)201202203def _get_text_stdout(buffer_stream):204 text_stream = _NonClosingTextIOWrapper(205 _WindowsConsoleWriter(STDOUT_HANDLE),206 'utf-16-le', 'strict', line_buffering=True)207 return ConsoleStream(text_stream, buffer_stream)208209210def _get_text_stderr(buffer_stream):211 text_stream = _NonClosingTextIOWrapper(212 _WindowsConsoleWriter(STDERR_HANDLE),213 'utf-16-le', 'strict', line_buffering=True)214 return ConsoleStream(text_stream, buffer_stream)215216217if PY2:218 def _hash_py_argv():219 return zlib.crc32('\x00'.join(sys.argv[1:]))220221 _initial_argv_hash = _hash_py_argv()222223 def _get_windows_argv():224 argc = c_int(0)225 argv_unicode = CommandLineToArgvW(GetCommandLineW(), byref(argc))226 argv = [argv_unicode[i] for i in range(0, argc.value)]227228 if not hasattr(sys, 'frozen'):229 argv = argv[1:]230 while len(argv) > 0:231 arg = argv[0]232 if not arg.startswith('-') or arg == '-':233 break234 argv = argv[1:]235 if arg in ('-c', '-m'):236 break237238 return argv[1:]239240241_stream_factories = {242 0: _get_text_stdin,243 1: _get_text_stdout,244 2: _get_text_stderr,245}246247248def _get_windows_console_stream(f, encoding, errors):249 if encoding in ('utf-16-le', None) \250 and errors in ('strict', None) and \251 hasattr(f, 'isatty') and f.isatty():252 func = _stream_factories.get(f.fileno())253 if func is not None:254 if not PY2:255 f = getattr(f, 'buffer')256 if f is None:257 return None258 else:259 # If we are on Python 2 we need to set the stream that we260 # deal with to binary mode as otherwise the exercise if a261 # bit moot. The same problems apply as for262 # get_binary_stdin and friends from _compat.263 msvcrt.setmode(f.fileno(), os.O_BINARY)264 return func(f)
modified:click/core.py+6 added-16 removed
1import os2import sys3import codecs3from contextlib import contextmanager4from itertools import repeat5from functools import update_wrapper67from .types import convert_type, IntRange, BOOL9from .utils import make_str, make_default_short_help, echo8from .utils import make_str, make_default_short_help, echo, get_os_args9from .exceptions import ClickException, UsageError, BadParameter, Abort, \10 MissingParameter11from .termui import prompt, confirm12from .formatting import HelpFormatter, join_options13from .parser import OptionParser, split_opt14from .globals import push_context, pop_context1517from ._compat import PY2, isidentifier, iteritems, _check_for_unicode_literals16from ._compat import PY2, isidentifier, iteritems17from ._unicodefun import _check_for_unicode_literals, _verify_python3_env181920_missing = object()21
642 unmodified lines
664 # If we are in Python 3, we will verify that the environment is665 # sane at this point of reject further execution to avoid a666 # broken script.667 if not PY2:668 try:669 import locale670 fs_enc = codecs.lookup(locale.getpreferredencoding()).name671 except Exception:672 fs_enc = 'ascii'673 if fs_enc == 'ascii':674 raise RuntimeError('Click will abort further execution '675 'because Python 3 was configured to use '676 'ASCII as encoding for the environment. '677 'Either switch to Python 2 or consult '678 'http://click.pocoo.org/python3/ '679 'for mitigation steps.')668 _verify_python3_env()669 else:670 _check_for_unicode_literals()671672 if args is None:684 args = sys.argv[1:]673 args = get_os_args()674 else:675 args = list(args)676677 if prog_name is None:678 prog_name = make_str(os.path.basename(679 sys.argv and sys.argv[0] or __file__))680
1036 unmodified lines
modified:click/decorators.py+2 added-1 removed
1 unmodified line
2import inspect34from functools import update_wrapper56from ._compat import iteritems, _check_for_unicode_literals6from ._compat import iteritems7from ._unicodefun import _check_for_unicode_literals8from .utils import echo9from .globals import get_current_context1011
293 unmodified lines
modified:click/formatting.py+7 added-1 removed
2 unmodified lines
3from .parser import split_opt4from ._compat import term_len567# Can force a width. This is used by the test system8FORCED_WIDTH = None91011def measure_table(rows):12 widths = {}13 for row in rows:14 for idx, col in enumerate(row):
87 unmodified lines
102 self.indent_increment = indent_increment103 if max_width is None:104 max_width = 80105 if width is None:106 width = FORCED_WIDTH107 if width is None:102 width = max(min(get_terminal_size()[0], max_width) - 2, 50)108 width = max(min(get_terminal_size()[0], max_width) - 2, 50)109 self.width = width110 self.current_indent = 0111 self.buffer = []112
144 unmodified lines
modified:click/termui.py+3 added
39 unmodified lines
4041 If the user aborts the input by sending a interrupt signal, this42 function will catch it and raise a :exc:`Abort` exception.4344 .. versionadded:: 6.045 Added unicode support for cmd.exe on Windows.4647 .. versionadded:: 4.048 Added the `err` parameter.4950 :param text: the text to show for the prompt.
489 unmodified lines
modified:click/testing.py+3 added
155 unmodified lines
156157 old_stdin = sys.stdin158 old_stdout = sys.stdout159 old_stderr = sys.stderr160 old_forced_width = clickpkg.formatting.FORCED_WIDTH161 clickpkg.formatting.FORCED_WIDTH = 80162163 env = self.make_env(env)164165 if PY2:
71 unmodified lines
237 clickpkg.termui.visible_prompt_func = old_visible_prompt_func238 clickpkg.termui.hidden_prompt_func = old_hidden_prompt_func239 clickpkg.termui._getchar = old__getchar_func240 clickpkg.utils.should_strip_ansi = old_should_strip_ansi241 clickpkg.formatting.FORCED_WIDTH = old_forced_width242243 def invoke(self, cli, args=None, input=None, env=None,244 catch_exceptions=True, color=False, **extra):245 """Invokes a command in an isolated environment. The arguments are
77 unmodified lines
modified:click/types.py+52 added-25 removed
1import os2import sys2import stat34from ._compat import open_stream, text_type, filename_to_ui, \6 get_filesystem_encoding, get_streerror5 get_filesystem_encoding, get_streerror, _get_argv_encoding, PY26from .exceptions import BadParameter7from .utils import safecall, LazyFile89
97 unmodified lines
107 name = 'text'108109 def convert(self, value, param, ctx):110 if isinstance(value, bytes):111 enc = _get_argv_encoding()112 try:113 enc = getattr(sys.stdin, 'encoding', None)114 if enc is not None:115 value = value.decode(enc)113 value = value.decode(enc)114 except UnicodeError:115 fs_enc = get_filesystem_encoding()116 if fs_enc != enc:117 try:118 value = value.decode(get_filesystem_encoding())119 except UnicodeError:120 value = value.decode('utf-8', 'replace')117 try:118 value = value.decode(fs_enc)119 except UnicodeError:120 value = value.decode('utf-8', 'replace')121 return value122 return value123124 def __repr__(self):
42 unmodified lines
167168 def convert(self, value, param, ctx):169 try:170 return int(value)171 except ValueError:171 except (ValueError, UnicodeError):172 self.fail('%s is not a valid integer' % value, param, ctx)173174 def __repr__(self):175 return 'INT'
60 unmodified lines
236237 def convert(self, value, param, ctx):238 try:239 return float(value)240 except ValueError:240 except (UnicodeError, ValueError):241 self.fail('%s is not a valid floating point value' %242 value, param, ctx)243244 def __repr__(self):
5 unmodified lines
250251 def convert(self, value, param, ctx):252 import uuid253 try:254 if PY2 and isinstance(value, text_type):255 value = value.encode('ascii')256 return uuid.UUID(value)255 except ValueError:257 except (UnicodeError, ValueError):258 self.fail('%s is not a valid UUID value' % value, param, ctx)259260 def __repr__(self):261 return 'UUID'
82 unmodified lines
344 different checks. First of all, instead of returning an open file345 handle it returns just the filename. Secondly, it can perform various346 basic checks about what the file or directory should be.347348 .. versionchanged:: 6.0349 `allow_dash` was added.350351 :param exists: if set to true, the file or directory needs to exist for352 this value to be valid. If this is not required and a353 file does indeed not exist, then all further checks are354 silently skipped.
3 unmodified lines
358 :param readable: if true, a readable check is performed.359 :param resolve_path: if this is true, then the path is fully resolved360 before the value is passed onwards. This means361 that it's absolute and symlinks are resolved.362 :param allow_dash: If this is set to `True`, a single dash to indicate363 standard streams is permitted.364 :param type: optionally a string type that should be used to365 represent the path. The default is `None` which366 means the return value will be either bytes or367 unicode depending on what makes most sense given the368 input data Click deals with.369 """370 envvar_list_splitter = os.path.pathsep371372 def __init__(self, exists=False, file_okay=True, dir_okay=True,361 writable=False, readable=True, resolve_path=False):373 writable=False, readable=True, resolve_path=False,374 allow_dash=False, path_type=None):375 self.exists = exists376 self.file_okay = file_okay377 self.dir_okay = dir_okay378 self.writable = writable379 self.readable = readable380 self.resolve_path = resolve_path381 self.allow_dash = allow_dash382 self.type = path_type383384 if self.file_okay and not self.dir_okay:385 self.name = 'file'386 self.path_type = 'File'
3 unmodified lines
390 else:391 self.name = 'path'392 self.path_type = 'Path'393394 def coerce_path_result(self, rv):395 if self.type is not None and not isinstance(rv, self.type):396 if self.type is text_type:397 rv = rv.decode(get_filesystem_encoding())398 else:399 rv = rv.encode(get_filesystem_encoding())400 return rv401402 def convert(self, value, param, ctx):403 rv = value381 if self.resolve_path:382 rv = os.path.realpath(rv)404384 try:385 st = os.stat(rv)386 except OSError:387 if not self.exists:388 return rv389 self.fail('%s "%s" does not exist.' % (390 self.path_type,391 filename_to_ui(value)392 ), param, ctx)405 is_dash = self.file_okay and self.allow_dash and rv in (b'-', '-')406407 if not is_dash:408 if self.resolve_path:409 rv = os.path.realpath(rv)410411 try:412 st = os.stat(rv)413 except OSError:414 if not self.exists:415 return self.coerce_path_result(rv)416 self.fail('%s "%s" does not exist.' % (417 self.path_type,418 filename_to_ui(value)419 ), param, ctx)420421 if not self.file_okay and stat.S_ISREG(st.st_mode):422 self.fail('%s "%s" is a file.' % (423 self.path_type,424 filename_to_ui(value)
13 unmodified lines
438 self.path_type,439 filename_to_ui(value)440 ), param, ctx)441415 return rv442 return self.coerce_path_result(rv)443444445class Tuple(CompositeParamType):446 """The default behavior of Click is to apply a type on a value directly.
104 unmodified lines
modified:click/utils.py+32 added-1 removed
9 unmodified lines
10 _default_text_stdout, _default_text_stderr, is_bytes, WIN1112if not PY2:13 from ._compat import _find_binary_writer14elif WIN:15 from ._winconsole import _get_windows_argv, \16 _hash_py_argv, _initial_argv_hash171819echo_native_types = string_types + (bytes, bytearray)20
215 unmodified lines
236237 Primarily it means that you can print binary data as well as Unicode238 data on both 2.x and 3.x to the given file in the most appropriate way239 possible. This is a very carefree function as in that it will try its237 best to not fail.240 best to not fail. As of Click 6.0 this includes support for unicode241 output on the Windows console.242243 In addition to that, if `colorama`_ is installed, the echo function will244 also support clever handling of ANSI codes. Essentially it will then245 do the following:
3 unmodified lines
249 terminal.250251 .. _colorama: http://pypi.python.org/pypi/colorama252253 .. versionchanged:: 6.0254 As of Click 6.0 the echo function will properly support unicode255 output on the windows console. Not that click does not modify256 the interpreter in any way which means that `sys.stdout` or the257 print statement or function will still not provide unicode support.258259 .. versionchanged:: 2.0260 Starting with version 2.0 of Click, the echo function will work261 with colorama if it's installed.262
127 unmodified lines
390 f = KeepOpenFile(f)391 return f392393394def get_os_args():395 """This returns the argument part of sys.argv in the most appropriate396 form for processing. What this means is that this return value is in397 a format that works for Click to process but does not necessarily398 correspond well to what's actually standard for the interpreter.399400 On most environments the return value is ``sys.argv[:1]`` unchanged.401 However if you are on Windows and running Python 2 the return value402 will actually be a list of unicode strings instead because the403 default behavior on that platform otherwise will not be able to404 carry all possible values that sys.argv can have.405406 .. versionadded:: 6.0407 """408 # We can only extract the unicode argv if sys.argv has not been409 # changed since the startup of the application.410 if PY2 and WIN and _initial_argv_hash == _hash_py_argv():411 return _get_windows_argv()412 return sys.argv[1:]413414415def format_filename(filename, shorten=False):416 """Formats a filename for user display. The main purpose of this417 function is to ensure that the filename can be displayed at all. This418 will decode the filename to unicode if necessary in a way that it will
62 unmodified lines
modified:docs/index.rst+1 added
73 unmodified lines
74 utils75 bashcomplete76 exceptions77 python378 wincmd7980API Reference81-------------82
18 unmodified lines
modified:docs/options.rst+2 added-2 removed
211 unmodified lines
212213 import sys214215 @click.command()216 @click.option('--shout/--no-shout', ' /S', default=False)216 @click.option('--shout/--no-shout', ' /-S', default=False)217 def info(shout):218 rv = sys.platform219 if shout:220 rv = rv.upper() + '!!!!111'
246 unmodified lines
467468.. click:example::469470 @click.command()471 @click.confirmation_option(help='Are you sure you want to drop the db?')471 @click.confirmation_option(prompt='Are you sure you want to drop the db?')472 def dropdb():473 click.echo('Dropped all tables!')474475.. admonition:: Callback Signature Changes
220 unmodified lines
modified:docs/python3.rst+6 added
137 unmodified lines
138139 export LC_ALL=C.UTF-8140 export LANG=C.UTF-8141142On some systems it was reported that `UTF-8` has to be written as `UTF8`143and vice versa. To see which locales are supported you can invoke144``locale -a``::145146 locale -a147148You need to do this before you invoke your Python script. If you are149curious about the reasons for this, you can join the discussions in the150Python 3 bug tracker:151
32 unmodified lines
modified:docs/utils.rst+19 added
28 unmodified lines
29suppressed by passing ``nl=False``::3031 click.echo(b'\xe2\x98\x83', nl=False)3233Last but not least :func:`echo` uses click's intelligent internal output34streams to stdout and stderr which support unicode output on the Windows35console. This means for as long as you are using `click.echo` you can36output unicode character (there are some limitations on the default font37with regards to which characters can be displayed). This functionality is38new in Click 6.0.3940.. versionadded:: 6.04142Click now emulates output streams on Windows to support unicode to the43Windows console through separate APIs. For more information see44`wincmd`_.4546.. versionadded:: 3.04748Starting with Click 3.0 you can also easily print to standard error by49passing ``err=True``::
228 unmodified lines
278279 stdin_text = click.get_text_stream('stdin')280 stdout_binary = click.get_binary_stream('stdout')281282.. versionadded:: 6.0283284Click now emulates output streams on Windows to support unicode to the285Windows console through separate APIs. For more information see286`wincmd`_.287288289Intelligent File Opening290------------------------291292.. versionadded:: 3.0
106 unmodified lines
added:docs/wincmd.rst+73 added
1Windows Console Notes2=====================34.. versionadded:: 6.056Until Click 6.0 there are various bugs and limitations with using Click on7a Windows console. Most notably the decoding of command line arguments8was performed with the wrong encoding on Python 2 and on all versions of9Python output of unicode characters was impossible. Starting with Click106.0 we now emulate output streams on Windows to support unicode to the11Windows console through separate APIs and we perform different decoding of12parameters.1314Here is a brief overview of how this works and what it means to you.1516Unicode Arguments17-----------------1819Click internally is generally based on the concept that any argument can20come in as either byte string or unicode string and conversion is21performed to the type expected value as late as possible. This has some22advantages as it allows us to accept the data in the most appropriate form23for the operating system and Python version.2425For instance paths are left as bytes on Python 2 unless you explicitly26tell it otherwise.2728This caused some problems on Windows where initially the wrong encoding29was used and garbage ended up in your input data. We not only fixed the30encoding part, but we also now extract unicode parameters from `sys.argv`.3132This means that on Python 2 under Windows, the arguments processed will33*most likely* be of unicode nature and not bytes. This was something that34previously did not really happen unless you explicitly passed in unicode35parameters so your custom types need to be aware of this.3637There is also another limitation with this: if `sys.argv` was modified38prior to invoking a click handler, we have to fall back to the regular39byte input in which case not all unicode values are available but only a40subset of the codepage used for parameters.4142Unicode Output and Input43------------------------4445Unicode output and input on Windows is implemented through the concept of46a dispatching text stream. What this means is that when click first needs47a text output (or input) stream on windows it goes through a few checks to48figure out of a windows console is connected or not. If no Windows49console is present then the text output stream is returned as such and the50encoding for that stream is set to ``utf-8`` like on all platforms.5152However if a console is connected the stream will instead be emulated and53use the cmd.exe unicode APIs to output text information. In this case the54stream will also use ``utf-16-le`` as internal encoding. However there is55some hackery going on that the underlying raw IO buffer is still bypassing56the unicode APIs and byte output through an indirection is still possible.5758This hackery is used on both Python 2 and Python 3 as neither version of59Python has native support for cmd.exe with unicode characters. There are60some limitations you need to be aware of:6162* this unicode support is limited to ``click.echo``, ``click.prompt`` as63 well as ``click.get_text_stream``.64* depending on if unicode values or byte strings are passed the control65 flow goes completely different places internally which can have some66 odd artifacts if data partially ends up being buffered. Click67 attempts to protect against that by manually always flushing but if68 you are mixing and matching different string types to ``stdout`` or69 ``stderr`` you will need to manually flush.7071Another important thing to note is that the Windows console's default72fonts do not support a lot of characters which means that you are mostly73limited to international letters but no emojis or special characters.
modified:tests/test_arguments.py+6 added-4 removed
1# -*- coding: utf-8 -*-2import click3from click._compat import PY2456def test_nargs_star(runner):7 @click.command()
110 unmodified lines
118119 with runner.isolated_filesystem():120 with open('foo.txt', 'wb') as f:121 f.write(b'OLD\n')121 result = runner.invoke(inout, ['foo.txt'], input='Hey!')122 result = runner.invoke(inout, ['foo.txt'], input='Hey!',123 catch_exceptions=False)124 assert result.output == ''125 assert result.exit_code == 0126 with open('foo.txt', 'rb') as f:127 assert f.read() == b'Foo bar baz\n'
108 unmodified lines
236 click.echo(arg)237238 result = runner.invoke(cmd, ['a', 'b', 'c'])239 assert result.output.splitlines() == [238 "('a',)",240 PY2 and "(u'a',)" or "('a',)",241 'b',242 'c',243 ]244
8 unmodified lines
253 click.echo(arg)254255 result = runner.invoke(cmd, ['a', 'b', 'c', 'd', 'e', 'f'])256 assert result.output.splitlines() == [255 "('a', 'b', 'c')",257 PY2 and "(u'a', u'b', u'c')" or "('a', 'b', 'c')",258 'd',257 "('e', 'f')",259 PY2 and "(u'e', u'f')" or "('e', 'f')",260 ]
modified:tests/test_imports.py+7 added-1 removed
1import sys2import json3import subprocess45from click._compat import WIN678IMPORT_TEST = b'''\9try:10 import __builtin__ as builtins11except ImportError:
19 unmodified lines
3132ALLOWED_IMPORTS = set([33 'weakref', 'os', 'struct', 'collections', 'sys', 'contextlib',34 'functools', 'stat', 're', 'codecs', 'inspect', 'itertools', 'io',33 'threading'35 'threading', 'colorama'36])3738if WIN:39 ALLOWED_IMPORTS.update(['ctypes', 'ctypes.wintypes', 'msvcrt', 'time',40 'zlib'])414243def test_light_imports():44 c = subprocess.Popen([sys.executable, '-'], stdin=subprocess.PIPE,45 stdout=subprocess.PIPE)46 rv = c.communicate(IMPORT_TEST)[0]
10 unmodified lines
modified:tests/test_options.py+16 added-11 removed
2 unmodified lines
3import os4import click5import pytest67from click._compat import text_type8910def test_prefixes(runner):11 @click.command()12 @click.option('++foo', is_flag=True, help='das foo')13 @click.option('--bar', is_flag=True, help='das bar')
131 unmodified lines
145146147def test_multiple_default_help(runner):148 @click.command()147 @click.option("--arg1", multiple=True, default=('foo', 'bar'),149 @click.option('--arg1', multiple=True, default=('foo', 'bar'),150 show_default=True)149 @click.option("--arg2", multiple=True, default=(1, 2), type=int,151 @click.option('--arg2', multiple=True, default=(1, 2), type=int,152 show_default=True)153 def cmd(arg, arg2):154 pass155156 result = runner.invoke(cmd, ['--help'])157 assert not result.exception156 assert "foo, bar" in result.output157 assert "1, 2" in result.output158 assert 'foo, bar' in result.output159 assert '1, 2' in result.output160161162def test_multiple_default_type(runner):163 @click.command()161 @click.option("--arg1", multiple=True, default=('foo', 'bar'))162 @click.option("--arg2", multiple=True, default=(1, "a"))164 @click.option('--arg1', multiple=True, default=('foo', 'bar'))165 @click.option('--arg2', multiple=True, default=(1, 'a'))166 def cmd(arg1, arg2):164 assert all(isinstance(e[0],str) for e in arg1)165 assert all(isinstance(e[1],str) for e in arg1)167 assert all(isinstance(e[0], text_type) for e in arg1)168 assert all(isinstance(e[1], text_type) for e in arg1)169167 assert all(isinstance(e[0],int) for e in arg2)168 assert all(isinstance(e[1],str) for e in arg2)170 assert all(isinstance(e[0], int) for e in arg2)171 assert all(isinstance(e[1], text_type) for e in arg2)172170 result = runner.invoke(cmd, "--arg1 a b --arg1 test 1 --arg2 2 two --arg2 4 four".split())173 result = runner.invoke(cmd, '--arg1 a b --arg1 test 1 --arg2 2 '174 'two --arg2 4 four'.split())175 assert not result.exception176177178def test_nargs_envvar(runner):179 @click.command()180 @click.option('--arg', nargs=2)181 def cmd(arg):
156 unmodified lines
modified:tests/test_testing.py+2 added-2 removed
3 unmodified lines
4import click56from click.testing import CliRunner78from click._compat import PY28from click._compat import PY2, WIN910# Use the most reasonable io that users would use for the python version.11if PY2:12 from cStringIO import StringIO as ReasonableBytesIO
103 unmodified lines
116 result = runner.invoke(cli)117 assert result.exit_code == 1118119120@pytest.mark.skipif(WIN, reason='Test does not make sense on Windows.')121def test_with_color():122 @click.command()123 def cli():124 click.secho('hello world', fg='blue')
57 unmodified lines
182183 result = runner.invoke(cli_no_error)184 assert result.exit_code == 0185 assert result.output == 'hello world\n'185
modified:tests/test_utils.py+13 added-5 removed
4 unmodified lines
56import click7import click.utils8import click._termui_impl9from click._compat import WIN, PY2101112def test_echo(runner):13 with runner.isolation() as out:
1 unmodified line
15 click.echo(b'\x44\x44')16 click.echo(42, nl=False)17 click.echo(b'a', nl=False)18 click.echo('\x1b[31mx\x1b[39m', nl=False)18 bytes = out.getvalue()19 bytes = out.getvalue().replace(b'\r\n', b'\n')20 assert bytes == b'\xe2\x98\x83\nDD\n42ax'2122 # If we are in Python 2, we expect that writing bytes into a string io23 # does not do anything crazy. In Python 3
58 unmodified lines
82 assert click.format_filename(b'foo.txt') == 'foo.txt'83 assert click.format_filename(b'/x/foo.txt') == '/x/foo.txt'84 assert click.format_filename(u'/x/foo.txt') == '/x/foo.txt'85 assert click.format_filename(u'/x/foo.txt', shorten=True) == 'foo.txt'85 assert click.format_filename(b'/x/foo\xff.txt', shorten=True) \86 == u'foo\ufffd.txt'8687 # filesystem encoding on windows permits this.88 if not WIN:89 assert click.format_filename(b'/x/foo\xff.txt', shorten=True) \90 == u'foo\ufffd.txt'919293def test_prompts(runner):94 @click.command()95 def test():96 if click.confirm('Foo'):
32 unmodified lines
129 assert not result.exception130 assert result.output == 'Foo [Y/n]: n\nno :(\n'131132133@pytest.mark.skipif(WIN, reason='Different behavior on windows.')134def test_prompts_abort(monkeypatch, capsys):135 def f(_):136 raise KeyboardInterrupt()137
7 unmodified lines
145 out, err = capsys.readouterr()146 assert out == 'Password: \nScrew you.\n'147148149@pytest.mark.skipif(WIN, reason='Different behavior on windows.')150@pytest.mark.parametrize('cat', ['cat', 'cat ', 'cat '])151def test_echo_via_pager(monkeypatch, capfd, cat):152 monkeypatch.setitem(os.environ, 'PAGER', cat)153 monkeypatch.setattr(click._termui_impl, 'isatty', lambda x: True)
1 unmodified line
155 out, err = capfd.readouterr()156 assert out == 'haha\n'157158159@pytest.mark.skipif(WIN, reason='Test does not make sense on Windows.')160def test_echo_color_flag(monkeypatch, capfd):161 isatty = True162 monkeypatch.setattr(click._compat, 'isatty', lambda x: isatty)163
19 unmodified lines
183 out, err = capfd.readouterr()184 assert out == text + '\n'185186187@pytest.mark.skipif(WIN, reason='Test too complex to make work windows.')188def test_echo_writing_to_standard_error(capfd, monkeypatch):189 def emulate_input(text):190 """Emulate keyboard input."""191 if sys.version_info[0] == 2:
70 unmodified lines
262 assert result.exception is None263 assert result.output == 'foobar\nmeep\n'264265266@pytest.mark.xfail(WIN and not PY2, reason='God knows ...')267def test_iter_keepopenfile(tmpdir):259268 expected = list(map(str, range(10)))269 p = tmpdir.mkdir('testdir').join('testfile')270 p.write(os.linesep.join(expected))271 f = p.open()272 for e_line, a_line in zip(expected, click.utils.KeepOpenFile(f)):273 assert e_line == a_line.strip()274275276@pytest.mark.xfail(WIN and not PY2, reason='God knows ...')277def test_iter_lazyfile(tmpdir):269278 expected = list(map(str, range(10)))279 p = tmpdir.mkdir('testdir').join('testfile')280 p.write(os.linesep.join(expected))281 f = p.open()
2 unmodified lines
modified:.travis.yml+1 added
2 unmodified lines
3 - "2.6"4 - "2.7"5 - "3.3"6 - "3.4"7 - "3.5"8 - "pypy"910env:11 - REQUIREMENTS=colorama
17 unmodified lines
modified:CHANGES+20 added
14 unmodified lines
15 subcommands works.16- Explicitly disallow nargs=-1 with a set default.17- The context is now closed before it's popped from the stack.18- Added support for short aliases for the false flag on toggles.19- Click will now attempt to aid you with debugging locale errors20 better by listing with the help of the OS what locales are21 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 on Windows the `echo`) and `prompt` functions33 now work with full unicode functionality in the Python windows console34 by emulating an output stream. This also applies to getting the35 virtual output and input streams via `click.get_text_stream(...)`.36- Unittests now always force a certain virtual terminal width.37- Added support for allowing dashes to indicate standard streams to the38 `Path` type.3940Version 5.141-----------42
251 unmodified lines