Skip to content
Myr

remove py2 parts of _compat module

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

authored by David Lord · committed by David Lord · parent 5cddd7f · Browse files · 16 files+267 added−639 removed
This commit

State

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

Diff stats

16 files+267 added−639 removed

  • tests:+12 added−30 removed
  • other:+255 added−609 removed

16 files+267 added−639 removed

modified:docs/conf.py+5 added
1from pallets_sphinx_themes import get_version2from pallets_sphinx_themes import ProjectLink34import click._compat56# compat until pallets-sphinx-themes is updated7click._compat.text_type = str89# Project --------------------------------------------------------------1011project = "Click"12copyright = "2014 Pallets"
43 unmodified lines
modified:src/click/__init__.py+1 added-5 removed
70 unmodified lines
71from .utils import get_os_args72from .utils import get_text_stream73from .utils import open_file7475# Controls if click should emit the warning about the use of unicode76# literals.77disable_unicode_literals_warning = False7879__version__ = "8.0.dev"75__version__ = "8.0.0.dev"
modified:src/click/_compat.py+168 added-347 removed
1# flake8: noqa1import codecs2import io3import os4import re5import sys6from weakref import WeakKeyDictionary79PY2 = sys.version_info[0] == 28CYGWIN = sys.platform.startswith("cygwin")9MSYS2 = sys.platform.startswith("win") and ("GCC" in sys.version)10# Determine local App Engine environment, per Google's own suggestion11APP_ENGINE = "APPENGINE_RUNTIME" in os.environ and "Development/" in os.environ.get(12 "SERVER_SOFTWARE", ""13)14WIN = sys.platform.startswith("win") and not APP_ENGINE and not MSYS215DEFAULT_COLUMNS = 80181916auto_wrap_for_ansi = None17colorama = None18get_winterm_size = None19_ansi_re = re.compile(r"\033\[[;?0-9]*[a-zA-Z]")202122def get_filesystem_encoding():
43 unmodified lines
66 force_writable=False,67 **extra68 ):69 self._stream = stream = _FixupStream(stream, force_readable, force_writable)71 io.TextIOWrapper.__init__(self, stream, encoding, errors, **extra)70 super().__init__(stream, encoding, errors, **extra)7173 # The io module is a place where the Python 3 text behavior74 # was forced upon Python 2, so we need to unbreak75 # it to look like Python 2.76 if PY2:7778 def write(self, x):79 if isinstance(x, str) or is_bytes(x):80 try:81 self.flush()82 except Exception:83 pass84 return self.buffer.write(str(x))85 return io.TextIOWrapper.write(self, x)8687 def writelines(self, lines):88 for line in lines:89 self.write(line)9072 def __del__(self):73 try:74 self.detach()75 except Exception:
25 unmodified lines
101 def read1(self, size):102 f = getattr(self._stream, "read1", None)103 if f is not None:104 return f(size)124 # We only dispatch to readline instead of read in Python 2 as we125 # do not want cause problems with the different implementation126 # of line buffering.127 if PY2:128 return self._stream.readline(size)105106 return self._stream.read(size)107108 def readable(self):109 if self._force_readable:
32 unmodified lines
142 return False143 return True144145169if PY2:170 text_type = unicode171 raw_input = raw_input172 string_types = (str, unicode)173 int_types = (int, long)174 iteritems = lambda x: x.iteritems()175 range_type = xrange146def is_bytes(x):147 return isinstance(x, (bytes, memoryview, bytearray))148177 from pipes import quote as shlex_quote149179 def is_bytes(x):180 return isinstance(x, (buffer, bytearray))181182 _identifier_re = re.compile(r"^[a-zA-Z_][a-zA-Z0-9_]*$")183184 # For Windows, we need to force stdout/stdin/stderr to binary if it's185 # fetched for that. This obviously is not the most correct way to do186 # it as it changes global state. Unfortunately, there does not seem to187 # be a clear better way to do it as just reopening the file in binary188 # mode does not change anything.189 #190 # An option would be to do what Python 3 does and to open the file as191 # binary only, patch it back to the system, and then use a wrapper192 # stream that converts newlines. It's not quite clear what's the193 # correct option here.194 #195 # This code also lives in _winconsole for the fallback to the console196 # emulation stream.197 #198 # There are also Windows environments where the `msvcrt` module is not199 # available (which is why we use try-catch instead of the WIN variable200 # here), such as the Google App Engine development server on Windows. In201 # those cases there is just nothing we can do.202 def set_binary_mode(f):203 return f204150def _is_binary_reader(stream, default=False):151 try:206 import msvcrt207 except ImportError:208 pass209 else:152 return isinstance(stream.read(0), bytes)153 except Exception:154 return default155 # This happens in some cases where the stream was already156 # closed. In this case, we assume the default.157211 def set_binary_mode(f):212 try:213 fileno = f.fileno()214 except Exception:215 pass216 else:217 msvcrt.setmode(fileno, os.O_BINARY)218 return f158159def _is_binary_writer(stream, default=False):160 try:221 import fcntl222 except ImportError:223 pass224 else:161 stream.write(b"")162 except Exception:163 try:164 stream.write("")165 return False166 except Exception:167 pass168 return default169 return True170226 def set_binary_mode(f):227 try:228 fileno = f.fileno()229 except Exception:230 pass231 else:232 flags = fcntl.fcntl(fileno, fcntl.F_GETFL)233 fcntl.fcntl(fileno, fcntl.F_SETFL, flags & ~os.O_NONBLOCK)234 return f171236 def isidentifier(x):237 return _identifier_re.search(x) is not None172def _find_binary_reader(stream):173 # We need to figure out if the given stream is already binary.174 # This can happen because the official docs recommend detaching175 # the streams to get binary streams. Some code might do this, so176 # we need to deal with this case explicitly.177 if _is_binary_reader(stream, False):178 return stream179239 def get_binary_stdin():240 return set_binary_mode(sys.stdin)180 buf = getattr(stream, "buffer", None)181242 def get_binary_stdout():243 _wrap_std_stream("stdout")244 return set_binary_mode(sys.stdout)182 # Same situation here; this time we assume that the buffer is183 # actually binary in case it's closed.184 if buf is not None and _is_binary_reader(buf, True):185 return buf186246 def get_binary_stderr():247 _wrap_std_stream("stderr")248 return set_binary_mode(sys.stderr)187250 def get_text_stdin(encoding=None, errors=None):251 rv = _get_windows_console_stream(sys.stdin, encoding, errors)252 if rv is not None:253 return rv254 return _make_text_stream(sys.stdin, encoding, errors, force_readable=True)188def _find_binary_writer(stream):189 # We need to figure out if the given stream is already binary.190 # This can happen because the official docs recommend detaching191 # the streams to get binary streams. Some code might do this, so192 # we need to deal with this case explicitly.193 if _is_binary_writer(stream, False):194 return stream195256 def get_text_stdout(encoding=None, errors=None):257 _wrap_std_stream("stdout")258 rv = _get_windows_console_stream(sys.stdout, encoding, errors)259 if rv is not None:260 return rv261 return _make_text_stream(sys.stdout, encoding, errors, force_writable=True)196 buf = getattr(stream, "buffer", None)197263 def get_text_stderr(encoding=None, errors=None):264 _wrap_std_stream("stderr")265 rv = _get_windows_console_stream(sys.stderr, encoding, errors)266 if rv is not None:267 return rv268 return _make_text_stream(sys.stderr, encoding, errors, force_writable=True)198 # Same situation here; this time we assume that the buffer is199 # actually binary in case it's closed.200 if buf is not None and _is_binary_writer(buf, True):201 return buf202270 def filename_to_ui(value):271 if isinstance(value, bytes):272 value = value.decode(get_filesystem_encoding(), "replace")273 return value203204def _stream_is_misconfigured(stream):205 """A stream is misconfigured if its encoding is ASCII."""206 # If the stream does not have an encoding set, we assume it's set207 # to ASCII. This appears to happen in certain unittest208 # environments. It's not quite clear what the correct behavior is209 # but this at least will force Click to recover somehow.210 return is_ascii_encoding(getattr(stream, "encoding", None) or "ascii")211276else:277 import io212279 text_type = str280 raw_input = input281 string_types = (str,)282 int_types = (int,)283 range_type = range284 isidentifier = lambda x: x.isidentifier()285 iteritems = lambda x: iter(x.items())213def _is_compat_stream_attr(stream, attr, value):214 """A stream attribute is compatible if it is equal to the215 desired value or the desired value is unset and the attribute216 has a value.217 """218 stream_value = getattr(stream, attr, None)219 return stream_value == value or (value is None and stream_value is not None)220287 from shlex import quote as shlex_quote221289 def is_bytes(x):290 return isinstance(x, (bytes, memoryview, bytearray))222def _is_compatible_text_stream(stream, encoding, errors):223 """Check if a stream's encoding and errors attributes are224 compatible with the desired values.225 """226 return _is_compat_stream_attr(227 stream, "encoding", encoding228 ) and _is_compat_stream_attr(stream, "errors", errors)229292 def _is_binary_reader(stream, default=False):293 try:294 return isinstance(stream.read(0), bytes)295 except Exception:296 return default297 # This happens in some cases where the stream was already298 # closed. In this case, we assume the default.230300 def _is_binary_writer(stream, default=False):301 try:302 stream.write(b"")303 except Exception:304 try:305 stream.write("")306 return False307 except Exception:308 pass309 return default310 return True231def _force_correct_text_stream(232 text_stream,233 encoding,234 errors,235 is_binary,236 find_binary,237 force_readable=False,238 force_writable=False,239):240 if is_binary(text_stream, False):241 binary_reader = text_stream242 else:243 # If the stream looks compatible, and won't default to a244 # misconfigured ascii encoding, return it as-is.245 if _is_compatible_text_stream(text_stream, encoding, errors) and not (246 encoding is None and _stream_is_misconfigured(text_stream)247 ):248 return text_stream249312 def _find_binary_reader(stream):313 # We need to figure out if the given stream is already binary.314 # This can happen because the official docs recommend detaching315 # the streams to get binary streams. Some code might do this, so316 # we need to deal with this case explicitly.317 if _is_binary_reader(stream, False):318 return stream250 # Otherwise, get the underlying binary reader.251 binary_reader = find_binary(text_stream)252320 buf = getattr(stream, "buffer", None)253 # If that's not possible, silently use the original reader254 # and get mojibake instead of exceptions.255 if binary_reader is None:256 return text_stream257322 # Same situation here; this time we assume that the buffer is323 # actually binary in case it's closed.324 if buf is not None and _is_binary_reader(buf, True):325 return buf258 # Default errors to replace instead of strict in order to get259 # something that works.260 if errors is None:261 errors = "replace"262327 def _find_binary_writer(stream):328 # We need to figure out if the given stream is already binary.329 # This can happen because the official docs recommend detaching330 # the streams to get binary streams. Some code might do this, so331 # we need to deal with this case explicitly.332 if _is_binary_writer(stream, False):333 return stream263 # Wrap the binary stream in a text stream with the correct264 # encoding parameters.265 return _make_text_stream(266 binary_reader,267 encoding,268 errors,269 force_readable=force_readable,270 force_writable=force_writable,271 )272335 buf = getattr(stream, "buffer", None)273337 # Same situation here; this time we assume that the buffer is338 # actually binary in case it's closed.339 if buf is not None and _is_binary_writer(buf, True):340 return buf274def _force_correct_text_reader(text_reader, encoding, errors, force_readable=False):275 return _force_correct_text_stream(276 text_reader,277 encoding,278 errors,279 _is_binary_reader,280 _find_binary_reader,281 force_readable=force_readable,282 )283342 def _stream_is_misconfigured(stream):343 """A stream is misconfigured if its encoding is ASCII."""344 # If the stream does not have an encoding set, we assume it's set345 # to ASCII. This appears to happen in certain unittest346 # environments. It's not quite clear what the correct behavior is347 # but this at least will force Click to recover somehow.348 return is_ascii_encoding(getattr(stream, "encoding", None) or "ascii")284350 def _is_compat_stream_attr(stream, attr, value):351 """A stream attribute is compatible if it is equal to the352 desired value or the desired value is unset and the attribute353 has a value.354 """355 stream_value = getattr(stream, attr, None)356 return stream_value == value or (value is None and stream_value is not None)357358 def _is_compatible_text_stream(stream, encoding, errors):359 """Check if a stream's encoding and errors attributes are360 compatible with the desired values.361 """362 return _is_compat_stream_attr(363 stream, "encoding", encoding364 ) and _is_compat_stream_attr(stream, "errors", errors)365366 def _force_correct_text_stream(367 text_stream,285def _force_correct_text_writer(text_writer, encoding, errors, force_writable=False):286 return _force_correct_text_stream(287 text_writer,288 encoding,289 errors,370 is_binary,371 find_binary,372 force_readable=False,373 force_writable=False,374 ):375 if is_binary(text_stream, False):376 binary_reader = text_stream377 else:378 # If the stream looks compatible, and won't default to a379 # misconfigured ascii encoding, return it as-is.380 if _is_compatible_text_stream(text_stream, encoding, errors) and not (381 encoding is None and _stream_is_misconfigured(text_stream)382 ):383 return text_stream290 _is_binary_writer,291 _find_binary_writer,292 force_writable=force_writable,293 )294385 # Otherwise, get the underlying binary reader.386 binary_reader = find_binary(text_stream)295388 # If that's not possible, silently use the original reader389 # and get mojibake instead of exceptions.390 if binary_reader is None:391 return text_stream296def get_binary_stdin():297 reader = _find_binary_reader(sys.stdin)298 if reader is None:299 raise RuntimeError("Was not able to determine binary stream for sys.stdin.")300 return reader301393 # Default errors to replace instead of strict in order to get394 # something that works.395 if errors is None:396 errors = "replace"302398 # Wrap the binary stream in a text stream with the correct399 # encoding parameters.400 return _make_text_stream(401 binary_reader,402 encoding,403 errors,404 force_readable=force_readable,405 force_writable=force_writable,406 )303def get_binary_stdout():304 writer = _find_binary_writer(sys.stdout)305 if writer is None:306 raise RuntimeError("Was not able to determine binary stream for sys.stdout.")307 return writer308408 def _force_correct_text_reader(text_reader, encoding, errors, force_readable=False):409 return _force_correct_text_stream(410 text_reader,411 encoding,412 errors,413 _is_binary_reader,414 _find_binary_reader,415 force_readable=force_readable,416 )309418 def _force_correct_text_writer(text_writer, encoding, errors, force_writable=False):419 return _force_correct_text_stream(420 text_writer,421 encoding,422 errors,423 _is_binary_writer,424 _find_binary_writer,425 force_writable=force_writable,426 )310def get_binary_stderr():311 writer = _find_binary_writer(sys.stderr)312 if writer is None:313 raise RuntimeError("Was not able to determine binary stream for sys.stderr.")314 return writer315428 def get_binary_stdin():429 reader = _find_binary_reader(sys.stdin)430 if reader is None:431 raise RuntimeError("Was not able to determine binary stream for sys.stdin.")432 return reader316434 def get_binary_stdout():435 writer = _find_binary_writer(sys.stdout)436 if writer is None:437 raise RuntimeError(438 "Was not able to determine binary stream for sys.stdout."439 )440 return writer317def get_text_stdin(encoding=None, errors=None):318 rv = _get_windows_console_stream(sys.stdin, encoding, errors)319 if rv is not None:320 return rv321 return _force_correct_text_reader(sys.stdin, encoding, errors, force_readable=True)322442 def get_binary_stderr():443 writer = _find_binary_writer(sys.stderr)444 if writer is None:445 raise RuntimeError(446 "Was not able to determine binary stream for sys.stderr."447 )448 return writer323450 def get_text_stdin(encoding=None, errors=None):451 rv = _get_windows_console_stream(sys.stdin, encoding, errors)452 if rv is not None:453 return rv454 return _force_correct_text_reader(455 sys.stdin, encoding, errors, force_readable=True456 )324def get_text_stdout(encoding=None, errors=None):325 rv = _get_windows_console_stream(sys.stdout, encoding, errors)326 if rv is not None:327 return rv328 return _force_correct_text_writer(sys.stdout, encoding, errors, force_writable=True)329458 def get_text_stdout(encoding=None, errors=None):459 rv = _get_windows_console_stream(sys.stdout, encoding, errors)460 if rv is not None:461 return rv462 return _force_correct_text_writer(463 sys.stdout, encoding, errors, force_writable=True464 )330466 def get_text_stderr(encoding=None, errors=None):467 rv = _get_windows_console_stream(sys.stderr, encoding, errors)468 if rv is not None:469 return rv470 return _force_correct_text_writer(471 sys.stderr, encoding, errors, force_writable=True472 )331def get_text_stderr(encoding=None, errors=None):332 rv = _get_windows_console_stream(sys.stderr, encoding, errors)333 if rv is not None:334 return rv335 return _force_correct_text_writer(sys.stderr, encoding, errors, force_writable=True)336474 def filename_to_ui(value):475 if isinstance(value, bytes):476 value = value.decode(get_filesystem_encoding(), "replace")477 else:478 value = value.encode("utf-8", "surrogateescape").decode("utf-8", "replace")479 return value337338def filename_to_ui(value):339 if isinstance(value, bytes):340 value = value.decode(get_filesystem_encoding(), "replace")341 else:342 value = value.encode("utf-8", "surrogateescape").decode("utf-8", "replace")343 return value344345482def get_streerror(e, default=None):346def get_strerror(e, default=None):347 if hasattr(e, "strerror"):348 msg = e.strerror349 else:350 if default is not None:
5 unmodified lines
356 return msg357358359def _wrap_io_open(file, mode, encoding, errors):496 """On Python 2, :func:`io.open` returns a text file wrapper that497 requires passing ``unicode`` to ``write``. Need to open the file in498 binary mode then wrap it in a subclass that can write ``str`` and499 ``unicode``.360 """Handles not passing ``encoding`` and ``errors`` in binary mode."""361 if "b" in mode:362 return io.open(file, mode)363501 Also handles not passing ``encoding`` and ``errors`` in binary mode.502 """503 binary = "b" in mode364 return io.open(file, mode, encoding=encoding, errors=errors)365505 if binary:506 kwargs = {}507 else:508 kwargs = {"encoding": encoding, "errors": errors}366510 if not PY2 or binary:511 return io.open(file, mode, **kwargs)512513 f = io.open(file, "{}b".format(mode.replace("t", "")))514 return _make_text_stream(f, **kwargs)515516367def open_stream(filename, mode="r", encoding=None, errors="strict", atomic=False):368 binary = "b" in mode369370 # Standard streams first. These are simple because they don't need
65 unmodified lines
436 f = _wrap_io_open(fd, mode, encoding, errors)437 return _AtomicFile(f, tmp_filename, os.path.realpath(filename)), True438439590# Used in a destructor call, needs extra protection from interpreter cleanup.591if hasattr(os, "replace"):592 _replace = os.replace593 _can_replace = True594else:595 _replace = os.rename596 _can_replace = not WIN597598440class _AtomicFile(object):441 def __init__(self, f, tmp_filename, real_filename):442 self._f = f443 self._tmp_filename = tmp_filename
7 unmodified lines
451 def close(self, delete=False):452 if self.closed:453 return454 self._f.close()614 if not _can_replace:615 try:616 os.remove(self._real_filename)617 except OSError:618 pass619 _replace(self._tmp_filename, self._real_filename)455 os.replace(self._tmp_filename, self._real_filename)456 self.closed = True457458 def __getattr__(self, name):459 return getattr(self._f, name)
7 unmodified lines
467 def __repr__(self):468 return repr(self._f)469470635auto_wrap_for_ansi = None636colorama = None637get_winterm_size = None638639471def strip_ansi(value):472 return _ansi_re.sub("", value)473474
23 unmodified lines
498if WIN:499 # Windows has a smaller terminal500 DEFAULT_COLUMNS = 79501671 from ._winconsole import _get_windows_console_stream, _wrap_std_stream502 from ._winconsole import _get_windows_console_stream503504 def _get_argv_encoding():505 import locale506507 return locale.getpreferredencoding()508678 if PY2:679680 def raw_input(prompt=""):681 sys.stderr.flush()682 if prompt:683 stdout = _default_text_stdout()684 stdout.write(prompt)685 stdin = _default_text_stdin()686 return stdin.readline().rstrip("\r\n")687509 try:510 import colorama511 except ImportError:512 pass
19 unmodified lines
532533 def _safe_write(s):534 try:535 return _write(s)715 except:536 except BaseException:537 ansi_wrapper.reset_all()538 raise539540 rv.write = _safe_write
14 unmodified lines
555556 def _get_argv_encoding():557 return getattr(sys.stdin, "encoding", None) or get_filesystem_encoding()558738 _get_windows_console_stream = lambda *x: None739 _wrap_std_stream = lambda *x: None559 def _get_windows_console_stream(f, encoding, errors):560 return None561562563def term_len(x):564 return len(strip_ansi(x))
47 unmodified lines
modified:src/click/_termui_impl.py+10 added-12 removed
5 unmodified lines
6"""7import contextlib8import math9import os10import shlex11import sys12import time1314from ._compat import _default_text_stdout15from ._compat import CYGWIN16from ._compat import get_best_encoding16from ._compat import int_types17from ._compat import isatty18from ._compat import open_stream19from ._compat import range_type20from ._compat import shlex_quote19from ._compat import strip_ansi20from ._compat import term_len21from ._compat import WIN22from .exceptions import ClickException
19 unmodified lines
42 try:43 hint = get_hint(obj)44 except TypeError:45 return None48 if hint is NotImplemented or not isinstance(hint, int_types) or hint < 0:46 if hint is NotImplemented or not isinstance(hint, int) or hint < 0:47 return None48 return hint4950
35 unmodified lines
86 length = _length_hint(iterable)87 if iterable is None:88 if length is None:89 raise TypeError("iterable or length is required")92 iterable = range_type(length)90 iterable = range(length)91 self.iter = iter(iterable)92 self.length = length93 self.length_known = length is not None94 self.pos = 0
263 unmodified lines
358 os.close(fd)359 try:360 if (361 hasattr(os, "system")364 and os.system("more {}".format(shlex_quote(filename))) == 0362 and os.system("more {}".format(shlex.quote(filename))) == 0363 ):364 return _pipepager(generator, "more", color)365 return _nullpager(stdout, generator, color)366 finally:
61 unmodified lines
428 encoding = get_best_encoding(sys.stdout)429 with open_stream(filename, "wb")[0] as f:430 f.write(text.encode(encoding))431 try:434 os.system("{} {}".format(shlex_quote(cmd), shlex_quote(filename)))432 os.system("{} {}".format(shlex.quote(cmd), shlex.quote(filename)))433 finally:434 os.unlink(filename)435436
36 unmodified lines
473 else:474 environ = None475 try:476 c = subprocess.Popen(479 "{} {}".format(shlex_quote(editor), shlex_quote(filename)),477 "{} {}".format(shlex.quote(editor), shlex.quote(filename)),478 env=environ,479 shell=True,480 )481 exit_code = c.wait()
68 unmodified lines
550 null.close()551 elif WIN:552 if locate:553 url = _unquote_file(url)556 args = "explorer /select,{}".format(shlex_quote(url))554 args = "explorer /select,{}".format(shlex.quote(url))555 else:558 args = 'start {} "" {}'.format("/WAIT" if wait else "", shlex_quote(url))556 args = 'start {} "" {}'.format("/WAIT" if wait else "", shlex.quote(url))557 return os.system(args)558 elif CYGWIN:559 if locate:560 url = _unquote_file(url)563 args = "cygstart {}".format(shlex_quote(os.path.dirname(url)))561 args = "cygstart {}".format(shlex.quote(os.path.dirname(url)))562 else:565 args = "cygstart {} {}".format("-w" if wait else "", shlex_quote(url))563 args = "cygstart {} {}".format("-w" if wait else "", shlex.quote(url))564 return os.system(args)565566 try:567 if locate:
109 unmodified lines
modified:src/click/_unicodefun.py-49 removed
1import codecs2import os3import sys35from ._compat import PY2478def _find_unicode_literals_frame():9 import __future__1011 if not hasattr(sys, "_getframe"): # not all Python implementations have it12 return 013 frm = sys._getframe(1)14 idx = 115 while frm is not None:16 if frm.f_globals.get("__name__", "").startswith("click."):17 frm = frm.f_back18 idx += 119 elif frm.f_code.co_flags & __future__.unicode_literals.compiler_flag:20 return idx21 else:22 break23 return 0242526def _check_for_unicode_literals():27 if not __debug__:28 return2930 from . import disable_unicode_literals_warning3132 if not PY2 or disable_unicode_literals_warning:33 return34 bad_frame = _find_unicode_literals_frame()35 if bad_frame <= 0:36 return37 from warnings import warn3839 warn(40 Warning(41 "Click detected the use of the unicode_literals __future__"42 " import. This is heavily discouraged because it can"43 " introduce subtle bugs in your code. You should instead"44 ' use explicit u"" literals for your unicode strings. For'45 " more information see"46 " https://click.palletsprojects.com/python3/"47 ),48 stacklevel=bad_frame,49 )50515def _verify_python3_env():6 """Ensures that the environment is good for unicode on Python 3."""54 if PY2:55 return7 try:8 import locale910 fs_enc = codecs.lookup(locale.getpreferredencoding()).name
72 unmodified lines
modified:src/click/_winconsole.py+8 added-67 removed
7 unmodified lines
8# the entire interpreter but just work in our little world of9# echo and prompt.10import ctypes11import io12import os13import sys12import time15import zlib13from ctypes import byref14from ctypes import c_char15from ctypes import c_char_p16from ctypes import c_int
2 unmodified lines
19from ctypes import c_void_p20from ctypes import POINTER21from ctypes import py_object22from ctypes import windll26from ctypes import WinError23from ctypes import WINFUNCTYPE24from ctypes.wintypes import DWORD25from ctypes.wintypes import HANDLE26from ctypes.wintypes import LPCWSTR
1 unmodified line
2829import msvcrt3031from ._compat import _NonClosingTextIOWrapper36from ._compat import PY237from ._compat import text_type3233try:34 from ctypes import pythonapi35
54 unmodified lines
90 ("suboffsets", c_ssize_p),91 ("internal", c_void_p),92 ]93100 if PY2:101 _fields_.insert(-1, ("smalltable", c_ssize_t * 2))9410395# On PyPy we cannot get buffers so our ability to operate here is96# severely limited.97if pythonapi is None:98 get_buffer = None
95 unmodified lines
194 def name(self):195 return self.buffer.name196197 def write(self, x):207 if isinstance(x, text_type):198 if isinstance(x, str):199 return self._text_stream.write(x)200 try:201 self.flush()202 except Exception:
40 unmodified lines
243 self.__wrapped.write(text[written : written + to_write])244 written += to_write245246256_wrapped_std_streams = set()257258259def _wrap_std_stream(name):260 # Python 2 & Windows 7 and below261 if (262 PY2263 and sys.getwindowsversion()[:2] <= (6, 1)264 and name not in _wrapped_std_streams265 ):266 setattr(sys, name, WindowsChunkedWriter(getattr(sys, name)))267 _wrapped_std_streams.add(name)268269247def _get_text_stdin(buffer_stream):248 text_stream = _NonClosingTextIOWrapper(249 io.BufferedReader(_WindowsConsoleReader(STDIN_HANDLE)),250 "utf-16-le",
22 unmodified lines
273 )274 return ConsoleStream(text_stream, buffer_stream)275276300if PY2:301302 def _hash_py_argv():303 return zlib.crc32("\x00".join(sys.argv[1:]))304305 _initial_argv_hash = _hash_py_argv()306307 def _get_windows_argv():308 argc = c_int(0)309 argv_unicode = CommandLineToArgvW(GetCommandLineW(), byref(argc))310 if not argv_unicode:311 raise WinError()312 try:313 argv = [argv_unicode[i] for i in range(0, argc.value)]314 finally:315 LocalFree(argv_unicode)316 del argv_unicode317318 if not hasattr(sys, "frozen"):319 argv = argv[1:]320 while len(argv) > 0:321 arg = argv[0]322 if not arg.startswith("-") or arg == "-":323 break324 argv = argv[1:]325 if arg.startswith(("-c", "-m")):326 break327328 return argv[1:]329330277_stream_factories = {278 0: _get_text_stdin,279 1: _get_text_stdout,280 2: _get_text_stderr,
15 unmodified lines
296297def _get_windows_console_stream(f, encoding, errors):298 if (299 get_buffer is not None354 and encoding in ("utf-16-le", None)355 and errors in ("strict", None)300 and encoding in {"utf-16-le", None}301 and errors in {"strict", None}302 and _is_console(f)303 ):304 func = _stream_factories.get(f.fileno())305 if func is not None:360 if not PY2:361 f = getattr(f, "buffer", None)362 if f is None:363 return None364 else:365 # If we are on Python 2 we need to set the stream that we366 # deal with to binary mode as otherwise the exercise if a367 # bit moot. The same problems apply as for368 # get_binary_stdin and friends from _compat.369 msvcrt.setmode(f.fileno(), os.O_BINARY)306 f = getattr(f, "buffer", None)307308 if f is None:309 return None310311 return func(f)
modified:src/click/core.py+8 added-18 removed
4 unmodified lines
5from contextlib import contextmanager6from functools import update_wrapper7from itertools import repeat89from ._compat import isidentifier10from ._compat import iteritems11from ._compat import PY212from ._compat import string_types13from ._unicodefun import _check_for_unicode_literals9from ._unicodefun import _verify_python3_env10from .exceptions import Abort11from .exceptions import BadParameter12from .exceptions import ClickException
12 unmodified lines
25from .types import BOOL26from .types import convert_type27from .types import IntRange28from .utils import echo34from .utils import get_os_args29from .utils import make_default_short_help30from .utils import make_str31from .utils import PacifyFlushWrapper32
696 unmodified lines
729 :param parent: the parent context if available.730 :param extra: extra keyword arguments forwarded to the context731 constructor.732 """739 for key, value in iteritems(self.context_settings):733 for key, value in self.context_settings.items():734 if key not in extra:735 extra[key] = value736 ctx = Context(self, info_name=info_name, parent=parent, **extra)737 with ctx.scope(cleanup=False):
52 unmodified lines
790 of :meth:`invoke`.791 :param extra: extra keyword arguments are forwarded to the context792 constructor. See :class:`Context` for more information.793 """800 # If we are in Python 3, we will verify that the environment is801 # sane at this point or reject further execution to avoid a802 # broken script.803 if not PY2:804 _verify_python3_env()805 else:806 _check_for_unicode_literals()794 # Verify that the environment is configured correctly, or reject795 # further execution to avoid a broken script.796 _verify_python3_env()797798 if args is None:809 args = get_os_args()799 args = sys.argv[1:]800 else:801 args = list(args)802803 if prog_name is None:
1026 unmodified lines
1830 name = None1831 possible_names = []18321833 for decl in decls:1844 if isidentifier(decl):1834 if decl.isidentifier():1835 if name is not None:1836 raise TypeError("Name defined twice")1837 name = decl1838 else:
13 unmodified lines
18521853 if name is None and possible_names:1854 possible_names.sort(key=lambda x: -len(x[0])) # group long options first1855 name = possible_names[0][1].replace("-", "_").lower()1866 if not isidentifier(name):1856 if not name.isidentifier():1857 name = None18581859 if name is None:1860 if not expose_value:
70 unmodified lines
1931 else envvar1932 )1933 )1934 if self.default is not None and (self.show_default or ctx.show_default):1945 if isinstance(self.show_default, string_types):1935 if isinstance(self.show_default, str):1936 default_string = "({})".format(self.show_default)1937 elif isinstance(self.default, (list, tuple)):1938 default_string = ", ".join(str(d) for d in self.default)1939 elif inspect.isfunction(self.default):
138 unmodified lines
modified:src/click/decorators.py+1 added-4 removed
1import inspect2import sys3from functools import update_wrapper45from ._compat import iteritems6from ._unicodefun import _check_for_unicode_literals5from .core import Argument6from .core import Command7from .core import Group8from .core import Option
82 unmodified lines
91 help = help.decode("utf-8")92 else:93 help = inspect.cleandoc(help)94 attrs["help"] = help97 _check_for_unicode_literals()95 return cls(96 name=name or f.__name__.lower().replace("_", "-"),97 callback=f,98 params=params,
184 unmodified lines
283 pass284 else:285 for dist in pkg_resources.working_set:286 scripts = dist.get_entry_map().get("console_scripts") or {}290 for _, entry_point in iteritems(scripts):287 for entry_point in scripts.values():288 if entry_point.module_name == module:289 ver = dist.version290 break291 if ver is None:
39 unmodified lines
modified:src/click/exceptions.py+2 added-19 removed
1from ._compat import filename_to_ui2from ._compat import get_text_stderr3from ._compat import PY23from .utils import echo456def _join_param_hints(param_hint):
4 unmodified lines
1112class ClickException(Exception):13 """An exception that Click can handle and show to the user."""1416 #: The exit code for this exception15 #: The exit code for this exception.16 exit_code = 11718 def __init__(self, message):20 ctor_msg = message21 if PY2:22 if ctor_msg is not None:23 ctor_msg = ctor_msg.encode("utf-8")24 Exception.__init__(self, ctor_msg)19 super().__init__(message)20 self.message = message2122 def format_message(self):23 return self.message2425 def __str__(self):26 return self.message2733 if PY2:34 __unicode__ = __str__3536 def __str__(self):37 return self.message.encode("utf-8")3828 def show(self, file=None):29 if file is None:30 file = get_text_stderr()31 echo("Error: {}".format(self.format_message()), file=file)
118 unmodified lines
150 return "missing parameter: {}".format(param_name)151 else:152 return self.message153165 if PY2:166 __unicode__ = __str__154168 def __str__(self):169 return self.__unicode__().encode("utf-8")170171155class NoSuchOption(UsageError):156 """Raised if click attempted to handle an option that does not157 exist.158
78 unmodified lines
modified:src/click/termui.py+3 added-6 removed
6 unmodified lines
78from ._compat import DEFAULT_COLUMNS9from ._compat import get_winterm_size10from ._compat import isatty11from ._compat import raw_input12from ._compat import string_types11from ._compat import strip_ansi14from ._compat import text_type12from ._compat import WIN13from .exceptions import Abort14from .exceptions import UsageError15from .globals import resolve_color_default
4 unmodified lines
20from .utils import LazyFile2122# The prompt functions to use. The doc tools currently override these23# functions to customize how they work.27visible_prompt_func = raw_input24visible_prompt_func = input2526_ansi_colors = {27 "black": 30,28 "red": 31,
245 unmodified lines
274 color = resolve_color_default(color)275276 if inspect.isgeneratorfunction(text_or_generator):277 i = text_or_generator()281 elif isinstance(text_or_generator, string_types):278 elif isinstance(text_or_generator, str):279 i = [text_or_generator]280 else:281 i = iter(text_or_generator)282283 # convert every element of i to a text type if necessary287 text_generator = (el if isinstance(el, string_types) else text_type(el) for el in i)284 text_generator = (el if isinstance(el, str) else str(el) for el in i)285286 from ._termui_impl import pager287288 return pager(itertools.chain(text_generator, "\n"), color)
404 unmodified lines
modified:src/click/testing.py+19 added-34 removed
1import contextlib2import io3import os4import shlex5import shutil6import sys
1 unmodified line
89from . import formatting10from . import termui11from . import utils11from ._compat import iteritems12from ._compat import PY213from ._compat import string_types12from ._compat import _find_binary_reader131416if PY2:17 from cStringIO import StringIO18else:19 import io20 from ._compat import _find_binary_reader212215class EchoingStdin(object):16 def __init__(self, input, output):17 self._input = input18 self._output = output
23 unmodified lines
4243def make_input_stream(input, charset):44 # Is already an input stream.45 if hasattr(input, "read"):54 if PY2:55 return input46 rv = _find_binary_reader(input)4748 if rv is not None:49 return rv5051 raise TypeError("Could not find binary reader for input stream.")5253 if input is None:54 input = b""55 elif not isinstance(input, bytes):56 input = input.encode(charset)65 if PY2:66 return StringIO(input)5758 return io.BytesIO(input)596061class Result(object):
112 unmodified lines
174 formatting.FORCED_WIDTH = 80175176 env = self.make_env(env)177187 if PY2:188 bytes_output = StringIO()189 if self.echo_stdin:190 input = EchoingStdin(input, bytes_output)191 sys.stdout = bytes_output192 if not self.mix_stderr:193 bytes_error = StringIO()194 sys.stderr = bytes_error195 else:196 bytes_output = io.BytesIO()178 bytes_output = io.BytesIO()197 if self.echo_stdin:198 input = EchoingStdin(input, bytes_output)199 input = io.TextIOWrapper(input, encoding=self.charset)200 sys.stdout = io.TextIOWrapper(bytes_output, encoding=self.charset)201 if not self.mix_stderr:202 bytes_error = io.BytesIO()203 sys.stderr = io.TextIOWrapper(bytes_error, encoding=self.charset)179180 if self.echo_stdin:181 input = EchoingStdin(input, bytes_output)182183 input = io.TextIOWrapper(input, encoding=self.charset)184 sys.stdout = io.TextIOWrapper(bytes_output, encoding=self.charset)185186 if not self.mix_stderr:187 bytes_error = io.BytesIO()188 sys.stderr = io.TextIOWrapper(bytes_error, encoding=self.charset)189190 if self.mix_stderr:191 sys.stderr = sys.stdout192193 sys.stdin = input
34 unmodified lines
228 utils.should_strip_ansi = should_strip_ansi229230 old_env = {}231 try:247 for key, value in iteritems(env):232 for key, value in env.items():233 old_env[key] = os.environ.get(key)234 if value is None:235 try:236 del os.environ[key]
2 unmodified lines
239 else:240 os.environ[key] = value241 yield (bytes_output, not self.mix_stderr and bytes_error)242 finally:258 for key, value in iteritems(old_env):243 for key, value in old_env.items():244 if value is None:245 try:246 del os.environ[key]247 except Exception:
53 unmodified lines
301 with self.isolation(input=input, env=env, color=color) as outstreams:302 exception = None303 exit_code = 0304320 if isinstance(args, string_types):305 if isinstance(args, str):306 args = shlex.split(args)307308 try:309 prog_name = extra.pop("prog_name")
58 unmodified lines
modified:src/click/types.py+9 added-17 removed
3 unmodified lines
45from ._compat import _get_argv_encoding6from ._compat import filename_to_ui7from ._compat import get_filesystem_encoding8from ._compat import get_streerror8from ._compat import get_strerror9from ._compat import open_stream10from ._compat import PY211from ._compat import text_type10from .exceptions import BadParameter11from .utils import LazyFile12from .utils import safecall13
77 unmodified lines
91 try:92 return self.func(value)93 except ValueError:94 try:97 value = text_type(value)95 value = str(value)96 except UnicodeError:99 value = str(value).decode("utf-8", "replace")97 value = value.decode("utf-8", "replace")9899 self.fail(value, param, ctx)100101102class UnprocessedParamType(ParamType):
74 unmodified lines
177 for normed_choice, original in normed_choices.items()178 }179180 if not self.case_sensitive:182 if PY2:183 lower = str.lower184 else:185 lower = str.casefold186187 normed_value = lower(normed_value)181 normed_value = normed_value.casefold()182 normed_choices = {189 lower(normed_choice): original183 normed_choice.casefold(): original184 for normed_choice, original in normed_choices.items()185 }186187 if normed_value in normed_choices:
232 unmodified lines
420 def convert(self, value, param, ctx):421 import uuid422423 try:430 if PY2 and isinstance(value, text_type):431 value = value.encode("ascii")424 return uuid.UUID(value)425 except ValueError:426 self.fail("{} is not a valid UUID value".format(value), param, ctx)427
80 unmodified lines
508 return f509 except (IOError, OSError) as e: # noqa: B014510 self.fail(511 "Could not open file: {}: {}".format(520 filename_to_ui(value), get_streerror(e)512 filename_to_ui(value), get_strerror(e)513 ),514 param,515 ctx,516 )
63 unmodified lines
580 self.path_type = "Path"581582 def coerce_path_result(self, rv):583 if self.type is not None and not isinstance(rv, self.type):592 if self.type is text_type:584 if self.type is str:585 rv = rv.decode(get_filesystem_encoding())586 else:587 rv = rv.encode(get_filesystem_encoding())588 return rv
103 unmodified lines
692 if isinstance(ty, tuple):693 return Tuple(ty)694 if isinstance(ty, ParamType):695 return ty704 if ty is text_type or ty is str or ty is None:696 if ty is str or ty is None:697 return STRING698 if ty is int:699 return INT700 # Booleans are only okay if not guessed. This is done because for
54 unmodified lines
modified:src/click/utils.py+21 added-31 removed
1 unmodified line
2import sys34from ._compat import _default_text_stderr5from ._compat import _default_text_stdout6from ._compat import _find_binary_writer7from ._compat import auto_wrap_for_ansi8from ._compat import binary_streams9from ._compat import filename_to_ui10from ._compat import get_filesystem_encoding10from ._compat import get_streerror11from ._compat import get_strerror12from ._compat import is_bytes13from ._compat import open_stream13from ._compat import PY214from ._compat import should_strip_ansi15from ._compat import string_types15from ._compat import strip_ansi16from ._compat import text_streams18from ._compat import text_type17from ._compat import WIN18from .globals import resolve_color_default1922if not PY2:23 from ._compat import _find_binary_writer24elif WIN:25 from ._winconsole import _get_windows_argv26 from ._winconsole import _hash_py_argv27 from ._winconsole import _initial_argv_hash2029echo_native_types = string_types + (bytes, bytearray)21echo_native_types = (str, bytes, bytearray)222324def _posixify(name):25 return "-".join(name.split()).lower()
17 unmodified lines
43 try:44 return value.decode(get_filesystem_encoding())45 except UnicodeError:46 return value.decode("utf-8", "replace")55 return text_type(value)47 return str(value)484950def make_default_short_help(help, max_length=45):51 """Return a condensed version of help string."""
68 unmodified lines
120 )121 except (IOError, OSError) as e: # noqa: E402122 from .exceptions import FileError123132 raise FileError(self.name, hint=get_streerror(e))124 raise FileError(self.name, hint=get_strerror(e))125 self._f = rv126 return rv127128 def close(self):
93 unmodified lines
222 file = _default_text_stdout()223224 # Convert non bytes/text into the native string type.225 if message is not None and not isinstance(message, echo_native_types):234 message = text_type(message)226 message = str(message)227228 if nl:229 message = message or u""238 if isinstance(message, text_type):230 if isinstance(message, str):231 message += u"\n"232 else:233 message += b"\n"234
1 unmodified line
236 # like bytes, we manually need to find the binary stream and write the237 # message in there. This is done separately so that most stream238 # types will work as you would expect. Eg: you can write to StringIO239 # for other cases.248 if message and not PY2 and is_bytes(message):240 if message and is_bytes(message):241 binary_file = _find_binary_writer(file)242 if binary_file is not None:243 file.flush()244 binary_file.write(message)
86 unmodified lines
331 return f332333334def get_os_args():343 """This returns the argument part of sys.argv in the most appropriate344 form for processing. What this means is that this return value is in345 a format that works for Click to process but does not necessarily346 correspond well to what's actually standard for the interpreter.335 """Returns the argument part of ``sys.argv``, removing the first336 value which is the name of the script.337348 On most environments the return value is ``sys.argv[:1]`` unchanged.349 However if you are on Windows and running Python 2 the return value350 will actually be a list of unicode strings instead because the351 default behavior on that platform otherwise will not be able to352 carry all possible values that sys.argv can have.353354 .. versionadded:: 6.0338 .. deprecated:: 8.0339 Will be removed in 8.1. Access ``sys.argv[1:]`` directly340 instead.341 """356 # We can only extract the unicode argv if sys.argv has not been357 # changed since the startup of the application.358 if PY2 and WIN and _initial_argv_hash == _hash_py_argv():359 return _get_windows_argv()342 import warnings343344 warnings.warn(345 "'get_os_args' is deprecated and will be removed in 8.1. Access"346 " 'sys.argv[1:]' directly instead.",347 DeprecationWarning,348 stacklevel=2,349 )350 return sys.argv[1:]351352353def format_filename(filename, shorten=False):
92 unmodified lines
modified:tests/test_arguments.py+6 added-17 removed
2 unmodified lines
34import pytest56import click7from click._compat import PY28from click._compat import text_type789def test_nargs_star(runner):10 @click.command()
69 unmodified lines
80 @click.command()81 @click.argument("arg")82 def from_bytes(arg):83 assert isinstance(86 arg, text_type84 arg, str85 ), "UTF-8 encoded argument should be implicitly converted to Unicode"8687 # Simulate empty locale environment variables90 if PY2:91 monkeypatch.setattr(sys.stdin, "encoding", "ANSI_X3.4-1968")92 monkeypatch.setattr(sys, "getfilesystemencoding", lambda: "ANSI_X3.4-1968")93 monkeypatch.setattr(sys, "getdefaultencoding", lambda: "ascii")94 else:95 monkeypatch.setattr(sys.stdin, "encoding", "utf-8")96 monkeypatch.setattr(sys, "getfilesystemencoding", lambda: "utf-8")97 monkeypatch.setattr(sys, "getdefaultencoding", lambda: "utf-8")88 monkeypatch.setattr(sys.stdin, "encoding", "utf-8")89 monkeypatch.setattr(sys, "getfilesystemencoding", lambda: "utf-8")90 monkeypatch.setattr(sys, "getdefaultencoding", lambda: "utf-8")9192 runner.invoke(93 from_bytes,94 [u"Something outside of ASCII range: 林".encode("UTF-8")],
165 unmodified lines
260 for arg in (a, b, c):261 click.echo(arg)262263 result = runner.invoke(cmd, ["a", "b", "c"])271 assert result.output.splitlines() == ["(u'a',)" if PY2 else "('a',)", "b", "c"]264 assert result.output.splitlines() == ["('a',)", "b", "c"]265266267def test_nargs_specified_plus_star_ordering(runner):268 @click.command()
4 unmodified lines
273 for arg in (a, b, c):274 click.echo(arg)275276 result = runner.invoke(cmd, ["a", "b", "c", "d", "e", "f"])284 assert result.output.splitlines() == [285 "(u'a', u'b', u'c')" if PY2 else "('a', 'b', 'c')",286 "d",287 "(u'e', u'f')" if PY2 else "('e', 'f')",288 ]277 assert result.output.splitlines() == ["('a', 'b', 'c')", "d", "('e', 'f')"]278279280def test_defaults_for_nargs(runner):281 @click.command()
23 unmodified lines
modified:tests/test_options.py+3 added-4 removed
3 unmodified lines
45import pytest67import click8from click._compat import text_type8910def test_prefixes(runner):11 @click.command()
156 unmodified lines
168 @click.command()169 @click.option("--arg1", multiple=True, default=("foo", "bar"))170 @click.option("--arg2", multiple=True, default=(1, "a"))171 def cmd(arg1, arg2):173 assert all(isinstance(e[0], text_type) for e in arg1)174 assert all(isinstance(e[1], text_type) for e in arg1)172 assert all(isinstance(e[0], str) for e in arg1)173 assert all(isinstance(e[1], str) for e in arg1)174175 assert all(isinstance(e[0], int) for e in arg2)177 assert all(isinstance(e[1], text_type) for e in arg2)176 assert all(isinstance(e[1], str) for e in arg2)177178 result = runner.invoke(179 cmd, "--arg1 a b --arg1 test 1 --arg2 2 two --arg2 4 four".split()180 )
377 unmodified lines
modified:tests/test_testing.py+3 added-9 removed
1import os2import sys3from io import BytesIO45import pytest67import click7from click._compat import PY28from click._compat import WIN9from click.testing import CliRunner1011# Use the most reasonable io that users would use for the python version.12if PY2:13 from cStringIO import StringIO as ReasonableBytesIO14else:15 from io import BytesIO as ReasonableBytesIO111712def test_runner():13 @click.command()14 def test():15 i = click.get_binary_stream("stdin")
28 unmodified lines
44 o.write(chunk)45 o.flush()4647 runner = CliRunner()54 result = runner.invoke(test, input=ReasonableBytesIO(b"Hello World!\n"))48 result = runner.invoke(test, input=BytesIO(b"Hello World!\n"))49 assert not result.exception50 assert result.output == "Hello World!\n"5152 runner = CliRunner(echo_stdin=True)59 result = runner.invoke(test, input=ReasonableBytesIO(b"Hello World!\n"))53 result = runner.invoke(test, input=BytesIO(b"Hello World!\n"))54 assert not result.exception55 assert result.output == "Hello World!\nHello World!\n"5657
240 unmodified lines