Merge branch '7.x'
Before adoption: this commit came in with the history the project adopted, so no landing records it.
# Conflicts: # CHANGES.rst
authored by David Lord · committed by David Lord · parents cd35e79, 93d947c · Browse files · 22 files·+595 added−199 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
22 files+595 added−199 removed
- tests:+219 added−39 removed
- other:+376 added−160 removed
Provenance
- Commit
2269786- Tree
1c07a01- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent 1
cd35e79- Parent 2
93d947c
22 files changed+595 added−199 removed
added:.github/ISSUE_TEMPLATE.md+33 added
123456789101112131415161718192021222324252627282930313233**This issue tracker is a tool to address bugs in Click itself.Please use the #pocoo IRC channel on freenode, the Discord server or Stack Overflow for general questions about using Flask or issuesnot related to Click.**
If you'd like to report a bug in Click, fill out the template below. Provideany extra information that may be useful / related to your problem.Ideally, create an [MCVE](https://stackoverflow.com/help/mcve), which helps usunderstand the problem and helps check that it is not caused by something inyour code.
---
### Expected Behavior
Tell us what should happen.
```pythonPaste a minimal example that causes the problem.```
### Actual Behavior
Tell us what happens instead.
```pytbPaste the full traceback if there was an exception.```
### Environment
* Python version:* Click version:modified:click/_compat.py+133 added-78 removed
14 unmodified lines15 WIN = sys.platform.startswith('win') and not APP_ENGINE and not MSYS216 DEFAULT_COLUMNS = 8017 18 19-_ansi_re = re.compile(r'\033\[((?:\d|;)*)([a-zA-Z])')19+_ansi_re = re.compile(r"\033\[[;?0-9]*[a-zA-Z]")20 21 22 def get_filesystem_encoding():23 return sys.getfilesystemencoding() or sys.getdefaultencoding()303 unmodified lines327 # environments. It's not quite clear what the correct behavior is328 # but this at least will force Click to recover somehow.329 return is_ascii_encoding(getattr(stream, 'encoding', None) or 'ascii')330 331+ def _is_compat_stream_attr(stream, attr, value):332+ """A stream attribute is compatible if it is equal to the333+ desired value or the desired value is unset and the attribute334+ has a value.335+ """336+ stream_value = getattr(stream, attr, None)337+ return stream_value == value or (value is None and stream_value is not None)338+339 def _is_compatible_text_stream(stream, encoding, errors):332- stream_encoding = getattr(stream, 'encoding', None)333- stream_errors = getattr(stream, 'errors', None)340+ """Check if a stream's encoding and errors attributes are341+ compatible with the desired values.342+ """343+ return (344+ _is_compat_stream_attr(stream, "encoding", encoding)345+ and _is_compat_stream_attr(stream, "errors", errors)346+ )347 335- # Perfect match.336- if stream_encoding == encoding and stream_errors == errors:337- return True338-339- # Otherwise, it's only a compatible stream if we did not ask for340- # an encoding.341- if encoding is None:342- return stream_encoding is not None343-344- return False345-346- def _force_correct_text_reader(text_reader, encoding, errors,347- force_readable=False):348- if _is_binary_reader(text_reader, False):349- binary_reader = text_reader348+ def _force_correct_text_stream(349+ text_stream,350+ encoding,351+ errors,352+ is_binary,353+ find_binary,354+ force_readable=False,355+ force_writable=False,356+ ):357+ if is_binary(text_stream, False):358+ binary_reader = text_stream359 else:351- # If there is no target encoding set, we need to verify that the352- # reader is not actually misconfigured.353- if encoding is None and not _stream_is_misconfigured(text_reader):354- return text_reader360+ # If the stream looks compatible, and won't default to a361+ # misconfigured ascii encoding, return it as-is.362+ if (363+ _is_compatible_text_stream(text_stream, encoding, errors)364+ and not (365+ encoding is None366+ and _stream_is_misconfigured(text_stream)367+ )368+ ):369+ return text_stream370 356- if _is_compatible_text_stream(text_reader, encoding, errors):357- return text_reader371+ # Otherwise, get the underlying binary reader.372+ binary_reader = find_binary(text_stream)373 359- # If the reader has no encoding, we try to find the underlying360- # binary reader for it. If that fails because the environment is361- # misconfigured, we silently go with the same reader because this362- # is too common to happen. In that case, mojibake is better than363- # exceptions.364- binary_reader = _find_binary_reader(text_reader)374+ # If that's not possible, silently use the original reader375+ # and get mojibake instead of exceptions.376 if binary_reader is None:366- return text_reader377+ return text_stream378 368- # At this point, we default the errors to replace instead of strict369- # because nobody handles those errors anyways and at this point370- # we're so fundamentally fucked that nothing can repair it.379+ # Default errors to replace instead of strict in order to get380+ # something that works.381 if errors is None:372- errors = 'replace'373- return _make_text_stream(binary_reader, encoding, errors,374- force_readable=force_readable)382+ errors = "replace"383 376- def _force_correct_text_writer(text_writer, encoding, errors,377- force_writable=False):378- if _is_binary_writer(text_writer, False):379- binary_writer = text_writer380- else:381- # If there is no target encoding set, we need to verify that the382- # writer is not actually misconfigured.383- if encoding is None and not _stream_is_misconfigured(text_writer):384- return text_writer384+ # Wrap the binary stream in a text stream with the correct385+ # encoding parameters.386+ return _make_text_stream(387+ binary_reader,388+ encoding,389+ errors,390+ force_readable=force_readable,391+ force_writable=force_writable,392+ )393 386- if _is_compatible_text_stream(text_writer, encoding, errors):387- return text_writer394+ def _force_correct_text_reader(text_reader, encoding, errors, force_readable=False):395+ return _force_correct_text_stream(396+ text_reader,397+ encoding,398+ errors,399+ _is_binary_reader,400+ _find_binary_reader,401+ force_readable=force_readable,402+ )403 389- # If the writer has no encoding, we try to find the underlying390- # binary writer for it. If that fails because the environment is391- # misconfigured, we silently go with the same writer because this392- # is too common to happen. In that case, mojibake is better than393- # exceptions.394- binary_writer = _find_binary_writer(text_writer)395- if binary_writer is None:396- return text_writer404+ def _force_correct_text_writer(text_writer, encoding, errors, force_writable=False):405+ return _force_correct_text_stream(406+ text_writer,407+ encoding,408+ errors,409+ _is_binary_writer,410+ _find_binary_writer,411+ force_writable=force_writable,412+ )413 398- # At this point, we default the errors to replace instead of strict399- # because nobody handles those errors anyways and at this point400- # we're so fundamentally fucked that nothing can repair it.401- if errors is None:402- errors = 'replace'403- return _make_text_stream(binary_writer, encoding, errors,404- force_writable=force_writable)405-414 def get_binary_stdin():415 reader = _find_binary_reader(sys.stdin)416 if reader is None:417 raise RuntimeError('Was not able to determine binary '56 unmodified lines474 msg = msg.decode('utf-8', 'replace')475 return msg476 477 470-def open_stream(filename, mode='r', encoding=None, errors='strict',471- atomic=False):478+def _wrap_io_open(file, mode, encoding, errors):479+ """On Python 2, :func:`io.open` returns a text file wrapper that480+ requires passing ``unicode`` to ``write``. Need to open the file in481+ binary mode then wrap it in a subclass that can write ``str`` and482+ ``unicode``.483+484+ Also handles not passing ``encoding`` and ``errors`` in binary mode.485+ """486+ binary = "b" in mode487+488+ if binary:489+ kwargs = {}490+ else:491+ kwargs = {"encoding": encoding, "errors": errors}492+493+ if not PY2 or binary:494+ return io.open(file, mode, **kwargs)495+496+ f = io.open(file, "b" + mode.replace("t", ""))497+ return _make_text_stream(f, **kwargs)498+499+500+def open_stream(filename, mode='r', encoding=None, errors='strict', atomic=False):501+ binary = "b" in mode502+503 # Standard streams first. These are simple because they don't need504 # special handling for the atomic flag. It's entirely ignored.505 if filename == '-':506 if any(m in mode for m in ['w', 'a', 'x']):476- if 'b' in mode:507+ if binary:508 return get_binary_stdout(), False509 return get_text_stdout(encoding=encoding, errors=errors), False479- if 'b' in mode:510+ if binary:511 return get_binary_stdin(), False512 return get_text_stdin(encoding=encoding, errors=errors), False513 514 # Non-atomic writes directly go out through the regular open functions.515 if not atomic:485- if encoding is None:486- return open(filename, mode), True487- return io.open(filename, mode, encoding=encoding, errors=errors), True516+ return _wrap_io_open(filename, mode, encoding, errors), True517 518 # Some usability stuff for atomic writes519 if 'a' in mode:520 raise ValueError(10 unmodified lines531 # Atomic writes are more complicated. They work by opening a file532 # as a proxy in the same folder and then using the fdopen533 # functionality to wrap it in a Python file. Then we wrap it in an534 # atomic file that moves the file over on close.506- import tempfile507- fd, tmp_filename = tempfile.mkstemp(dir=os.path.dirname(filename),508- prefix='.__atomic-write')535+ import errno536+ import random537 510- if encoding is not None:511- f = io.open(fd, mode, encoding=encoding, errors=errors)512- else:513- f = os.fdopen(fd, mode)538+ try:539+ perm = os.stat(filename).st_mode540+ except OSError:541+ perm = None542 543+ flags = os.O_RDWR | os.O_CREAT | os.O_EXCL544+545+ if binary:546+ flags |= getattr(os, 'O_BINARY', 0)547+548+ while True:549+ tmp_filename = os.path.join(550+ os.path.dirname(filename),551+ '.__atomic-write%08x' % (random.randrange(1 << 32),),552+ )553+ try:554+ fd = os.open(tmp_filename, flags, 0o666 if perm is None else perm)555+ break556+ except OSError as e:557+ if e.errno == errno.EEXIST or (558+ os.name == "nt"559+ and e.errno == errno.EACCES560+ and os.path.isdir(e.filename)561+ and os.access(e.filename, os.W_OK)562+ ):563+ continue564+ raise565+566+ if perm is not None:567+ os.chmod(tmp_filename, perm) # in case perm includes bits in umask568+569+ f = _wrap_io_open(fd, mode, encoding, errors)570 return _AtomicFile(f, tmp_filename, os.path.realpath(filename)), True571 572 573 # Used in a destructor call, needs extra protection from interpreter cleanup.196 unmodified linesmodified:click/_termui_impl.py+21 added-4 removed
106 unmodified lines107 raise RuntimeError('You need to use progress bars in a with block.')108 self.render_progress()109 return self.generator()110 111+ def __next__(self):112+ # Iteration is defined in terms of a generator function,113+ # returned by iter(self); use that to define next(). This works114+ # because `self.iter` is an iterable consumed by that generator,115+ # so it is re-entry safe. Calling `next(self.generator())`116+ # twice works and does "what you want".117+ return next(iter(self))118+119+ # Python 2 compat120+ next = __next__121+122 def is_fast(self):123 return time.time() - self.start <= self.short_limit124 125 def render_finish(self):167 unmodified lines293 self.current_item = None294 self.finished = True295 296 def generator(self):297+ """Return a generator which yields the items added to the bar298+ during construction, and updates the progress bar *after* the299+ yielded block returns.300 """287- Returns a generator which yields the items added to the bar during288- construction, and updates the progress bar *after* the yielded block289- returns.290- """301+ # WARNING: the iterator interface for `ProgressBar` relies on302+ # this and only works because this is a simple generator which303+ # doesn't create or manage additional state. If this function304+ # changes, the impact should be evaluated both against305+ # `iter(bar)` and `next(bar)`. `next()` in particular may call306+ # `self.generator()` repeatedly, and this must remain safe in307+ # order for that interface to work.308 if not self.entered:309 raise RuntimeError('You need to use progress bars in a with block.')310 311 if self.is_hidden:346 unmodified linesmodified:click/_winconsole.py+16 added-2 removed
22 unmodified lines23 PyObject_GetBuffer = pythonapi.PyObject_GetBuffer24 PyBuffer_Release = pythonapi.PyBuffer_Release25 except ImportError:26 pythonapi = None27-from ctypes.wintypes import LPWSTR, LPCWSTR, HANDLE27+from ctypes.wintypes import DWORD, LPWSTR, LPCWSTR, HANDLE28 29 30 c_ssize_p = POINTER(c_ssize_t)31 32 kernel32 = windll.kernel3233 GetStdHandle = kernel32.GetStdHandle34 ReadConsoleW = kernel32.ReadConsoleW35 WriteConsoleW = kernel32.WriteConsoleW36+GetConsoleMode = kernel32.GetConsoleMode37 GetLastError = kernel32.GetLastError38 GetCommandLineW = WINFUNCTYPE(LPWSTR)(39 ('GetCommandLineW', windll.kernel32))40 CommandLineToArgvW = WINFUNCTYPE(246 unmodified lines287 2: _get_text_stderr,288 }289 290 291+def _is_console(f):292+ if not hasattr(f, 'fileno'):293+ return False294+295+ try:296+ fileno = f.fileno()297+ except OSError:298+ return False299+300+ handle = msvcrt.get_osfhandle(fileno)301+ return bool(GetConsoleMode(handle, byref(DWORD())))302+303+304 def _get_windows_console_stream(f, encoding, errors):305 if get_buffer is not None and \306 encoding in ('utf-16-le', None) \307 and errors in ('strict', None) and \294- hasattr(f, 'isatty') and f.isatty():308+ _is_console(f):309 func = _stream_factories.get(f.fileno())310 if func is not None:311 if not PY2:312 f = getattr(f, 'buffer', None)9 unmodified linesmodified:click/core.py+21 added-10 removed
181 unmodified lines182 .. versionadded:: 4.0183 Added the `color`, `ignore_unknown_options`, and184 `max_content_width` parameters.185 186+ .. versionadded:: 7.1187+ Added the `show_default` parameter.188+189 :param command: the command class for this context.190 :param parent: the parent context.191 :param info_name: the info name for this invocation. Generally this192 is the most descriptive name for the script or813 unmodified lines1006 opts = []1007 for param in self.get_params(ctx):1008 rv = param.get_help_record(ctx)1009 if rv is not None:1007- opts.append(rv)1010+ part_a, part_b = rv1011+ opts.append((part_a, part_b.replace('\n', ' ')))1012 1013 if opts:1014 with formatter.section('Options'):1015 formatter.write_dl(opts)371 unmodified lines1387 intentionally not finalized.1388 1389 Some settings are supported by both options and arguments.1390 1387- .. versionchanged:: 2.01388- Changed signature for parameter callback to also be passed the1389- parameter. In Click 2.0, the old callback format will still work,1390- but it will raise a warning to give you change to migrate the1391- code easier.1392-1391 :param param_decls: the parameter declarations for this option or1392 argument. This is a list of flags or argument1393 names.1394 :param type: the type that should be used. Either a :class:`ParamType`20 unmodified lines1415 should not be set for arguments or it will inverse the1416 order of processing.1417 :param envvar: a string or list of strings that are environment variables1418 that should be checked.1419+1420+ .. versionchanged:: 7.11421+ Empty environment variables are ignored rather than taking the1422+ empty string value. This makes it possible for scripts to clear1423+ variables if they can't unset them.1424+1425+ .. versionchanged:: 2.01426+ Changed signature for parameter callback to also be passed the1427+ parameter. The old callback format will still work, but it will1428+ raise a warning to give you a chance to migrate the code easier.1429 """1430 param_type_name = 'parameter'1431 1432 def __init__(self, param_decls=None, type=None, required=False,126 unmodified lines1559 rv = os.environ.get(envvar)1560 if rv is not None:1561 return rv1562 else:1555- return os.environ.get(self.envvar)1563+ rv = os.environ.get(self.envvar)1564 1565+ if rv != "":1566+ return rv1567+1568 def value_from_envvar(self, ctx):1569 rv = self.resolve_envvar_value(ctx)1570 if rv is not None and self.nargs != 1:1571 rv = self.type.split_envvar_value(rv)106 unmodified lines1678 flag_value = not self.default1679 self.is_flag = is_flag1680 self.flag_value = flag_value1681 if self.is_flag and isinstance(self.flag_value, bool) \1671- and type is None:1682+ and type in [None, bool]:1683 self.type = BOOL1684 self.is_bool_flag = True1685 else:1686 self.is_bool_flag = False155 unmodified lines1842 1843 return ((any_prefix_is_slash and '; ' or ' / ').join(rv), help)1844 1845 def get_default(self, ctx):1835- # If we're a non boolean flag out default is more complex because1846+ # If we're a non boolean flag our default is more complex because1847 # we need to look at all flags in the same group to figure out1848 # if we're the the default one in which case we return the flag1849 # value as default.1850 if self.is_flag and not self.is_bool_flag:116 unmodified linesmodified:click/decorators.py+3 added-3 removed
92 unmodified lines93 r"""Creates a new :class:`Command` and uses the decorated function as94 callback. This will also automatically attach all decorated95 :func:`option`\s and :func:`argument`\s as parameters to the command.96 97- The name of the command defaults to the name of the function. If you98- want to change that, you can pass the intended name as the first99- argument.97+ The name of the command defaults to the name of the function with98+ underscores replaced by dashes. If you want to change that, you can99+ pass the intended name as the first argument.100 101 All keyword arguments are forwarded to the underlying command class.102 103 Once decorated the function turns into a :class:`Command` instance208 unmodified linesmodified:click/exceptions.py+13 added
150 unmodified lines151 msg and '. ' or '.',152 msg or '',153 )154 155+ def __str__(self):156+ if self.message is None:157+ param_name = self.param.name if self.param else None158+ return "missing parameter: {}".format(param_name)159+ else:160+ return self.message161 162+ if PY2:163+ __unicode__ = __str__164+165+ def __str__(self):166+ return self.__unicode__().encode("utf-8")167+168+169 class NoSuchOption(UsageError):170 """Raised if click attempted to handle an option that does not171 exist.172 76 unmodified linesmodified:click/termui.py+11 added-2 removed
1+import io2 import os3 import sys4 import struct5 import inspect6 import itertools7 8 from ._compat import raw_input, text_type, string_types, \8- isatty, strip_ansi, get_winterm_size, DEFAULT_COLUMNS, WIN9+ isatty, strip_ansi, get_winterm_size, DEFAULT_COLUMNS, WIN10 from .utils import echo11 from .exceptions import Abort, UsageError12 from .types import convert_type, Choice, Path13 from .globals import resolve_color_default14+from .utils import LazyFile15 16 17 # The prompt functions to use. The doc tools currently override these18 # functions to customize how they work.30 unmodified lines49 prompt = text50 if type is not None and show_choices and isinstance(type, Choice):51 prompt += ' (' + ", ".join(map(str, type.choices)) + ')'52 if default is not None and show_default:51- prompt = '%s [%s]' % (prompt, default)53+ prompt = '%s [%s]' % (prompt, _format_default(default))54 return prompt + suffix55 56 57+def _format_default(default):58+ if isinstance(default, (io.IOBase, LazyFile)) and hasattr(default, "name"):59+ return default.name60+61+ return default62+63+64 def prompt(text, default=None, hide_input=False, confirmation_prompt=False,65 type=None, value_proc=None, prompt_suffix=': ', show_default=True,66 err=False, show_choices=True):67 """Prompts a user for input. This is a convenience function that can568 unmodified linesmodified:click/testing.py+7 added-4 removed
77 unmodified lines78 #: The runner that created the result79 self.runner = runner80 #: The standard output as bytes.81 self.stdout_bytes = stdout_bytes82- #: The standard error as bytes, or False(y) if not available82+ #: The standard error as bytes, or None if not available83 self.stderr_bytes = stderr_bytes84 #: The exit code as integer.85 self.exit_code = exit_code86 #: The exception that happened if one did.14 unmodified lines101 102 @property103 def stderr(self):104 """The standard error as unicode string."""105- if not self.stderr_bytes:105+ if self.stderr_bytes is None:106 raise ValueError("stderr not separately captured")107 return self.stderr_bytes.decode(self.runner.charset, 'replace') \108 .replace('\r\n', '\n')109 167 unmodified lines277 clickpkg.utils.should_strip_ansi = old_should_strip_ansi278 clickpkg.formatting.FORCED_WIDTH = old_forced_width279 280 def invoke(self, cli, args=None, input=None, env=None,281- catch_exceptions=True, color=False, mix_stderr=False, **extra):281+ catch_exceptions=True, color=False, **extra):282 """Invokes a command in an isolated environment. The arguments are283 forwarded directly to the command line script, the `extra` keyword284 arguments are passed to the :meth:`~clickpkg.Command.main` function of285 the command.60 unmodified lines346 exc_info = sys.exc_info()347 finally:348 sys.stdout.flush()349 stdout = outstreams[0].getvalue()350+ if self.mix_stderr:351+ stderr = None352+ else:350- stderr = outstreams[1] and outstreams[1].getvalue()353+ stderr = outstreams[1].getvalue()354 355 return Result(runner=self,356 stdout_bytes=stdout,357 stderr_bytes=stderr,20 unmodified linesmodified:docs/commands.rst+15 added-6 removed
86 unmodified lines87 @click.option('--debug/--no-debug', default=False)88 @click.pass_context89 def cli(ctx, debug):90 # ensure that ctx.obj exists and is a dict (in case `cli()` is called91- # by means other than the `if` block below91+ # by means other than the `if` block below)92 ctx.ensure_object(dict)93 94 ctx.obj['DEBUG'] = debug95 220 unmodified lines316 When using multi command chaining you can only have one command (the last)317 use ``nargs=-1`` on an argument. It is also not possible to nest multi318 commands below chained multicommands. Other than that there are no319 restrictions on how they work. They can accept options and arguments as320-normal.320+normal. The order between options and arguments is limited for chained321+commands. Currently only ``--options argument`` order is allowed.322 323 Another note: the :attr:`Context.invoked_subcommand` attribute is a bit324 useless for multi commands as it will give ``'*'`` as value if more than325 one command is invoked. This is necessary because the handling of113 unmodified lines439 440 This is useful if you plug in some commands from another package but441 you're not satisfied with the defaults.442 442-The default map can be nested arbitrarily for each subcommand and443-provided when the script is invoked. Alternatively, it can also be444-overridden at any point by commands. For instance, a top-level command could445-load the defaults from a configuration file.443+The default map can be nested arbitrarily for each subcommand:444 445+.. code-block:: python446+447+ default_map = {448+ "debug": True, # default for a top level option449+ "runserver": {"port": 5000} # default for a subcommand450+ }451+452+The default map can be provided when the script is invoked, or453+overridden at any point by commands. For instance, a top-level command454+could load the defaults from a configuration file.455+456 Example usage:457 458 .. click:example::459 112 unmodified linesmodified:docs/options.rst+21 added-6 removed
147 unmodified lines148 Multiple Options149 ----------------150 151 Similarly to ``nargs``, there is also the case of wanting to support a152-parameter being provided multiple times to and have all values recorded --152+parameter being provided multiple times and have all the values recorded --153 not just the last one. For instance, ``git commit -m foo -m bar`` would154 record two lines for the commit message: ``foo`` and ``bar``. This can be155 accomplished with the ``multiple`` flag:156 11 unmodified lines168 .. click:run::169 170 invoke(commit, args=['-m', 'foo', '-m', 'bar'])171 172+When passing a ``default`` with ``multiple=True``, the default value173+must be a list or tuple, otherwise it will be interpreted as a list of174+single characters.175+176+.. code-block:: python177+178+ @click.option("--format", multiple=True, default=["json"])179+180+181 Counting182 --------183 184 In some very rare circumstances, it is interesting to use the repetition164 unmodified lines349 invoke(digest, args=['--hash-type=foo'])350 println()351 invoke(digest, args=['--help'])352 344-.. note::353+Only pass the choices as list or tuple. Other iterables (like354+generators) may lead to unexpected results.355 346- You should only pass the choices as list or tuple. Other iterables (like347- generators) may lead to surprising results.356+Choices work with options that have ``multiple=True``. If a ``default``357+value is given with ``multiple=True``, it should be a list or tuple of358+valid choices.359 349- Choices should be unique after considering the effects of350- ``case_sensitive`` and any specified token normalization function.360+Choices should be unique after considering the effects of361+``case_sensitive`` and any specified token normalization function.362 363 .. versionchanged:: 7.1364 The resulting value from an option will always be on the of the365 originally passed choices regardless of ``case_sensitive``.38 unmodified lines404 .. click:run::405 406 invoke(hello, input=['John'])407 408+It is advised that prompt not be used in conjunction with the multiple409+flag set to True. Instead, prompt in the function interactively.410+411+412 Password Prompts413 ----------------414 415 Click also supports hidden prompts and asking for confirmation. This is408 unmodified linesmodified:docs/python3.rst+6 added
118 unmodified lines119 configured to use ASCII as encoding for the environment. Either switch120 to Python 2 or consult the Python 3 section of the docs for121 mitigation steps.122 123+.. note::124+125+ In Python 3.7 and later you will no longer get a ``RuntimeError`` in126+ many cases thanks to :pep:`538` and :pep:`540`, which changed the127+ default assumption in unconfigured environments.128+129 You are dealing with an environment where Python 3 thinks you are130 restricted to ASCII data. The solution to these problems is different131 depending on which locale your computer is running in.132 59 unmodified linesmodified:docs/quickstart.rst+1 added-1 removed
32 unmodified lines33 works.34 35 If you are on Mac OS X or Linux::36 37- $ sudo pip install virtualenv37+ $ pip install virtualenv --user38 39 One of these will probably install virtualenv on your system. Maybe it's even40 in your package manager. If you use Ubuntu, try::41 236 unmodified linesmodified:docs/testing.rst+3 added-3 removed
80 unmodified lines81 82 File System Isolation83 ---------------------84 85-For basic command line tools that want to operate with the file system, the86-:meth:`CliRunner.isolated_filesystem` method comes in useful which sets up87-an empty folder and changes the current working directory to:85+For basic command line tools with file system operations, the86+:meth:`CliRunner.isolated_filesystem` method is useful for setting the87+current working directory to a new, empty folder.88 89 .. code-block:: python90 :caption: cat.py91 54 unmodified linesmodified:docs/utils.rst+10 added
387 unmodified lines388 length=number_of_users) as bar:389 for user in bar:390 modify_the_user(user)391 392+Note that :func:`progressbar` updates the bar *after* each iteration of the393+loop. So code like this will render correctly::394+395+ import time396+397+ with click.progressbar([1, 2, 3]) as bar:398+ for x in bar:399+ print('sleep({})...'.format(x))400+ time.sleep(x)401+402 Another useful feature is to associate a label with the progress bar which403 will be shown preceding the progress bar::404 405 with click.progressbar(all_the_users_to_process,15 unmodified linesmodified:docs/why.rst+31 added-36 removed
8 unmodified lines9 10 * is lazily composable without restrictions11 * supports implementation of Unix/POSIX command line conventions12 * supports loading values from environment variables out of the box13-* supports for prompting of custom values13+* support for prompting of custom values14 * is fully nestable and composable15 * works the same in Python 2 and 316 * supports file handling out of the box17 * comes with useful common helpers (getting terminal dimensions,18 ANSI colors, fetching direct keyboard input, screen clearing,19 finding config paths, launching apps and editors, etc.)20 21-There are many alternatives to Click and you can have a look at them if22-you enjoy them better. The obvious ones are ``optparse`` and ``argparse``23-from the standard library.21+There are many alternatives to Click; the obvious ones are ``optparse``22+and ``argparse`` from the standard library. Have a look to see if something23+else resonates with you.24 25 Click actually implements its own parsing of arguments and does not use26 ``optparse`` or ``argparse`` following the ``optparse`` parsing behavior.27 The reason it's not based on ``argparse`` is that ``argparse`` does not28 allow proper nesting of commands by design and has some deficiencies when29 it comes to POSIX compliant argument handling.30 31-Click is designed to be fun to work with and at the same time not stand in32-your way. It's not overly flexible either. Currently, for instance, it33-does not allow you to customize the help pages too much. This is intentional34-because Click is designed to allow you to nest command line utilities. The35-idea is that you can have a system that works together with another system by36-tacking two Click instances together and they will continue working as they37-should.31+Click is designed to be fun and customizable but not overly flexible.32+For instance, the customizability of help pages is constrained. This33+constraint is intentional because Click promises multiple Click instances34+will continue to function as intended when strung together.35 36 Too much customizability would break this promise.37 38 Click was written to support the `Flask <https://palletsprojects.com/p/flask/>`_39 microframework ecosystem because no tool could provide it with the40 functionality it needed.41 42 To get an understanding of what Click is all about, I strongly recommend46-looking at the :ref:`complex-guide` chapter to see what it's useful for.43+looking at the :ref:`complex-guide` chapter.44 45 Why not Argparse?46 -----------------47 51-Click is internally based on optparse instead of argparse. This however48+Click is internally based on ``optparse`` instead of ``argparse``. This49 is an implementation detail that a user does not have to be concerned53-with. The reason however Click is not using argparse is that it has some54-problematic behaviors that make handling arbitrary command line interfaces55-hard:50+with. Click is not based on argparse because it has some behaviors that51+make handling arbitrary command line interfaces hard:52 57-* argparse has built-in magic behavior to guess if something is an58- argument or an option. This becomes a problem when dealing with59- incomplete command lines as it's not possible to know without having a60- full understanding of the command line how the parser is going to61- behave. This goes against Click's ambitions of dispatching to62- subparsers.63-* argparse currently does not support disabling of interspersed64- arguments. Without this feature it's not possible to safely implement65- Click's nested parsing nature.53+* argparse has built-in behavior to guess if something is an54+ argument or an option. This becomes a problem when dealing with55+ incomplete command lines; the behaviour becomes unpredictable56+ without full knowledge of a command line. This goes against Click's57+ ambitions of dispatching to subparsers.58+* argparse does not support disabling interspersed arguments. Without59+ this feature, it's not possible to safely implement Click's nested60+ parsing.61 62 Why not Docopt etc.?63 --------------------64 70-Docopt and many tools like it are cool in how they work, but very few of65+Docopt, and many tools like it, are cool in how they work, but very few of66 these tools deal with nesting of commands and composability in a way like67 Click. To the best of the developer's knowledge, Click is the first68 Python library that aims to create a level of composability of applications69 that goes beyond what the system itself supports.2 unmodified lines72 according to those rules. The side effect of this is that docopt is quite73 rigid in how it handles the command line interface. The upside of docopt74 is that it gives you strong control over your help page; the downside is75 that due to this it cannot rewrap your output for the current terminal81-width and it makes translations hard. On top of that docopt is restricted76+width, and it makes translations hard. On top of that, docopt is restricted77 to basic parsing. It does not handle argument dispatching and callback78 invocation or types. This means there is a lot of code that needs to be79 written in addition to the basic help page to handle the parsing results.80 81 Most of all, however, it makes composability hard. While docopt does87-support dispatching to subcommands, it for instance does not directly82+support dispatching to subcommands, it, for instance, does not directly83 support any kind of automatic subcommand enumeration based on what's84 available or it does not enforce subcommands to work in a consistent way.85 86 This is fine, but it's different from how Click wants to work. Click aims2 unmodified lines89 90 - Click does not just parse, it also dispatches to the appropriate code.91 - Click has a strong concept of an invocation context that allows92 subcommands to respond to data from the parent command.98-- Click has strong information available for all parameters and commands99- so that it can generate unified help pages for the full CLI and to93+- Click has strong information available for all parameters and commands,94+ so it can generate unified help pages for the full CLI and95 assist the user in converting the input data as necessary.101-- Click has a strong understanding of what types are and can give the user96+- Click has a strong understanding of what types are, and it can give the user97 consistent error messages if something goes wrong. A subcommand98 written by a different developer will not suddenly die with a99 different error message because it's manually handled.100 - Click has enough meta information available for its whole program106- that it can evolve over time to improve the user experience without101+ to evolve over time and improve the user experience without102 forcing developers to adjust their programs. For instance, if Click103 decides to change how help pages are formatted, all Click programs104 will automatically benefit from this.105 111-The aim of Click is to make composable systems, whereas the aim of docopt106+The aim of Click is to make composable systems. Whereas, the aim of docopt107 is to build the most beautiful and hand-crafted command line interfaces.108 These two goals conflict with one another in subtle ways. Click109 actively prevents people from implementing certain patterns in order to115-achieve unified command line interfaces. You have very little input on116-reformatting your help pages for instance.110+achieve unified command line interfaces. For instance, as a developer, you111+are given very little choice in formatting your help pages.112 113 114 Why Hardcoded Behaviors?115 ------------------------22 unmodified lines138 even optparse and argparse support automatic expansion of long arguments.139 The reason for this is that it's a liability for backwards compatibility.140 If people start relying on automatically modified parameters and someone141 adds a new parameter in the future, the script might stop working. These147-kinds of problems are hard to find so Click does not attempt to be magical142+kinds of problems are hard to find, so Click does not attempt to be magical143 about this.144 145 This sort of behavior however can be implemented on a higher level to146 support things such as explicit aliases. For more information see1 unmodified linemodified:tests/test_arguments.py+9 added
201 unmodified lines202 assert result.exit_code == 2203 assert 'Missing argument "ARG".' in result.output204 205 206+def test_missing_argument_string_cast():207+ ctx = click.Context(click.Command(""))208+209+ with pytest.raises(click.MissingParameter) as excinfo:210+ click.Argument(["a"], required=True).full_process_value(ctx, None)211+212+ assert str(excinfo.value) == "missing parameter: a"213+214+215 def test_implicit_non_required(runner):216 @click.command()217 @click.argument('f', default='test')218 def cli(f):89 unmodified linesmodified:tests/test_options.py+31 added-3 removed
111 unmodified lines112 assert result.exception113 assert 'Error: Missing option "-m" / "--message".' in result.output114 115 116+def test_empty_envvar(runner):117+ @click.command()118+ @click.option('--mypath', type=click.Path(exists=True), envvar='MYPATH')119+ def cli(mypath):120+ click.echo('mypath: %s' % mypath)121+122+ result = runner.invoke(cli, [], env={'MYPATH': ''})123+ assert result.exit_code == 0124+ assert result.output == 'mypath: None\n'125+126+127 def test_multiple_envvar(runner):128 @click.command()129 @click.option('--arg', multiple=True)130 def cmd(arg):189 unmodified lines320 result = runner.invoke(cmd, ['-whatever=23'])321 assert result.output == '23\n'322 323 324+def test_missing_option_string_cast():325+ ctx = click.Context(click.Command(""))326+327+ with pytest.raises(click.MissingParameter) as excinfo:328+ click.Option(['-a'], required=True).full_process_value(ctx, None)329+330+ assert str(excinfo.value) == "missing parameter: a"331+332+333 def test_missing_choice(runner):334 @click.command()335 @click.option('--foo', type=click.Choice(['foo', 'bar']),336 required=True)69 unmodified lines406 407 result = runner.invoke(cmd, ['--help'])408 assert result.exit_code == 0409 out = result.output.splitlines()390- assert ' --foo TEXT hello' in out391- assert ' i am' in out392- assert ' multiline' in out410+ assert ' --foo TEXT hello i am multiline' in out411 412 def test_argument_custom_class(runner):413 class CustomArgument(click.Argument):414 def get_default(self, ctx):54 unmodified lines469 assert 'I am a help text' in result.output470 assert 'you wont see me' not in result.output471 472 473+def test_bool_flag_with_type(runner):474+ @click.command()475+ @click.option('--shout/--no-shout', default=False, type=bool)476+ def cmd(shout):477+ pass478+479+ result = runner.invoke(cmd)480+ assert not result.exception481+482+483 def test_aliases_for_flags(runner):484 @click.command()485 @click.option('--warnings/--no-warnings', ' /-W', default=True)486 def cli(warnings):46 unmodified linesmodified:tests/test_termui.py+38 added
183 unmodified lines184 else:185 assert False, 'Expected an exception because of abort-related inputs.'186 187 188+def test_progressbar_is_iterator(runner, monkeypatch):189+ fake_clock = FakeClock()190+191+ @click.command()192+ def cli():193+ with click.progressbar(range(10), label='test') as progress:194+ while True:195+ try:196+ next(progress)197+ fake_clock.advance_time()198+ except StopIteration:199+ break200+201+ monkeypatch.setattr(time, 'time', fake_clock.time)202+ monkeypatch.setattr(click._termui_impl, 'isatty', lambda _: True)203+204+ result = runner.invoke(cli, [])205+ assert result.exception is None206+207+208 def test_choices_list_in_prompt(runner, monkeypatch):209 @click.command()210 @click.option('-g', type=click.Choice(['none', 'day', 'week', 'month']),211 prompt=True)12 unmodified lines224 result = runner.invoke(cli_without_choices, [], input='none')225 assert '(none, day, week, month)' not in result.output226 227 228+@pytest.mark.parametrize(229+ "file_kwargs",230+ [231+ {"mode": "rt"},232+ {"mode": "rb"},233+ {"lazy": True},234+ ]235+)236+def test_file_prompt_default_format(runner, file_kwargs):237+ @click.command()238+ @click.option("-f", default=__file__, prompt="file", type=click.File(**file_kwargs))239+ def cli(f):240+ click.echo(f.name)241+242+ result = runner.invoke(cli)243+ assert result.output == "file [{0}]: \n{0}\n".format(__file__)244+245+246 def test_secho(runner):247 with runner.isolation() as outstreams:248 click.secho(None, nl=False)249 bytes = outstreams[0].getvalue()108 unmodified linesmodified:tests/test_testing.py+12 added
255 unmodified lines256 257 with pytest.raises(ValueError):258 result_mix.stderr259 260+ @click.command()261+ def cli_empty_stderr():262+ click.echo("stdout")263 264+ runner = CliRunner(mix_stderr=False)265+266+ result = runner.invoke(cli_empty_stderr)267+268+ assert result.output == 'stdout\n'269+ assert result.stdout == 'stdout\n'270+ assert result.stderr == ''271+272+273 @pytest.mark.parametrize('args, expected_output', [274 (None, 'bar\n'),275 ([], 'bar\n'),276 ('', 'bar\n'),25 unmodified linesmodified:tests/test_utils.py+129 added-36 removed
1 import os2+import stat3 import sys4 5 import pytest6 43 unmodified lines50 click.echo(u'hello', file=f)51 assert f.getvalue() == u'hello\n'52 53 53-def test_styling():54- examples = [55- ('x', dict(fg='black'), '\x1b[30mx\x1b[0m'),56- ('x', dict(fg='red'), '\x1b[31mx\x1b[0m'),57- ('x', dict(fg='green'), '\x1b[32mx\x1b[0m'),58- ('x', dict(fg='yellow'), '\x1b[33mx\x1b[0m'),59- ('x', dict(fg='blue'), '\x1b[34mx\x1b[0m'),60- ('x', dict(fg='magenta'), '\x1b[35mx\x1b[0m'),61- ('x', dict(fg='cyan'), '\x1b[36mx\x1b[0m'),62- ('x', dict(fg='white'), '\x1b[37mx\x1b[0m'),63- ('x', dict(bg='black'), '\x1b[40mx\x1b[0m'),64- ('x', dict(bg='red'), '\x1b[41mx\x1b[0m'),65- ('x', dict(bg='green'), '\x1b[42mx\x1b[0m'),66- ('x', dict(bg='yellow'), '\x1b[43mx\x1b[0m'),67- ('x', dict(bg='blue'), '\x1b[44mx\x1b[0m'),68- ('x', dict(bg='magenta'), '\x1b[45mx\x1b[0m'),69- ('x', dict(bg='cyan'), '\x1b[46mx\x1b[0m'),70- ('x', dict(bg='white'), '\x1b[47mx\x1b[0m'),71- ('foo bar', dict(blink=True), '\x1b[5mfoo bar\x1b[0m'),72- ('foo bar', dict(underline=True), '\x1b[4mfoo bar\x1b[0m'),73- ('foo bar', dict(bold=True), '\x1b[1mfoo bar\x1b[0m'),74- ('foo bar', dict(dim=True), '\x1b[2mfoo bar\x1b[0m'),54+@pytest.mark.parametrize(55+ ("styles", "ref"),56+ [57+ ({"fg": "black"}, "\x1b[30mx y\x1b[0m"),58+ ({"fg": "red"}, "\x1b[31mx y\x1b[0m"),59+ ({"fg": "green"}, "\x1b[32mx y\x1b[0m"),60+ ({"fg": "yellow"}, "\x1b[33mx y\x1b[0m"),61+ ({"fg": "blue"}, "\x1b[34mx y\x1b[0m"),62+ ({"fg": "magenta"}, "\x1b[35mx y\x1b[0m"),63+ ({"fg": "cyan"}, "\x1b[36mx y\x1b[0m"),64+ ({"fg": "white"}, "\x1b[37mx y\x1b[0m"),65+ ({"bg": "black"}, "\x1b[40mx y\x1b[0m"),66+ ({"bg": "red"}, "\x1b[41mx y\x1b[0m"),67+ ({"bg": "green"}, "\x1b[42mx y\x1b[0m"),68+ ({"bg": "yellow"}, "\x1b[43mx y\x1b[0m"),69+ ({"bg": "blue"}, "\x1b[44mx y\x1b[0m"),70+ ({"bg": "magenta"}, "\x1b[45mx y\x1b[0m"),71+ ({"bg": "cyan"}, "\x1b[46mx y\x1b[0m"),72+ ({"bg": "white"}, "\x1b[47mx y\x1b[0m"),73+ ({"blink": True}, "\x1b[5mx y\x1b[0m"),74+ ({"underline": True}, "\x1b[4mx y\x1b[0m"),75+ ({"bold": True}, "\x1b[1mx y\x1b[0m"),76+ ({"dim": True}, "\x1b[2mx y\x1b[0m"),77+ ],78+)79+def test_styling(styles, ref):80+ assert click.style("x y", **styles) == ref81+ assert click.unstyle(ref) == "x y"82+83+84+@pytest.mark.parametrize(85+ ("text", "expect"),86+ [87+ ("\x1b[?25lx y\x1b[?25h", "x y"),88 ]76- for text, styles, ref in examples:77- assert click.style(text, **styles) == ref78- assert click.unstyle(ref) == text89+)90+def test_unstyle_other_ansi(text, expect):91+ assert click.unstyle(text) == expect92 93 94+95 def test_filename_formatting():96 assert click.format_filename(b'foo.txt') == 'foo.txt'97 assert click.format_filename(b'/x/foo.txt') == '/x/foo.txt'98 assert click.format_filename(u'/x/foo.txt') == '/x/foo.txt'179 unmodified lines278 assert err == 'Pause to stderr\n'279 280 281 def test_open_file(runner):282+ @click.command()283+ @click.argument('filename')284+ def cli(filename):285+ with click.open_file(filename) as f:286+ click.echo(f.read())287+288+ click.echo('meep')289+290 with runner.isolated_filesystem():291 with open('hello.txt', 'w') as f:292 f.write('Cool stuff')293 272- @click.command()273- @click.argument('filename')274- def cli(filename):275- with click.open_file(filename) as f:276- click.echo(f.read())277- click.echo('meep')278-294 result = runner.invoke(cli, ['hello.txt'])295 assert result.exception is None296 assert result.output == 'Cool stuff\nmeep\n'297 1 unmodified line299 assert result.exception is None300 assert result.output == 'foobar\nmeep\n'301 302 288-@pytest.mark.xfail(WIN and not PY2, reason='God knows ...')303+def test_open_file_ignore_errors_stdin(runner):304+ @click.command()305+ @click.argument("filename")306+ def cli(filename):307+ with click.open_file(filename, errors="ignore") as f:308+ click.echo(f.read())309+310+ result = runner.invoke(cli, ["-"], input=os.urandom(16))311+ assert result.exception is None312+313+314+def test_open_file_respects_ignore(runner):315+ with runner.isolated_filesystem():316+ with open("test.txt", "w") as f:317+ f.write("Hello world!")318+319+ with click.open_file("test.txt", encoding="utf8", errors="ignore") as f:320+ assert f.errors == "ignore"321+322+323+def test_open_file_ignore_invalid_utf8(runner):324+ with runner.isolated_filesystem():325+ with open("test.txt", "wb") as f:326+ f.write(b"\xe2\x28\xa1")327+328+ with click.open_file("test.txt", encoding="utf8", errors="ignore") as f:329+ f.read()330+331+332+def test_open_file_ignore_no_encoding(runner):333+ with runner.isolated_filesystem():334+ with open("test.bin", "wb") as f:335+ f.write(os.urandom(16))336+337+ with click.open_file("test.bin", errors="ignore") as f:338+ f.read()339+340+341+@pytest.mark.skipif(WIN, reason='os.chmod() is not fully supported on Windows.')342+@pytest.mark.parametrize('permissions', [343+ 0o400,344+ 0o444,345+ 0o600,346+ 0o644,347+ ])348+def test_open_file_atomic_permissions_existing_file(runner, permissions):349+ with runner.isolated_filesystem():350+ with open('existing.txt', 'w') as f:351+ f.write('content')352+ os.chmod('existing.txt', permissions)353+354+ @click.command()355+ @click.argument('filename')356+ def cli(filename):357+ click.open_file(filename, 'w', atomic=True).close()358+359+ result = runner.invoke(cli, ['existing.txt'])360+ assert result.exception is None361+ assert stat.S_IMODE(os.stat('existing.txt').st_mode) == permissions362+363+364+@pytest.mark.skipif(WIN, reason='os.stat() is not fully supported on Windows.')365+def test_open_file_atomic_permissions_new_file(runner):366+ with runner.isolated_filesystem():367+ @click.command()368+ @click.argument('filename')369+ def cli(filename):370+ click.open_file(filename, 'w', atomic=True).close()371+372+ # Create a test file to get the expected permissions for new files373+ # according to the current umask.374+ with open('test.txt', 'w'):375+ pass376+ permissions = stat.S_IMODE(os.stat('test.txt').st_mode)377+378+ result = runner.invoke(cli, ['new.txt'])379+ assert result.exception is None380+ assert stat.S_IMODE(os.stat('new.txt').st_mode) == permissions381+382+383 def test_iter_keepopenfile(tmpdir):384 expected = list(map(str, range(10)))385 p = tmpdir.mkdir('testdir').join('testfile')292- p.write(os.linesep.join(expected))386+ p.write("\n".join(expected))387 with p.open() as f:388 for e_line, a_line in zip(expected, click.utils.KeepOpenFile(f)):389 assert e_line == a_line.strip()390 391 298-@pytest.mark.xfail(WIN and not PY2, reason='God knows ...')392 def test_iter_lazyfile(tmpdir):393 expected = list(map(str, range(10)))394 p = tmpdir.mkdir('testdir').join('testfile')302- p.write(os.linesep.join(expected))395+ p.write("\n".join(expected))396 with p.open() as f:397 with click.utils.LazyFile(f.name) as lf:398 for e_line, a_line in zip(expected, lf):399 assert e_line == a_line.strip()modified:CHANGES.rst+31 added-5 removed
18 unmodified lines19 -----------20 21 Unreleased22 23-- Add ``no_args_is_help`` option to ``click.Command``, defaults to24- False :pr:`1167`23+- Fix PyPI package name, "click" is lowercase again.24 - Fix link in ``unicode_literals`` error message. :pr:`1151`25 - Add support for colored output on UNIX Jupyter notebooks.26 :issue:`1185`27+- Operations that strip ANSI controls will strip the cursor hide/show28+ sequences. :issue:`1216`29 - Remove unused compat shim for ``bytes``. :pr:`1195`29-- Expand unit testing around termui, especially getchar (Windows).30+- Expand testing around termui, especially getchar on Windows.31 :issue:`1116`32 - Fix output on Windows Python 2.7 built with MSVC 14. :pr:`1342`32-- Always return of of the passed choices for ``click.Choice``33- :issue:`1277`, :pr:`1318`33 - Fix ``OSError`` when running in MSYS2. :issue:`1338`34+- Fix ``OSError`` when redirecting to ``NUL`` stream on Windows.35+ :issue:`1065`36 - Fix error in new AppEngine environments. :issue:`1462`37+- Always return one of the passed choices for ``click.Choice``38+ :issue:`1277`, :pr:`1318`39+- Add ``no_args_is_help`` option to ``click.Command``, defaults to40+ False :pr:`1167`41+- Add ``show_defaults`` parameter to ``Context`` to enable showing42+ defaults globally. :issue:`1018`43+- Handle ``env MYPATH=''`` as though the option were not passed.44+ :issue:`1196`45+- It is once again possible to call ``next(bar)`` on an active46+ progress bar instance. :issue:`1125`47+- ``open_file`` with ``atomic=True`` retains permissions of existing48+ files and respects the current umask for new files. :issue:`1376`49+- When using the test ``CliRunner`` with ``mix_stderr=False``, if50+ ``result.stderr`` is empty it will not raise a ``ValueError``.51+ :issue:`1193`52+- Remove the unused ``mix_stderr`` parameter from53+ ``CliRunner.invoke``. :issue:`1435`54+- Fix ``TypeError`` raised when using bool flags and specifying55+ ``type=bool``. :issue:`1287`56+- Newlines in option help text are replaced with spaces before57+ re-wrapping to avoid uneven line breaks. :issue:`834`58+- ``MissingParameter`` exceptions are printable in the Python59+ interpreter. :issue:`1139`60+- Fix how default values for file-type options are shown during61+ prompts. :issue:`914`62 63 64 Version 7.065 -----------541 unmodified lines