Skip to content
Myr

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

22 files+595 added−199 removed

added:.github/ISSUE_TEMPLATE.md+33 added
modified:click/_compat.py+133 added-78 removed
14 unmodified lines
15WIN = sys.platform.startswith('win') and not APP_ENGINE and not MSYS216DEFAULT_COLUMNS = 80171819_ansi_re = re.compile(r'\033\[((?:\d|;)*)([a-zA-Z])')19_ansi_re = re.compile(r"\033\[[;?0-9]*[a-zA-Z]")202122def get_filesystem_encoding():23 return sys.getfilesystemencoding() or sys.getdefaultencoding()
303 unmodified lines
327 # 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')330331 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)338339 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 )347335 # Perfect match.336 if stream_encoding == encoding and stream_errors == errors:337 return True338339 # 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 None343344 return False345346 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_stream370356 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)373359 # 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_stream378368 # 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"383376 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 )393386 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 )403389 # 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 )413398 # 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)405414 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 lines
474 msg = msg.decode('utf-8', 'replace')475 return msg476477470def open_stream(filename, mode='r', encoding=None, errors='strict',471 atomic=False):478def _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``.483484 Also handles not passing ``encoding`` and ``errors`` in binary mode.485 """486 binary = "b" in mode487488 if binary:489 kwargs = {}490 else:491 kwargs = {"encoding": encoding, "errors": errors}492493 if not PY2 or binary:494 return io.open(file, mode, **kwargs)495496 f = io.open(file, "b" + mode.replace("t", ""))497 return _make_text_stream(f, **kwargs)498499500def open_stream(filename, mode='r', encoding=None, errors='strict', atomic=False):501 binary = "b" in mode502503 # 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), False513514 # 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), True517518 # Some usability stuff for atomic writes519 if 'a' in mode:520 raise ValueError(
10 unmodified lines
531 # 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 random537510 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 = None542543 flags = os.O_RDWR | os.O_CREAT | os.O_EXCL544545 if binary:546 flags |= getattr(os, 'O_BINARY', 0)547548 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 raise565566 if perm is not None:567 os.chmod(tmp_filename, perm) # in case perm includes bits in umask568569 f = _wrap_io_open(fd, mode, encoding, errors)570 return _AtomicFile(f, tmp_filename, os.path.realpath(filename)), True571572573# Used in a destructor call, needs extra protection from interpreter cleanup.
196 unmodified lines
modified:click/_termui_impl.py+21 added-4 removed
106 unmodified lines
107 raise RuntimeError('You need to use progress bars in a with block.')108 self.render_progress()109 return self.generator()110111 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))118119 # Python 2 compat120 next = __next__121122 def is_fast(self):123 return time.time() - self.start <= self.short_limit124125 def render_finish(self):
167 unmodified lines
293 self.current_item = None294 self.finished = True295296 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.')310311 if self.is_hidden:
346 unmodified lines
modified:click/_winconsole.py+16 added-2 removed
22 unmodified lines
23 PyObject_GetBuffer = pythonapi.PyObject_GetBuffer24 PyBuffer_Release = pythonapi.PyBuffer_Release25except ImportError:26 pythonapi = None27from ctypes.wintypes import LPWSTR, LPCWSTR, HANDLE27from ctypes.wintypes import DWORD, LPWSTR, LPCWSTR, HANDLE282930c_ssize_p = POINTER(c_ssize_t)3132kernel32 = windll.kernel3233GetStdHandle = kernel32.GetStdHandle34ReadConsoleW = kernel32.ReadConsoleW35WriteConsoleW = kernel32.WriteConsoleW36GetConsoleMode = kernel32.GetConsoleMode37GetLastError = kernel32.GetLastError38GetCommandLineW = WINFUNCTYPE(LPWSTR)(39 ('GetCommandLineW', windll.kernel32))40CommandLineToArgvW = WINFUNCTYPE(
246 unmodified lines
287 2: _get_text_stderr,288}289290291def _is_console(f):292 if not hasattr(f, 'fileno'):293 return False294295 try:296 fileno = f.fileno()297 except OSError:298 return False299300 handle = msvcrt.get_osfhandle(fileno)301 return bool(GetConsoleMode(handle, byref(DWORD())))302303304def _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 lines
modified:click/core.py+21 added-10 removed
181 unmodified lines
182 .. versionadded:: 4.0183 Added the `color`, `ignore_unknown_options`, and184 `max_content_width` parameters.185186 .. versionadded:: 7.1187 Added the `show_default` parameter.188189 :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 or
813 unmodified lines
1006 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', ' ')))10121013 if opts:1014 with formatter.section('Options'):1015 formatter.write_dl(opts)
371 unmodified lines
1387 intentionally not finalized.13881389 Some settings are supported by both options and arguments.13901387 .. 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.13921391 :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 lines
1415 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.14191420 .. 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.14241425 .. 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'14311432 def __init__(self, param_decls=None, type=None, required=False,
126 unmodified lines
1559 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)15641565 if rv != "":1566 return rv15671568 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 lines
1678 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 = False
155 unmodified lines
18421843 return ((any_prefix_is_slash and '; ' or ' / ').join(rv), help)18441845 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 lines
modified:click/decorators.py+3 added-3 removed
92 unmodified lines
93 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.9697 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.100101 All keyword arguments are forwarded to the underlying command class.102103 Once decorated the function turns into a :class:`Command` instance
208 unmodified lines
modified:click/exceptions.py+13 added
150 unmodified lines
151 msg and '. ' or '.',152 msg or '',153 )154155 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.message161162 if PY2:163 __unicode__ = __str__164165 def __str__(self):166 return self.__unicode__().encode("utf-8")167168169class NoSuchOption(UsageError):170 """Raised if click attempted to handle an option that does not171 exist.172
76 unmodified lines
modified:click/termui.py+11 added-2 removed
1import io2import os3import sys4import struct5import inspect6import itertools78from ._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, WIN10from .utils import echo11from .exceptions import Abort, UsageError12from .types import convert_type, Choice, Path13from .globals import resolve_color_default14from .utils import LazyFile151617# The prompt functions to use. The doc tools currently override these18# functions to customize how they work.
30 unmodified lines
49 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 + suffix555657def _format_default(default):58 if isinstance(default, (io.IOBase, LazyFile)) and hasattr(default, "name"):59 return default.name6061 return default626364def 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 can
568 unmodified lines
modified:click/testing.py+7 added-4 removed
77 unmodified lines
78 #: 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 lines
101102 @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 lines
277 clickpkg.utils.should_strip_ansi = old_should_strip_ansi278 clickpkg.formatting.FORCED_WIDTH = old_forced_width279280 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 lines
346 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()354355 return Result(runner=self,356 stdout_bytes=stdout,357 stderr_bytes=stderr,
20 unmodified lines
modified:docs/commands.rst+15 added-6 removed
86 unmodified lines
87 @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)9394 ctx.obj['DEBUG'] = debug95
220 unmodified lines
316When using multi command chaining you can only have one command (the last)317use ``nargs=-1`` on an argument. It is also not possible to nest multi318commands below chained multicommands. Other than that there are no319restrictions on how they work. They can accept options and arguments as320normal.320normal. The order between options and arguments is limited for chained321commands. Currently only ``--options argument`` order is allowed.322323Another note: the :attr:`Context.invoked_subcommand` attribute is a bit324useless for multi commands as it will give ``'*'`` as value if more than325one command is invoked. This is necessary because the handling of
113 unmodified lines
439440This is useful if you plug in some commands from another package but441you're not satisfied with the defaults.442442The default map can be nested arbitrarily for each subcommand and443provided when the script is invoked. Alternatively, it can also be444overridden at any point by commands. For instance, a top-level command could445load the defaults from a configuration file.443The default map can be nested arbitrarily for each subcommand:444445.. code-block:: python446447 default_map = {448 "debug": True, # default for a top level option449 "runserver": {"port": 5000} # default for a subcommand450 }451452The default map can be provided when the script is invoked, or453overridden at any point by commands. For instance, a top-level command454could load the defaults from a configuration file.455456Example usage:457458.. click:example::459
112 unmodified lines
modified:docs/options.rst+21 added-6 removed
147 unmodified lines
148Multiple Options149----------------150151Similarly to ``nargs``, there is also the case of wanting to support a152parameter being provided multiple times to and have all values recorded --152parameter being provided multiple times and have all the values recorded --153not just the last one. For instance, ``git commit -m foo -m bar`` would154record two lines for the commit message: ``foo`` and ``bar``. This can be155accomplished with the ``multiple`` flag:156
11 unmodified lines
168.. click:run::169170 invoke(commit, args=['-m', 'foo', '-m', 'bar'])171172When passing a ``default`` with ``multiple=True``, the default value173must be a list or tuple, otherwise it will be interpreted as a list of174single characters.175176.. code-block:: python177178 @click.option("--format", multiple=True, default=["json"])179180181Counting182--------183184In some very rare circumstances, it is interesting to use the repetition
164 unmodified lines
349 invoke(digest, args=['--hash-type=foo'])350 println()351 invoke(digest, args=['--help'])352344.. note::353Only pass the choices as list or tuple. Other iterables (like354generators) may lead to unexpected results.355346 You should only pass the choices as list or tuple. Other iterables (like347 generators) may lead to surprising results.356Choices work with options that have ``multiple=True``. If a ``default``357value is given with ``multiple=True``, it should be a list or tuple of358valid choices.359349 Choices should be unique after considering the effects of350 ``case_sensitive`` and any specified token normalization function.360Choices should be unique after considering the effects of361``case_sensitive`` and any specified token normalization function.362363.. 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 lines
404.. click:run::405406 invoke(hello, input=['John'])407408It is advised that prompt not be used in conjunction with the multiple409flag set to True. Instead, prompt in the function interactively.410411412Password Prompts413----------------414415Click also supports hidden prompts and asking for confirmation. This is
408 unmodified lines
modified:docs/python3.rst+6 added
118 unmodified lines
119 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.122123.. note::124125 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.128129You are dealing with an environment where Python 3 thinks you are130restricted to ASCII data. The solution to these problems is different131depending on which locale your computer is running in.132
59 unmodified lines
modified:docs/quickstart.rst+1 added-1 removed
32 unmodified lines
33works.3435If you are on Mac OS X or Linux::3637 $ sudo pip install virtualenv37 $ pip install virtualenv --user3839One of these will probably install virtualenv on your system. Maybe it's even40in your package manager. If you use Ubuntu, try::41
236 unmodified lines
modified:docs/testing.rst+3 added-3 removed
80 unmodified lines
8182File System Isolation83---------------------8485For basic command line tools that want to operate with the file system, the86:meth:`CliRunner.isolated_filesystem` method comes in useful which sets up87an empty folder and changes the current working directory to:85For basic command line tools with file system operations, the86:meth:`CliRunner.isolated_filesystem` method is useful for setting the87current working directory to a new, empty folder.8889.. code-block:: python90 :caption: cat.py91
54 unmodified lines
modified:docs/utils.rst+10 added
387 unmodified lines
388 length=number_of_users) as bar:389 for user in bar:390 modify_the_user(user)391392Note that :func:`progressbar` updates the bar *after* each iteration of the393loop. So code like this will render correctly::394395 import time396397 with click.progressbar([1, 2, 3]) as bar:398 for x in bar:399 print('sleep({})...'.format(x))400 time.sleep(x)401402Another useful feature is to associate a label with the progress bar which403will be shown preceding the progress bar::404405 with click.progressbar(all_the_users_to_process,
15 unmodified lines
modified:docs/why.rst+31 added-36 removed
8 unmodified lines
910* 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.)2021There are many alternatives to Click and you can have a look at them if22you enjoy them better. The obvious ones are ``optparse`` and ``argparse``23from the standard library.21There are many alternatives to Click; the obvious ones are ``optparse``22and ``argparse`` from the standard library. Have a look to see if something23else resonates with you.2425Click actually implements its own parsing of arguments and does not use26``optparse`` or ``argparse`` following the ``optparse`` parsing behavior.27The reason it's not based on ``argparse`` is that ``argparse`` does not28allow proper nesting of commands by design and has some deficiencies when29it comes to POSIX compliant argument handling.3031Click is designed to be fun to work with and at the same time not stand in32your way. It's not overly flexible either. Currently, for instance, it33does not allow you to customize the help pages too much. This is intentional34because Click is designed to allow you to nest command line utilities. The35idea is that you can have a system that works together with another system by36tacking two Click instances together and they will continue working as they37should.31Click is designed to be fun and customizable but not overly flexible.32For instance, the customizability of help pages is constrained. This33constraint is intentional because Click promises multiple Click instances34will continue to function as intended when strung together.3536Too much customizability would break this promise.3738Click was written to support the `Flask <https://palletsprojects.com/p/flask/>`_39microframework ecosystem because no tool could provide it with the40functionality it needed.4142To get an understanding of what Click is all about, I strongly recommend46looking at the :ref:`complex-guide` chapter to see what it's useful for.43looking at the :ref:`complex-guide` chapter.4445Why not Argparse?46-----------------4751Click is internally based on optparse instead of argparse. This however48Click is internally based on ``optparse`` instead of ``argparse``. This49is an implementation detail that a user does not have to be concerned53with. The reason however Click is not using argparse is that it has some54problematic behaviors that make handling arbitrary command line interfaces55hard:50with. Click is not based on argparse because it has some behaviors that51make handling arbitrary command line interfaces hard:5257* 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.6162Why not Docopt etc.?63--------------------6470Docopt and many tools like it are cool in how they work, but very few of65Docopt, and many tools like it, are cool in how they work, but very few of66these tools deal with nesting of commands and composability in a way like67Click. To the best of the developer's knowledge, Click is the first68Python library that aims to create a level of composability of applications69that goes beyond what the system itself supports.
2 unmodified lines
72according to those rules. The side effect of this is that docopt is quite73rigid in how it handles the command line interface. The upside of docopt74is that it gives you strong control over your help page; the downside is75that due to this it cannot rewrap your output for the current terminal81width and it makes translations hard. On top of that docopt is restricted76width, and it makes translations hard. On top of that, docopt is restricted77to basic parsing. It does not handle argument dispatching and callback78invocation or types. This means there is a lot of code that needs to be79written in addition to the basic help page to handle the parsing results.8081Most of all, however, it makes composability hard. While docopt does87support dispatching to subcommands, it for instance does not directly82support dispatching to subcommands, it, for instance, does not directly83support any kind of automatic subcommand enumeration based on what's84available or it does not enforce subcommands to work in a consistent way.8586This is fine, but it's different from how Click wants to work. Click aims
2 unmodified lines
8990- 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.105111The aim of Click is to make composable systems, whereas the aim of docopt106The aim of Click is to make composable systems. Whereas, the aim of docopt107is to build the most beautiful and hand-crafted command line interfaces.108These two goals conflict with one another in subtle ways. Click109actively prevents people from implementing certain patterns in order to115achieve unified command line interfaces. You have very little input on116reformatting your help pages for instance.110achieve unified command line interfaces. For instance, as a developer, you111are given very little choice in formatting your help pages.112113114Why Hardcoded Behaviors?115------------------------
22 unmodified lines
138even optparse and argparse support automatic expansion of long arguments.139The reason for this is that it's a liability for backwards compatibility.140If people start relying on automatically modified parameters and someone141adds a new parameter in the future, the script might stop working. These147kinds of problems are hard to find so Click does not attempt to be magical142kinds of problems are hard to find, so Click does not attempt to be magical143about this.144145This sort of behavior however can be implemented on a higher level to146support things such as explicit aliases. For more information see
1 unmodified line
modified:tests/test_arguments.py+9 added
201 unmodified lines
202 assert result.exit_code == 2203 assert 'Missing argument "ARG".' in result.output204205206def test_missing_argument_string_cast():207 ctx = click.Context(click.Command(""))208209 with pytest.raises(click.MissingParameter) as excinfo:210 click.Argument(["a"], required=True).full_process_value(ctx, None)211212 assert str(excinfo.value) == "missing parameter: a"213214215def test_implicit_non_required(runner):216 @click.command()217 @click.argument('f', default='test')218 def cli(f):
89 unmodified lines
modified:tests/test_options.py+31 added-3 removed
111 unmodified lines
112 assert result.exception113 assert 'Error: Missing option "-m" / "--message".' in result.output114115116def 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)121122 result = runner.invoke(cli, [], env={'MYPATH': ''})123 assert result.exit_code == 0124 assert result.output == 'mypath: None\n'125126127def test_multiple_envvar(runner):128 @click.command()129 @click.option('--arg', multiple=True)130 def cmd(arg):
189 unmodified lines
320 result = runner.invoke(cmd, ['-whatever=23'])321 assert result.output == '23\n'322323324def test_missing_option_string_cast():325 ctx = click.Context(click.Command(""))326327 with pytest.raises(click.MissingParameter) as excinfo:328 click.Option(['-a'], required=True).full_process_value(ctx, None)329330 assert str(excinfo.value) == "missing parameter: a"331332333def test_missing_choice(runner):334 @click.command()335 @click.option('--foo', type=click.Choice(['foo', 'bar']),336 required=True)
69 unmodified lines
406407 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 out411412def test_argument_custom_class(runner):413 class CustomArgument(click.Argument):414 def get_default(self, ctx):
54 unmodified lines
469 assert 'I am a help text' in result.output470 assert 'you wont see me' not in result.output471472473def test_bool_flag_with_type(runner):474 @click.command()475 @click.option('--shout/--no-shout', default=False, type=bool)476 def cmd(shout):477 pass478479 result = runner.invoke(cmd)480 assert not result.exception481482483def test_aliases_for_flags(runner):484 @click.command()485 @click.option('--warnings/--no-warnings', ' /-W', default=True)486 def cli(warnings):
46 unmodified lines
modified:tests/test_termui.py+38 added
183 unmodified lines
184 else:185 assert False, 'Expected an exception because of abort-related inputs.'186187188def test_progressbar_is_iterator(runner, monkeypatch):189 fake_clock = FakeClock()190191 @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 break200201 monkeypatch.setattr(time, 'time', fake_clock.time)202 monkeypatch.setattr(click._termui_impl, 'isatty', lambda _: True)203204 result = runner.invoke(cli, [])205 assert result.exception is None206207208def 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 lines
224 result = runner.invoke(cli_without_choices, [], input='none')225 assert '(none, day, week, month)' not in result.output226227228@pytest.mark.parametrize(229 "file_kwargs",230 [231 {"mode": "rt"},232 {"mode": "rb"},233 {"lazy": True},234 ]235)236def 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)241242 result = runner.invoke(cli)243 assert result.output == "file [{0}]: \n{0}\n".format(__file__)244245246def test_secho(runner):247 with runner.isolation() as outstreams:248 click.secho(None, nl=False)249 bytes = outstreams[0].getvalue()
108 unmodified lines
modified:tests/test_testing.py+12 added
255 unmodified lines
256257 with pytest.raises(ValueError):258 result_mix.stderr259260 @click.command()261 def cli_empty_stderr():262 click.echo("stdout")263264 runner = CliRunner(mix_stderr=False)265266 result = runner.invoke(cli_empty_stderr)267268 assert result.output == 'stdout\n'269 assert result.stdout == 'stdout\n'270 assert result.stderr == ''271272273@pytest.mark.parametrize('args, expected_output', [274 (None, 'bar\n'),275 ([], 'bar\n'),276 ('', 'bar\n'),
25 unmodified lines
modified:tests/test_utils.py+129 added-36 removed
1import os2import stat3import sys45import pytest6
43 unmodified lines
50 click.echo(u'hello', file=f)51 assert f.getvalue() == u'hello\n'525353def 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)79def test_styling(styles, ref):80 assert click.style("x y", **styles) == ref81 assert click.unstyle(ref) == "x y"828384@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)90def test_unstyle_other_ansi(text, expect):91 assert click.unstyle(text) == expect92939495def 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 lines
278 assert err == 'Pause to stderr\n'279280281def 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())287288 click.echo('meep')289290 with runner.isolated_filesystem():291 with open('hello.txt', 'w') as f:292 f.write('Cool stuff')293272 @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')278294 result = runner.invoke(cli, ['hello.txt'])295 assert result.exception is None296 assert result.output == 'Cool stuff\nmeep\n'297
1 unmodified line
299 assert result.exception is None300 assert result.output == 'foobar\nmeep\n'301302288@pytest.mark.xfail(WIN and not PY2, reason='God knows ...')303def 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())309310 result = runner.invoke(cli, ["-"], input=os.urandom(16))311 assert result.exception is None312313314def test_open_file_respects_ignore(runner):315 with runner.isolated_filesystem():316 with open("test.txt", "w") as f:317 f.write("Hello world!")318319 with click.open_file("test.txt", encoding="utf8", errors="ignore") as f:320 assert f.errors == "ignore"321322323def 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")327328 with click.open_file("test.txt", encoding="utf8", errors="ignore") as f:329 f.read()330331332def 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))336337 with click.open_file("test.bin", errors="ignore") as f:338 f.read()339340341@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 ])348def 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)353354 @click.command()355 @click.argument('filename')356 def cli(filename):357 click.open_file(filename, 'w', atomic=True).close()358359 result = runner.invoke(cli, ['existing.txt'])360 assert result.exception is None361 assert stat.S_IMODE(os.stat('existing.txt').st_mode) == permissions362363364@pytest.mark.skipif(WIN, reason='os.stat() is not fully supported on Windows.')365def 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()371372 # 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)377378 result = runner.invoke(cli, ['new.txt'])379 assert result.exception is None380 assert stat.S_IMODE(os.stat('new.txt').st_mode) == permissions381382383def 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()390391298@pytest.mark.xfail(WIN and not PY2, reason='God knows ...')392def 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 lines
19-----------2021Unreleased2223- 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`626364Version 7.065-----------
541 unmodified lines