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
Provenance
- Commit
8e35beb- Tree
eefefde- Author
Claudio Bandera <claudio.bandera@kit.edu>- Committer
Claudio Bandera <claudio.bandera@kit.edu>- Parent 1
8e18d48- Parent 2
07a4f18
26 files changed+815 added−109 removed
added:.ci/appveyor.yml+50 added
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950# From https://github.com/ogrisel/python-appveyor-demo/blob/master/appveyor.yml
environment: global: # SDK v7.0 MSVC Express 2008's SetEnv.cmd script will fail if the # /E:ON and /V:ON options are not enabled in the batch script intepreter # See: http://stackoverflow.com/a/13751649/163740 CMD_IN_ENV: "cmd /E:ON /V:ON /C .\\.ci\\run_with_env.cmd"
matrix: - PYTHON: "C:\\Python27" PYTHON_VERSION: "2.7.x" PYTHON_ARCH: "32"
- PYTHON: "C:\\Python27-x64" PYTHON_VERSION: "2.7.x" PYTHON_ARCH: "64"
- PYTHON: "C:\\Python33" PYTHON_VERSION: "3.3.x" PYTHON_ARCH: "32"
- PYTHON: "C:\\Python33-x64" PYTHON_VERSION: "3.3.x" PYTHON_ARCH: "64"
- PYTHON: "C:\\Python34" PYTHON_VERSION: "3.4.x" PYTHON_ARCH: "32"
- PYTHON: "C:\\Python34-x64" PYTHON_VERSION: "3.4.x" PYTHON_ARCH: "64"
branches: only: - master
install: - "SET PATH=%PYTHON%;%PYTHON%\\Scripts;%PATH%" # Check that we have the expected version and architecture for Python - "python --version" - "python -c \"import struct; print(struct.calcsize('P') * 8)\"" # Build data files - "pip install . pytest"
build: false # Not a C# project, build stuff at the test step instead.
test_script: - "%CMD_IN_ENV% python -m pytest tests"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 OFF21+22+SET COMMAND_TO_RUN=%*23+SET WIN_SDK_ROOT=C:\Program Files\Microsoft SDKs\Windows24+25+SET MAJOR_PYTHON_VERSION="%PYTHON_VERSION:~0,1%"26+IF %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+)34+35+IF "%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 lines31 STRING, INT, FLOAT, BOOL, UUID, UNPROCESSED32 33 # Utilities34 from .utils import echo, get_binary_stream, get_text_stream, open_file, \35- format_filename, get_app_dir35+ format_filename, get_app_dir, get_os_args36 37 # Terminal functions38 from .termui import prompt, confirm, get_terminal_size, echo_via_pager, \39 progressbar, clear, style, unstyle, secho, edit, launch, getchar, \28 unmodified lines68 'INT', 'FLOAT', 'BOOL', 'UUID', 'UNPROCESSED',69 70 # 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',73 74 # Terminal functions75 'prompt', 'confirm', 'get_terminal_size', 'echo_via_pager',76 'progressbar', 'clear', 'style', 'unstyle', 'secho', 'edit', 'launch',20 unmodified linesmodified:click/_compat.py+55 added-37 removed
3 unmodified lines4 import sys5 import codecs6 from weakref import WeakKeyDictionary7 8-import click8 10-9 PY2 = sys.version_info[0] == 210 WIN = sys.platform.startswith('win')11 DEFAULT_COLUMNS = 8012 13 14 _ansi_re = re.compile('\033\[((?:\d|;)*)([a-zA-Z])')15 16 19-def _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 032-33-34-def _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)50-51-17 def get_filesystem_encoding():18 return sys.getfilesystemencoding() or sys.getdefaultencoding()19 20 135 unmodified lines156 # 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 lines185 def get_binary_stderr():186 return set_binary_mode(sys.stderr)187 188 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)193 194 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)199 200 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)205 206 def filename_to_ui(value):207 if isinstance(value, bytes):161 unmodified lines369 'stream for sys.stderr.')370 return writer371 372 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)377 378 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)383 384 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)389 390 def filename_to_ui(value):391 if isinstance(value, bytes):65 unmodified lines457 return _AtomicFile(f, tmp_filename, filename), True458 459 460 # Used in a destructor call, needs extra protection from interpreter cleanup.461+if hasattr(os, 'replace'):462+ _replace = os.replace463+ _can_replace = True464+else:475-_rename = os.rename465+ _replace = os.rename466+ _can_replace = not WIN467 468 469 class _AtomicFile(object):470 10 unmodified lines481 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 = True492 493 def __getattr__(self, name):494 return getattr(self._f, name)31 unmodified lines526 if WIN:527 # Windows has a smaller terminal528 DEFAULT_COLUMNS = 79529 530+ from ._winconsole import _get_windows_console_stream531+532+ def _get_argv_encoding():533+ import locale534+ return locale.getpreferredencoding()535+536+ 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')544+545 try:546 import colorama547 except ImportError:548 pass34 unmodified lines583 def get_winterm_size():584 win = colorama.win32.GetConsoleScreenBufferInfo(585 colorama.win32.STDOUT).srWindow586 return win.Right - win.Left, win.Bottom - win.Top587+else:588+ def _get_argv_encoding():589+ return getattr(sys.stdin, 'encoding', None) or get_filesystem_encoding()590 591+ _get_windows_console_stream = lambda *x: None592 593+594 def term_len(x):595 return len(strip_ansi(x))596 597 22 unmodified lines620 return rv621 return func622 623 624+_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 linesmodified:click/_termui_impl.py+12 added-1 removed
127 unmodified lines128 return 0.0129 130 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 ''145 146 def format_pos(self):147 pos = str(self.pos)398 unmodified linesadded:click/_unicodefun.py+114 added
1+import os2+import sys3+import codecs4+5+from ._compat import PY26+7+8+# 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.12+click = sys.modules[__name__.rsplit('.', 1)[0]]13+14+15+def _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 028+29+30+def _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)46+47+48+def _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+ return59+60+ 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 = True73+74+ 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))95+96+ 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_locale109+110+ 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.10+11+import io12+import os13+import sys14+import zlib15+import time16+import ctypes17+import msvcrt18+from click._compat import _NonClosingTextIOWrapper, text_type, PY219+from ctypes import byref, POINTER, pythonapi, c_int, c_char, c_char_p, \20+ c_void_p, py_object, c_ssize_t, c_ulong, windll, WINFUNCTYPE21+from ctypes.wintypes import LPWSTR, LPCWSTR22+23+24+c_ssize_p = POINTER(c_ssize_t)25+26+PyObject_GetBuffer = pythonapi.PyObject_GetBuffer27+PyBuffer_Release = pythonapi.PyBuffer_Release28+29+kernel32 = windll.kernel3230+GetStdHandle = kernel32.GetStdHandle31+ReadConsoleW = kernel32.ReadConsoleW32+WriteConsoleW = kernel32.WriteConsoleW33+GetLastError = kernel32.GetLastError34+GetCommandLineW = WINFUNCTYPE(LPWSTR)(35+ ('GetCommandLineW', windll.kernel32))36+CommandLineToArgvW = WINFUNCTYPE(37+ POINTER(LPWSTR), LPCWSTR, POINTER(c_int))(38+ ('CommandLineToArgvW', windll.shell32))39+40+41+STDIN_HANDLE = GetStdHandle(-10)42+STDOUT_HANDLE = GetStdHandle(-11)43+STDERR_HANDLE = GetStdHandle(-12)44+45+46+PyBUF_SIMPLE = 047+PyBUF_WRITABLE = 148+49+ERROR_SUCCESS = 050+ERROR_NOT_ENOUGH_MEMORY = 851+ERROR_OPERATION_ABORTED = 99552+53+STDIN_FILENO = 054+STDOUT_FILENO = 155+STDERR_FILENO = 256+57+EOF = b'\x1a'58+MAX_BYTES_WRITTEN = 3276759+60+61+class 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+ ]75+76+ if PY2:77+ _fields_.insert(-1, ('smalltable', c_ssize_t * 2))78+79+80+def 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))89+90+91+class _WindowsConsoleRawIOBase(io.RawIOBase):92+93+ def __init__(self, handle):94+ self.handle = handle95+96+ def isatty(self):97+ io.RawIOBase.isatty(self)98+ return True99+100+101+class _WindowsConsoleReader(_WindowsConsoleRawIOBase):102+103+ def readable(self):104+ return True105+106+ 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')113+114+ buffer = get_buffer(b, writable=True)115+ code_units_to_be_read = bytes_to_be_read // 2116+ code_units_read = c_ulong()117+118+ 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())125+126+ if buffer[0] == EOF:127+ return 0128+ return 2 * code_units_read.value129+130+131+class _WindowsConsoleWriter(_WindowsConsoleRawIOBase):132+133+ def writable(self):134+ return True135+136+ @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' % errno143+144+ 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()150+151+ WriteConsoleW(self.handle, buf, code_units_to_be_written,152+ byref(code_units_written), None)153+ bytes_written = 2 * code_units_written.value154+155+ if bytes_written == 0 and bytes_to_be_written > 0:156+ raise OSError(self._get_error_message(GetLastError()))157+ return bytes_written158+159+160+class ConsoleStream(object):161+162+ def __init__(self, text_stream, byte_stream):163+ self._text_stream = text_stream164+ self.buffer = byte_stream165+166+ @property167+ def name(self):168+ return self.buffer.name169+170+ 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)178+179+ def writelines(self, lines):180+ for line in lines:181+ self.write(line)182+183+ def __getattr__(self, name):184+ return getattr(self._text_stream, name)185+186+ def isatty(self):187+ return self.buffer.isatty()188+189+ def __repr__(self):190+ return '<ConsoleStream name=%r encoding=%r>' % (191+ self.name,192+ self.encoding,193+ )194+195+196+def _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)201+202+203+def _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)208+209+210+def _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)215+216+217+if PY2:218+ def _hash_py_argv():219+ return zlib.crc32('\x00'.join(sys.argv[1:]))220+221+ _initial_argv_hash = _hash_py_argv()222+223+ 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)]227+228+ 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+ break237+238+ return argv[1:]239+240+241+_stream_factories = {242+ 0: _get_text_stdin,243+ 1: _get_text_stdout,244+ 2: _get_text_stderr,245+}246+247+248+def _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
1 import os2 import sys3-import codecs3 from contextlib import contextmanager4 from itertools import repeat5 from functools import update_wrapper6 7 from .types import convert_type, IntRange, BOOL9-from .utils import make_str, make_default_short_help, echo8+from .utils import make_str, make_default_short_help, echo, get_os_args9 from .exceptions import ClickException, UsageError, BadParameter, Abort, \10 MissingParameter11 from .termui import prompt, confirm12 from .formatting import HelpFormatter, join_options13 from .parser import OptionParser, split_opt14 from .globals import push_context, pop_context15 17-from ._compat import PY2, isidentifier, iteritems, _check_for_unicode_literals16+from ._compat import PY2, isidentifier, iteritems17+from ._unicodefun import _check_for_unicode_literals, _verify_python3_env18 19 20 _missing = object()21 642 unmodified lines664 # 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()671 672 if args is None:684- 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 1036 unmodified linesmodified:click/decorators.py+2 added-1 removed
1 unmodified line2 import inspect3 4 from functools import update_wrapper5 6-from ._compat import iteritems, _check_for_unicode_literals6+from ._compat import iteritems7+from ._unicodefun import _check_for_unicode_literals8 from .utils import echo9 from .globals import get_current_context10 11 293 unmodified linesmodified:click/formatting.py+7 added-1 removed
2 unmodified lines3 from .parser import split_opt4 from ._compat import term_len5 6 7+# Can force a width. This is used by the test system8+FORCED_WIDTH = None9+10+11 def measure_table(rows):12 widths = {}13 for row in rows:14 for idx, col in enumerate(row):87 unmodified lines102 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 linesmodified:click/termui.py+3 added
39 unmodified lines40 41 If the user aborts the input by sending a interrupt signal, this42 function will catch it and raise a :exc:`Abort` exception.43 44+ .. versionadded:: 6.045+ Added unicode support for cmd.exe on Windows.46+47 .. versionadded:: 4.048 Added the `err` parameter.49 50 :param text: the text to show for the prompt.489 unmodified linesmodified:click/testing.py+3 added
155 unmodified lines156 157 old_stdin = sys.stdin158 old_stdout = sys.stdout159 old_stderr = sys.stderr160+ old_forced_width = clickpkg.formatting.FORCED_WIDTH161+ clickpkg.formatting.FORCED_WIDTH = 80162 163 env = self.make_env(env)164 165 if PY2:71 unmodified lines237 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_width242 243 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 are77 unmodified linesmodified:click/types.py+52 added-25 removed
1 import os2-import sys2 import stat3 4 from ._compat import open_stream, text_type, filename_to_ui, \6- get_filesystem_encoding, get_streerror5+ get_filesystem_encoding, get_streerror, _get_argv_encoding, PY26 from .exceptions import BadParameter7 from .utils import safecall, LazyFile8 9 97 unmodified lines107 name = 'text'108 109 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 value123 124 def __repr__(self):42 unmodified lines167 168 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)173 174 def __repr__(self):175 return 'INT'60 unmodified lines236 237 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)243 244 def __repr__(self):5 unmodified lines250 251 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)259 260 def __repr__(self):261 return 'UUID'82 unmodified lines344 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.347 348+ .. versionchanged:: 6.0349+ `allow_dash` was added.350+351 :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 lines358 :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.pathsep371 372 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_type383 384 if self.file_okay and not self.dir_okay:385 self.name = 'file'386 self.path_type = 'File'3 unmodified lines390 else:391 self.name = 'path'392 self.path_type = 'Path'393 394+ 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 rv401+402 def convert(self, value, param, ctx):403 rv = value381- if self.resolve_path:382- rv = os.path.realpath(rv)404 384- 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'-', '-')406 407+ if not is_dash:408+ if self.resolve_path:409+ rv = os.path.realpath(rv)410+411+ 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)420+421 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 lines438 self.path_type,439 filename_to_ui(value)440 ), param, ctx)441 415- return rv442+ return self.coerce_path_result(rv)443 444 445 class Tuple(CompositeParamType):446 """The default behavior of Click is to apply a type on a value directly.104 unmodified linesmodified:click/utils.py+32 added-1 removed
9 unmodified lines10 _default_text_stdout, _default_text_stderr, is_bytes, WIN11 12 if not PY2:13 from ._compat import _find_binary_writer14+elif WIN:15+ from ._winconsole import _get_windows_argv, \16+ _hash_py_argv, _initial_argv_hash17 18 19 echo_native_types = string_types + (bytes, bytearray)20 215 unmodified lines236 237 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.242 243 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 lines249 terminal.250 251 .. _colorama: http://pypi.python.org/pypi/colorama252 253+ .. 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.258+259 .. versionchanged:: 2.0260 Starting with version 2.0 of Click, the echo function will work261 with colorama if it's installed.262 127 unmodified lines390 f = KeepOpenFile(f)391 return f392 393 394+def 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.399+400+ 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.405+406+ .. 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:]413+414+415 def 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 will62 unmodified linesmodified:docs/index.rst+1 added
73 unmodified lines74 utils75 bashcomplete76 exceptions77 python378+ wincmd79 80 API Reference81 -------------82 18 unmodified linesmodified:docs/options.rst+2 added-2 removed
211 unmodified lines212 213 import sys214 215 @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 lines467 468 .. click:example::469 470 @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!')474 475 .. admonition:: Callback Signature Changes220 unmodified linesmodified:docs/python3.rst+6 added
137 unmodified lines138 139 export LC_ALL=C.UTF-8140 export LANG=C.UTF-8141 142+On some systems it was reported that `UTF-8` has to be written as `UTF8`143+and vice versa. To see which locales are supported you can invoke144+``locale -a``::145+146+ locale -a147+148 You need to do this before you invoke your Python script. If you are149 curious about the reasons for this, you can join the discussions in the150 Python 3 bug tracker:151 32 unmodified linesmodified:docs/utils.rst+19 added
28 unmodified lines29 suppressed by passing ``nl=False``::30 31 click.echo(b'\xe2\x98\x83', nl=False)32 33+Last but not least :func:`echo` uses click's intelligent internal output34+streams to stdout and stderr which support unicode output on the Windows35+console. This means for as long as you are using `click.echo` you can36+output unicode character (there are some limitations on the default font37+with regards to which characters can be displayed). This functionality is38+new in Click 6.0.39+40+.. versionadded:: 6.041+42+Click now emulates output streams on Windows to support unicode to the43+Windows console through separate APIs. For more information see44+`wincmd`_.45+46 .. versionadded:: 3.047 48 Starting with Click 3.0 you can also easily print to standard error by49 passing ``err=True``::228 unmodified lines278 279 stdin_text = click.get_text_stream('stdin')280 stdout_binary = click.get_binary_stream('stdout')281 282+.. versionadded:: 6.0283 284+Click now emulates output streams on Windows to support unicode to the285+Windows console through separate APIs. For more information see286+`wincmd`_.287+288+289 Intelligent File Opening290 ------------------------291 292 .. versionadded:: 3.0106 unmodified linesadded:docs/wincmd.rst+73 added
1+Windows Console Notes2+=====================3+4+.. versionadded:: 6.05+6+Until Click 6.0 there are various bugs and limitations with using Click on7+a Windows console. Most notably the decoding of command line arguments8+was performed with the wrong encoding on Python 2 and on all versions of9+Python output of unicode characters was impossible. Starting with Click10+6.0 we now emulate output streams on Windows to support unicode to the11+Windows console through separate APIs and we perform different decoding of12+parameters.13+14+Here is a brief overview of how this works and what it means to you.15+16+Unicode Arguments17+-----------------18+19+Click internally is generally based on the concept that any argument can20+come in as either byte string or unicode string and conversion is21+performed to the type expected value as late as possible. This has some22+advantages as it allows us to accept the data in the most appropriate form23+for the operating system and Python version.24+25+For instance paths are left as bytes on Python 2 unless you explicitly26+tell it otherwise.27+28+This caused some problems on Windows where initially the wrong encoding29+was used and garbage ended up in your input data. We not only fixed the30+encoding part, but we also now extract unicode parameters from `sys.argv`.31+32+This means that on Python 2 under Windows, the arguments processed will33+*most likely* be of unicode nature and not bytes. This was something that34+previously did not really happen unless you explicitly passed in unicode35+parameters so your custom types need to be aware of this.36+37+There is also another limitation with this: if `sys.argv` was modified38+prior to invoking a click handler, we have to fall back to the regular39+byte input in which case not all unicode values are available but only a40+subset of the codepage used for parameters.41+42+Unicode Output and Input43+------------------------44+45+Unicode output and input on Windows is implemented through the concept of46+a dispatching text stream. What this means is that when click first needs47+a text output (or input) stream on windows it goes through a few checks to48+figure out of a windows console is connected or not. If no Windows49+console is present then the text output stream is returned as such and the50+encoding for that stream is set to ``utf-8`` like on all platforms.51+52+However if a console is connected the stream will instead be emulated and53+use the cmd.exe unicode APIs to output text information. In this case the54+stream will also use ``utf-16-le`` as internal encoding. However there is55+some hackery going on that the underlying raw IO buffer is still bypassing56+the unicode APIs and byte output through an indirection is still possible.57+58+This hackery is used on both Python 2 and Python 3 as neither version of59+Python has native support for cmd.exe with unicode characters. There are60+some limitations you need to be aware of:61+62+* 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.70+71+Another important thing to note is that the Windows console's default72+fonts do not support a lot of characters which means that you are mostly73+limited to international letters but no emojis or special characters.modified:tests/test_arguments.py+6 added-4 removed
1 # -*- coding: utf-8 -*-2 import click3+from click._compat import PY24 5 6 def test_nargs_star(runner):7 @click.command()110 unmodified lines118 119 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 lines236 click.echo(arg)237 238 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 lines253 click.echo(arg)254 255 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
1 import sys2 import json3 import subprocess4 5+from click._compat import WIN6 7+8 IMPORT_TEST = b'''\9 try:10 import __builtin__ as builtins11 except ImportError:19 unmodified lines31 32 ALLOWED_IMPORTS = set([33 'weakref', 'os', 'struct', 'collections', 'sys', 'contextlib',34 'functools', 'stat', 're', 'codecs', 'inspect', 'itertools', 'io',33- 'threading'35+ 'threading', 'colorama'36 ])37 38+if WIN:39+ ALLOWED_IMPORTS.update(['ctypes', 'ctypes.wintypes', 'msvcrt', 'time',40+ 'zlib'])41 42+43 def 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 linesmodified:tests/test_options.py+16 added-11 removed
2 unmodified lines3 import os4 import click5 import pytest6 7+from click._compat import text_type8 9+10 def 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 lines145 146 147 def 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 pass155 156 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.output160 161+162 def 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)169 167- 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)172 170- 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.exception176 177+178 def test_nargs_envvar(runner):179 @click.command()180 @click.option('--arg', nargs=2)181 def cmd(arg):156 unmodified linesmodified:tests/test_testing.py+2 added-2 removed
3 unmodified lines4 import click5 6 from click.testing import CliRunner7 8-from click._compat import PY28+from click._compat import PY2, WIN9 10 # Use the most reasonable io that users would use for the python version.11 if PY2:12 from cStringIO import StringIO as ReasonableBytesIO103 unmodified lines116 result = runner.invoke(cli)117 assert result.exit_code == 1118 119 120+@pytest.mark.skipif(WIN, reason='Test does not make sense on Windows.')121 def test_with_color():122 @click.command()123 def cli():124 click.secho('hello world', fg='blue')57 unmodified lines182 183 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 lines5 6 import click7 import click.utils8 import click._termui_impl9+from click._compat import WIN, PY210 11 12 def test_echo(runner):13 with runner.isolation() as out:1 unmodified line15 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'21 22 # If we are in Python 2, we expect that writing bytes into a string io23 # does not do anything crazy. In Python 358 unmodified lines82 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'86 87+ # 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'91 92+93 def test_prompts(runner):94 @click.command()95 def test():96 if click.confirm('Foo'):32 unmodified lines129 assert not result.exception130 assert result.output == 'Foo [Y/n]: n\nno :(\n'131 132 133+@pytest.mark.skipif(WIN, reason='Different behavior on windows.')134 def test_prompts_abort(monkeypatch, capsys):135 def f(_):136 raise KeyboardInterrupt()137 7 unmodified lines145 out, err = capsys.readouterr()146 assert out == 'Password: \nScrew you.\n'147 148 149+@pytest.mark.skipif(WIN, reason='Different behavior on windows.')150 @pytest.mark.parametrize('cat', ['cat', 'cat ', 'cat '])151 def 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 line155 out, err = capfd.readouterr()156 assert out == 'haha\n'157 158 159+@pytest.mark.skipif(WIN, reason='Test does not make sense on Windows.')160 def test_echo_color_flag(monkeypatch, capfd):161 isatty = True162 monkeypatch.setattr(click._compat, 'isatty', lambda x: isatty)163 19 unmodified lines183 out, err = capfd.readouterr()184 assert out == text + '\n'185 186 187+@pytest.mark.skipif(WIN, reason='Test too complex to make work windows.')188 def 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 lines262 assert result.exception is None263 assert result.output == 'foobar\nmeep\n'264 265 266+@pytest.mark.xfail(WIN and not PY2, reason='God knows ...')267 def test_iter_keepopenfile(tmpdir):259-268 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()274 275 276+@pytest.mark.xfail(WIN and not PY2, reason='God knows ...')277 def test_iter_lazyfile(tmpdir):269-278 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 linesmodified:.travis.yml+1 added
2 unmodified lines3 - "2.6"4 - "2.7"5 - "3.3"6 - "3.4"7+ - "3.5"8 - "pypy"9 10 env:11 - REQUIREMENTS=colorama17 unmodified linesmodified:CHANGES+20 added
14 unmodified lines15 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.39 40 Version 5.141 -----------42 251 unmodified lines