Skip to content
Myr

Merge branch '8.1.x'

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

authored by David Lord · committed by David Lord · parents 187666a, f20395d · Browse files · 28 files+696 added−247 removed
This commit

State

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

Diff stats

28 files+696 added−247 removed

  • tests:+213 added−46 removed
  • other:+483 added−201 removed

28 files+696 added−247 removed

modified:docs/arguments.rst+3 added-9 removed
122 unmodified lines
123-------------------124125In the previous example, the files were opened immediately. But what if126we just want the filename? The naïve way is to use the default string127argument type. However, remember that Click is Unicode-based, so the string128will always be a Unicode value. Unfortunately, filenames can be Unicode or129bytes depending on which operating system is being used. As such, the type130is insufficient.127argument type. The :class:`Path` type has several checks available which raise nice128errors if they fail, such as existence. Filenames in these error messages are formatted129with :func:`format_filename`, so any undecodable bytes will be printed nicely.130132Instead, you should be using the :class:`Path` type, which automatically133handles this ambiguity. Not only will it return either bytes or Unicode134depending on what makes more sense, but it will also be able to do some135basic checks for you such as existence checks.136131Example:132133.. click:example::134
129 unmodified lines
modified:docs/complex.rst+163 added
216 unmodified lines
217218.. click:run::219220 invoke(cp, [])221222Lazily Loading Subcommands223--------------------------224225Large CLIs and CLIs with slow imports may benefit from deferring the loading of226subcommands. The interfaces which support this mode of use are227:meth:`MultiCommand.list_commands` and :meth:`MultiCommand.get_command`. A custom228:class:`MultiCommand` subclass can implement a lazy loader by storing extra data such229that :meth:`MultiCommand.get_command` is responsible for running imports.230231Since the primary case for this is a :class:`Group` which loads its subcommands lazily,232the following example shows a lazy-group implementation.233234.. warning::235236 Lazy loading of python code can result in hard to track down bugs, circular imports237 in order-dependent codebases, and other surprising behaviors. It is recommended that238 this technique only be used in concert with testing which will at least run the239 ``--help`` on each subcommand. That will guarantee that each subcommand can be loaded240 successfully.241242Defining the Lazy Group243```````````````````````244245The following :class:`Group` subclass adds an attribute, ``lazy_subcommands``, which246stores a mapping from subcommand names to the information for importing them.247248.. code-block:: python249250 # in lazy_group.py251 import importlib252 import click253254 class LazyGroup(click.Group):255 def __init__(self, *args, lazy_subcommands=None, **kwargs):256 super().__init__(*args, **kwargs)257 # lazy_subcommands is a map of the form:258 #259 # {command-name} -> {module-name}.{command-object-name}260 #261 self.lazy_subcommands = lazy_subcommands or {}262263 def list_commands(self, ctx):264 base = super().list_commands(ctx)265 lazy = sorted(self.lazy_subcommands.keys())266 return base + lazy267268 def get_command(self, ctx, cmd_name):269 if cmd_name in self.lazy_subcommands:270 return self._lazy_load(cmd_name)271 return super().get_command(ctx, cmd_name)272273 def _lazy_load(self, cmd_name):274 # lazily loading a command, first get the module name and attribute name275 import_path = self.lazy_subcommands[cmd_name]276 modname, cmd_object_name = import_path.rsplit(".", 1)277 # do the import278 mod = importlib.import_module(modname)279 # get the Command object from that module280 cmd_object = getattr(mod, cmd_object_name)281 # check the result to make debugging easier282 if not isinstance(cmd_object, click.BaseCommand):283 raise ValueError(284 f"Lazy loading of {import_path} failed by returning "285 "a non-command object"286 )287 return cmd_object288289Using LazyGroup To Define a CLI290```````````````````````````````291292With ``LazyGroup`` defined, it's now possible to write a group which lazily loads its293subcommands like so:294295.. code-block:: python296297 # in main.py298 import click299 from lazy_group import LazyGroup300301 @click.group(302 cls=LazyGroup,303 lazy_subcommands={"foo": "foo.cli", "bar": "bar.cli"},304 help="main CLI command for lazy example",305 )306 def cli():307 pass308309 # in foo.py310 import click311312 @click.group(help="foo command for lazy example")313 def cli():314 pass315316 # in bar.py317 import click318 from lazy_group import LazyGroup319320 @click.group(321 cls=LazyGroup,322 lazy_subcommands={"baz": "baz.cli"},323 help="bar command for lazy example",324 )325 def cli():326 pass327328 # in baz.py329 import click330331 @click.group(help="baz command for lazy example")332 def cli():333 pass334335336What triggers Lazy Loading?337```````````````````````````338339There are several events which may trigger lazy loading by running the340:meth:`MultiCommand.get_command` function.341Some are intuititve, and some are less so.342343All cases are described with respect to the above example, assuming the main program344name is ``cli``.3453461. Command resolution. If a user runs ``cli bar baz``, this must first resolve ``bar``,347 and then resolve ``baz``. Each subcommand resolution step does a lazy load.3482. Helptext rendering. In order to get the short help description of subcommands,349 ``cli --help`` will load ``foo`` and ``bar``. Note that it will still not load350 ``baz``.3513. Shell completion. In order to get the subcommands of a lazy command, ``cli <TAB>``352 will need to resolve the subcommands of ``cli``. This process will trigger the lazy353 loads.354355Further Deferring Imports356`````````````````````````357358It is possible to make the process even lazier, but it is generally more difficult the359more you want to defer work.360361For example, subcommands could be represented as a custom :class:`BaseCommand` subclass362which defers importing the command until it is invoked, but which provides363:meth:`BaseCommand.get_short_help_str` in order to support completions and helptext.364More simply, commands can be constructed whose callback functions defer any actual work365until after an import.366367This command definition provides ``foo``, but any of the work associated with importing368the "real" callback function is deferred until invocation time:369370.. click:example::371372 @click.command()373 @click.option("-n", type=int)374 @click.option("-w", type=str)375 def foo(n, w):376 from mylibrary import foo_concrete377378 foo_concrete(n, w)379380Because ``click`` builds helptext and usage info from options, arguments, and command381attributes, it has no awareness that the underlying function is in any way handling a382deferred import. Therefore, all ``click``-provided utilities and functionality will work383as normal on such a command.
modified:docs/conf.py-5 removed
1from pallets_sphinx_themes import get_version2from pallets_sphinx_themes import ProjectLink34import click._compat56# compat until pallets-sphinx-themes is updated7click._compat.text_type = str84# Project --------------------------------------------------------------56project = "Click"7copyright = "2014 Pallets"
45 unmodified lines
modified:docs/contrib.rst+10 added-14 removed
2 unmodified lines
3=============4click-contrib5=============67As the userbase of Click grows, more and more major feature requests pop up in8Click's bugtracker. As reasonable as it may be for those features to be bundled9with Click instead of being a standalone project, many of those requested10features are either highly experimental or have unproven practical use, while11potentially being a burden to maintain.7As the number of users of Click grows, more and more major feature requests are8made. To users it may seem reasonable to include those features with Click;9however, many of them are experimental or aren't practical to support10generically. Maintainers have to choose what is reasonable to maintain in Click11core.1213This is why click-contrib_ exists. The GitHub organization is a collection of14possibly experimental third-party packages whose featureset does not belong15into Click, but also a playground for major features that may be added to Click16in the future. It is also meant to coordinate and concentrate effort on writing17third-party extensions for Click, and to ease the effort of searching for such18extensions. In that sense it could be described as a low-maintenance19alternative to extension repositories of other frameworks.13The click-contrib_ GitHub organization exists as a place to collect third-party14packages that extend Click's features. It is also meant to ease the effort of15searching for such extensions.1617Please note that the quality and stability of those packages may be different22than what you expect from Click itself. While published under a common23organization, they are still projects separate from Click.18than Click itself. While published under a common organization, they are still19separate from Click and the Pallets maintainers.2021.. _click-contrib: https://github.com/click-contrib/
modified:docs/documentation.rst+28 added-2 removed
83 unmodified lines
84Preventing Rewrapping85---------------------8687The default behavior of Click is to rewrap text based on the width of the88terminal. In some circumstances, this can become a problem. The main issue89is when showing code examples, where newlines are significant.88terminal, to a maximum 80 characters. In some circumstances, this can become89a problem. The main issue is when showing code examples, where newlines are90significant.9192Rewrapping can be disabled on a per-paragraph basis by adding a line with93solely the ``\b`` escape marker in it. This line will be removed from the94help text and rewrapping will be disabled.
25 unmodified lines
120.. click:run::121122 invoke(cli, args=['--help'])123124To change the maximum width, pass ``max_content_width`` when calling the command.125126.. code-block:: python127128 cli(max_content_width=120)129130131.. _doc-meta-variables:132133Truncating Help Texts134---------------------
81 unmodified lines
216.. click:run::217218 invoke(cli, prog_name='repo.py')219220Command Epilog Help221-------------------222223The help epilog is like the help string but it's printed at the end of the help224page after everything else. Useful for showing example command usages or225referencing additional help resources.226227.. click:example::228229 @click.command(epilog='Check out our docs at https://click.palletsprojects.com/ for more details')230 def init():231 """Initializes the repository."""232233And what it looks like:234235.. click:run::236237 invoke(init, prog_name='repo.py', args=['--help'])238239Help Parameter Customization240----------------------------241242.. versionadded:: 2.0
25 unmodified lines
modified:docs/quickstart.rst+8 added-26 removed
27 unmodified lines
2829Virtualenv to the rescue! Virtualenv enables multiple side-by-side30installations of Python, one for each project. It doesn't actually31install separate copies of Python, but it does provide a clever way to32keep different project environments isolated. Let's see how virtualenv33works.32keep different project environments isolated.3335If you are on Mac OS X or Linux::34Create your project folder, then a virtualenv within it::3537 $ 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::4142 $ sudo apt-get install python-virtualenv4344If you are on Windows (or none of the above methods worked) you must install45``pip`` first. For more information about this, see `installing pip`_.46Once you have it installed, run the ``pip`` command from above, but without47the `sudo` prefix.4849.. _installing pip: https://pip.readthedocs.io/en/latest/installing/5051Once you have virtualenv installed, just fire up a shell and create52your own environment. I usually create a project folder and a `venv`53folder within::5436 $ mkdir myproject37 $ cd myproject57 $ virtualenv venv58 New python executable in venv/bin/python38 $ python3 -m venv .venv3940Now, whenever you want to work on a project, you only have to activate the41corresponding environment. On OS X and Linux, do the following::4263 $ . venv/bin/activate43 $ . .venv/bin/activate44 (venv) $4546If you are a Windows user, the following command is for you::4767 $ venv\scripts\activate48 > .venv\scripts\activate49 (venv) >5051Either way, you should now be using your virtualenv (notice how the prompt of52your shell has changed to show the active environment).5372And if you want to go back to the real world, use the following command::54And if you want to stop using the virtualenv, use the following command::5556 $ deactivate5758After doing this, the prompt of your shell should be as familiar as before.
218 unmodified lines
modified:src/click/_compat.py+13 added-16 removed
5 unmodified lines
6import typing as t7from weakref import WeakKeyDictionary89CYGWIN = sys.platform.startswith("cygwin")10MSYS2 = sys.platform.startswith("win") and ("GCC" in sys.version)11# Determine local App Engine environment, per Google's own suggestion12APP_ENGINE = "APPENGINE_RUNTIME" in os.environ and "Development/" in os.environ.get(13 "SERVER_SOFTWARE", ""14)15WIN = sys.platform.startswith("win") and not APP_ENGINE and not MSYS210WIN = sys.platform.startswith("win")11auto_wrap_for_ansi: t.Optional[t.Callable[[t.TextIO], t.TextIO]] = None12_ansi_re = re.compile(r"\033\[[;?0-9]*[a-zA-Z]")131420def get_filesystem_encoding() -> str:21 return sys.getfilesystemencoding() or sys.getdefaultencoding()222315def _make_text_stream(16 stream: t.BinaryIO,17 encoding: t.Optional[str],18 errors: t.Optional[str],
338 unmodified lines
357 return _force_correct_text_writer(sys.stderr, encoding, errors, force_writable=True)358359360def _wrap_io_open(370 file: t.Union[str, "os.PathLike[t.AnyStr]", int],361 file: t.Union[str, "os.PathLike[str]", int],362 mode: str,363 encoding: t.Optional[str],364 errors: t.Optional[str],365) -> t.IO[t.Any]:
4 unmodified lines
370 return open(file, mode, encoding=encoding, errors=errors)371372373def open_stream(383 filename: str,374 filename: "t.Union[str, os.PathLike[str]]",375 mode: str = "r",376 encoding: t.Optional[str] = None,377 errors: t.Optional[str] = "strict",378 atomic: bool = False,379) -> t.Tuple[t.IO[t.Any], bool]:380 binary = "b" in mode381 filename = os.fspath(filename)382383 # Standard streams first. These are simple because they ignore the384 # atomic flag. Use fsdecode to handle Path("-").385 if os.fsdecode(filename) == "-":
169 unmodified lines
555556else:557558 def _get_argv_encoding() -> str:567 return getattr(sys.stdin, "encoding", None) or get_filesystem_encoding()559 return getattr(sys.stdin, "encoding", None) or sys.getfilesystemencoding()560561 def _get_windows_console_stream(562 f: t.TextIO, encoding: t.Optional[str], errors: t.Optional[str]563 ) -> t.Optional[t.TextIO]:
11 unmodified lines
575 return False576577578def _make_cached_stream_func(587 src_func: t.Callable[[], t.TextIO], wrapper_func: t.Callable[[], t.TextIO]588) -> t.Callable[[], t.TextIO]:579 src_func: t.Callable[[], t.Optional[t.TextIO]],580 wrapper_func: t.Callable[[], t.TextIO],581) -> t.Callable[[], t.Optional[t.TextIO]]:582 cache: t.MutableMapping[t.TextIO, t.TextIO] = WeakKeyDictionary()583591 def func() -> t.TextIO:584 def func() -> t.Optional[t.TextIO]:585 stream = src_func()586587 if stream is None:588 return None589590 try:591 rv = cache.get(stream)592 except Exception:593 rv = None
30 unmodified lines
modified:src/click/_termui_impl.py+31 added-9 removed
8 unmodified lines
9import sys10import time11import typing as t12from gettext import gettext as _13from io import StringIO14from types import TracebackType1516from ._compat import _default_text_stdout17from ._compat import CYGWIN18from ._compat import get_best_encoding
41 unmodified lines
60 self.show_eta = show_eta61 self.show_percent = show_percent62 self.show_pos = show_pos63 self.item_show_func = item_show_func62 self.label = label or ""64 self.label: str = label or ""6566 if file is None:67 file = _default_text_stdout()6869 # There are no standard streams attached to write to. For example,70 # pythonw on Windows.71 if file is None:72 file = StringIO()7374 self.file = file75 self.color = color76 self.update_min_steps = update_min_steps77 self._completed_intervals = 069 self.width = width70 self.autowidth = width == 078 self.width: int = width79 self.autowidth: bool = width == 08081 if length is None:82 from operator import length_hint83
4 unmodified lines
88 if iterable is None:89 if length is None:90 raise TypeError("iterable or length is required")91 iterable = t.cast(t.Iterable[V], range(length))83 self.iter = iter(iterable)92 self.iter: t.Iterable[V] = iter(iterable)93 self.length = length94 self.pos = 095 self.avg: t.List[float] = []96 self.last_eta: float97 self.start: float98 self.start = self.last_eta = time.time()88 self.eta_known = False89 self.finished = False99 self.eta_known: bool = False100 self.finished: bool = False101 self.max_width: t.Optional[int] = None91 self.entered = False102 self.entered: bool = False103 self.current_item: t.Optional[V] = None93 self.is_hidden = not isatty(self.file)104 self.is_hidden: bool = not isatty(self.file)105 self._last_line: t.Optional[str] = None106107 def __enter__(self) -> "ProgressBar[V]":108 self.entered = True109 self.render_progress()110 return self111101 def __exit__(self, *_: t.Any) -> None:112 def __exit__(113 self,114 exc_type: t.Optional[t.Type[BaseException]],115 exc_value: t.Optional[BaseException],116 tb: t.Optional[TracebackType],117 ) -> None:118 self.render_finish()119120 def __iter__(self) -> t.Iterator[V]:121 if not self.entered:
237 unmodified lines
359360def pager(generator: t.Iterable[str], color: t.Optional[bool] = None) -> None:361 """Decide what method to use for paging through text."""362 stdout = _default_text_stdout()363364 # There are no standard streams attached to write to. For example,365 # pythonw on Windows.366 if stdout is None:367 stdout = StringIO()368369 if not isatty(sys.stdin) or not isatty(stdout):370 return _nullpager(stdout, generator, color)371 pager_cmd = (os.environ.get("PAGER", None) or "").strip()372 if pager_cmd:
367 unmodified lines
modified:src/click/core.py+40 added-21 removed
5 unmodified lines
6import typing as t7from collections import abc8from contextlib import contextmanager9from contextlib import ExitStack10from functools import partial10from functools import update_wrapper11from gettext import gettext as _12from gettext import ngettext13from itertools import repeat14from types import TracebackType1516from . import types17from .exceptions import Abort18from .exceptions import BadParameter
435 unmodified lines
454 self._depth += 1455 push_context(self)456 return self457458 def __exit__(self, *_: t.Any) -> None:458 def __exit__(459 self,460 exc_type: t.Optional[t.Type[BaseException]],461 exc_value: t.Optional[BaseException],462 tb: t.Optional[TracebackType],463 ) -> None:464 self._depth -= 1465 if self._depth == 0:466 self.close()467 pop_context()
617 unmodified lines
1085 # chained commands which all returned `None` -- so it's not1086 # even always obvious that `rv` indicates success/failure1087 # by its truthiness/falsiness1088 ctx.exit()1084 except (EOFError, KeyboardInterrupt):1089 except (EOFError, KeyboardInterrupt) as e:1090 echo(file=sys.stderr)1086 raise Abort() from None1091 raise Abort() from e1092 except ClickException as e:1093 if not standalone_mode:1094 raise1095 e.show()
37 unmodified lines
1133 :param prog_name: Name of the executable in the shell.1134 :param complete_var: Name of the environment variable that holds1135 the completion instruction. Defaults to1136 ``_{PROG_NAME}_COMPLETE``.11371138 .. versionchanged:: 8.2.01139 Dots (``.``) in ``prog_name`` are replaced with underscores (``_``).1140 """1141 if complete_var is None:1134 complete_var = f"_{prog_name}_COMPLETE".replace("-", "_").upper()1142 complete_name = prog_name.replace("-", "_").replace(".", "_")1143 complete_var = f"_{complete_name}_COMPLETE".upper()11441145 instruction = os.environ.get(complete_var)11461147 if not instruction:
211 unmodified lines
1359 self.format_epilog(ctx, formatter)13601361 def format_help_text(self, ctx: Context, formatter: HelpFormatter) -> None:1362 """Writes the help text to the formatter if it exists."""1354 text = self.help if self.help is not None else ""1363 if self.help is not None:1364 # truncate the help text to the first form feed1365 text = inspect.cleandoc(self.help).partition("\f")[0]1366 else:1367 text = ""13681369 if self.deprecated:1370 text = _("(Deprecated) {text}").format(text=text)13711372 if text:1360 text = inspect.cleandoc(text).partition("\f")[0]1373 formatter.write_paragraph()13741375 with formatter.indentation():1376 formatter.write_text(text)
493 unmodified lines
1870 Added the :attr:`command_class` attribute.1871 """1872 from .decorators import command18731862 if self.command_class and kwargs.get("cls") is None:1863 kwargs["cls"] = self.command_class18641874 func: t.Optional[t.Callable[..., t.Any]] = None18751876 if args and callable(args[0]):1877 assert (
1 unmodified line
1879 ), "Use 'command(**kwargs)(callable)' to provide arguments."1880 (func,) = args1881 args = ()18821883 if self.command_class and kwargs.get("cls") is None:1884 kwargs["cls"] = self.command_class18851886 def decorator(f: t.Callable[..., t.Any]) -> Command:1887 cmd: Command = command(*args, **kwargs)(f)1888 self.add_command(cmd)1889 return cmd
214 unmodified lines
2104 t.Union[t.List["CompletionItem"], t.List[str]],2105 ]2106 ] = None,2107 ) -> None:2108 self.name: t.Optional[str]2109 self.opts: t.List[str]2110 self.secondary_opts: t.List[str]2111 self.name, self.opts, self.secondary_opts = self._parse_decls(2112 param_decls or (), expose_value2113 )2099 self.type = types.convert_type(type, default)2114 self.type: types.ParamType = types.convert_type(type, default)21152116 # Default nargs to what the type tells us if we have that2117 # information available.2118 if nargs is None:
191 unmodified lines
2310 _("Value must be an iterable."), ctx=ctx, param=self2311 ) from None23122313 if self.nargs == 1 or self.type.is_composite:2299 convert: t.Callable[[t.Any], t.Any] = partial(2300 self.type, param=self, ctx=ctx2301 )23142315 def convert(value: t.Any) -> t.Any:2316 return self.type(value, param=self, ctx=ctx)23172318 elif self.nargs == -1:23192304 def convert(value: t.Any) -> t.Tuple[t.Any, ...]:2320 def convert(value: t.Any) -> t.Any: # t.Tuple[t.Any, ...]2321 return tuple(self.type(x, self, ctx) for x in check_iter(value))23222323 else: # nargs > 123242309 def convert(value: t.Any) -> t.Tuple[t.Any, ...]:2325 def convert(value: t.Any) -> t.Any: # t.Tuple[t.Any, ...]2326 value = tuple(check_iter(value))23272328 if len(value) != self.nargs:2329 raise BadParameter(
239 unmodified lines
2569 # Not a flag, and prompt is not enabled, can be used as a2570 # flag if flag_value is set.2571 self._flag_needs_value = flag_value is not None25722573 self.default: t.Union[t.Any, t.Callable[[], t.Any]]25742575 if is_flag and default_is_missing and not self.required:2558 self.default: t.Union[t.Any, t.Callable[[], t.Any]] = False2576 if multiple:2577 self.default = ()2578 else:2579 self.default = False25802581 if flag_value is None:2582 flag_value = not self.default25832584 self.type: types.ParamType2585 if is_flag and type is None:2586 # Re-guess the type from the flag value instead of the2587 # default.2588 self.type = types.convert_type(None, flag_value)25892590 self.is_flag: bool = is_flag2569 self.is_bool_flag = is_flag and isinstance(self.type, types.BoolParamType)2591 self.is_bool_flag: bool = is_flag and isinstance(self.type, types.BoolParamType)2592 self.flag_value: t.Any = flag_value25932594 # Counting2595 self.count = count
30 unmodified lines
26262627 if self.is_flag:2628 raise TypeError("'count' is not valid with 'is_flag'.")26292608 if self.multiple and self.is_flag:2609 raise TypeError("'multiple' is not valid with 'is_flag', use 'count'.")26102630 def to_info_dict(self) -> t.Dict[str, t.Any]:2631 info_dict = super().to_info_dict()2632 info_dict.update(2633 help=self.help,
409 unmodified lines
modified:src/click/decorators.py+12 added-8 removed
327 unmodified lines
328329 f.__click_params__.append(param) # type: ignore330331332def argument(*param_decls: str, **attrs: t.Any) -> _Decorator[FC]:332def argument(333 *param_decls: str, cls: t.Optional[t.Type[Argument]] = None, **attrs: t.Any334) -> _Decorator[FC]:335 """Attaches an argument to the command. All positional arguments are336 passed as parameter declarations to :class:`Argument`; all keyword337 arguments are forwarded unchanged (except ``cls``).338 This is equivalent to creating an :class:`Argument` instance manually
7 unmodified lines
346 :param param_decls: Passed as positional arguments to the constructor of347 ``cls``.348 :param attrs: Passed as keyword arguments to the constructor of ``cls``.349 """350 if cls is None:351 cls = Argument352353 def decorator(f: FC) -> FC:350 ArgumentClass = attrs.pop("cls", None) or Argument351 _param_memo(f, ArgumentClass(param_decls, **attrs))354 _param_memo(f, cls(param_decls, **attrs))355 return f356357 return decorator358359357def option(*param_decls: str, **attrs: t.Any) -> _Decorator[FC]:360def option(361 *param_decls: str, cls: t.Optional[t.Type[Option]] = None, **attrs: t.Any362) -> _Decorator[FC]:363 """Attaches an option to the command. All positional arguments are364 passed as parameter declarations to :class:`Option`; all keyword365 arguments are forwarded unchanged (except ``cls``).366 This is equivalent to creating an :class:`Option` instance manually
7 unmodified lines
374 :param param_decls: Passed as positional arguments to the constructor of375 ``cls``.376 :param attrs: Passed as keyword arguments to the constructor of ``cls``.377 """378 if cls is None:379 cls = Option380381 def decorator(f: FC) -> FC:375 # Issue 926, copy attrs, so pre-defined options can re-use the same cls=376 option_attrs = attrs.copy()377 OptionClass = option_attrs.pop("cls", None) or Option378 _param_memo(f, OptionClass(param_decls, **option_attrs))382 _param_memo(f, cls(param_decls, **attrs))383 return f384385 return decorator386
184 unmodified lines
modified:src/click/exceptions.py+5 added-4 removed
1import os1import typing as t2from gettext import gettext as _3from gettext import ngettext45from ._compat import get_text_stderr6from .utils import echo7from .utils import format_filename89if t.TYPE_CHECKING:10 from .core import Command11 from .core import Context12 from .core import Parameter1314
42 unmodified lines
5758 def __init__(self, message: str, ctx: t.Optional["Context"] = None) -> None:59 super().__init__(message)60 self.ctx = ctx60 self.cmd = self.ctx.command if self.ctx else None61 self.cmd: t.Optional["Command"] = self.ctx.command if self.ctx else None6263 def show(self, file: t.Optional[t.IO[t.Any]] = None) -> None:64 if file is None:65 file = get_text_stderr()
195 unmodified lines
261 if hint is None:262 hint = _("unknown error")263264 super().__init__(hint)264 self.ui_filename = os.fsdecode(filename)265 self.ui_filename: str = format_filename(filename)266 self.filename = filename267268 def format_message(self) -> str:269 return _("Could not open file {filename!r}: {message}").format(
14 unmodified lines
284285 __slots__ = ("exit_code",)286287 def __init__(self, code: int = 0) -> None:287 self.exit_code = code288 self.exit_code: int = code
modified:src/click/parser.py+4 added-4 removed
166 unmodified lines
167 const: t.Optional[t.Any] = None,168 ):169 self._short_opts = []170 self._long_opts = []171 self.prefixes = set()171 self.prefixes: t.Set[str] = set()172173 for opt in opts:174 prefix, value = split_opt(opt)175 if not prefix:
17 unmodified lines
193 @property194 def takes_value(self) -> bool:195 return self.action in ("store", "append")196197 def process(self, value: str, state: "ParsingState") -> None:197 def process(self, value: t.Any, state: "ParsingState") -> None:198 if self.action == "store":199 state.opts[self.dest] = value # type: ignore200 elif self.action == "store_const":201 state.opts[self.dest] = self.const # type: ignore
69 unmodified lines
271 #: This controls how the parser deals with interspersed arguments.272 #: If this is set to `False`, the parser will stop on the first273 #: non-option. Click uses this to implement nested subcommands274 #: safely.275 self.allow_interspersed_args = True275 self.allow_interspersed_args: bool = True276 #: This tells the parser how to deal with unknown options. By277 #: default it will error out (which is sensible), but there is a278 #: second mode where it will ignore it and continue processing279 #: after shifting all the unknown options into the resulting args.280 self.ignore_unknown_options = False280 self.ignore_unknown_options: bool = False281282 if ctx is not None:283 self.allow_interspersed_args = ctx.allow_interspersed_args284 self.ignore_unknown_options = ctx.ignore_unknown_options
245 unmodified lines
modified:src/click/shell_completion.py+30 added-25 removed
78 unmodified lines
79 type: str = "plain",80 help: t.Optional[str] = None,81 **kwargs: t.Any,82 ) -> None:83 self.value = value84 self.type = type85 self.help = help83 self.value: t.Any = value84 self.type: str = type85 self.help: t.Optional[str] = help86 self._info = kwargs8788 def __getattr__(self, name: str) -> t.Any:89 return self._info.get(name)
66 unmodified lines
156 compadd -U -V unsorted -a completions157 fi158}159160if [[ $zsh_eval_context[-1] == loadautofunc ]]; then161 # autoload from fpath, call function directly162 %(complete_func)s "$@"163else164 # eval/source/. command, register function for later160compdef %(complete_func)s %(prog_name)s;165 compdef %(complete_func)s %(prog_name)s166fi167"""168169_SOURCE_FISH = """\164function %(complete_func)s;165 set -l response;170function %(complete_func)s171 set -l response (env %(complete_var)s=fish_complete COMP_WORDS=(commandline -cp) \172COMP_CWORD=(commandline -t) %(prog_name)s)173167 for value in (env %(complete_var)s=fish_complete COMP_WORDS=(commandline -cp) \168COMP_CWORD=(commandline -t) %(prog_name)s);169 set response $response $value;170 end;174 for completion in $response175 set -l metadata (string split "," $completion)176172 for completion in $response;173 set -l metadata (string split "," $completion);177 if test $metadata[1] = "dir"178 __fish_complete_directories $metadata[2]179 else if test $metadata[1] = "file"180 __fish_complete_path $metadata[2]181 else if test $metadata[1] = "plain"182 echo $metadata[2]183 end184 end185end186175 if test $metadata[1] = "dir";176 __fish_complete_directories $metadata[2];177 else if test $metadata[1] = "file";178 __fish_complete_path $metadata[2];179 else if test $metadata[1] = "plain";180 echo $metadata[2];181 end;182 end;183end;184187complete --no-files --command %(prog_name)s --arguments \186"(%(complete_func)s)";188"(%(complete_func)s)"189"""190191192class ShellComplete:
111 unmodified lines
304 def _check_version(self) -> None:305 import subprocess306307 output = subprocess.run(306 ["bash", "-c", "echo ${BASH_VERSION}"], stdout=subprocess.PIPE308 ["bash", "-c", 'echo "${BASH_VERSION}"'], stdout=subprocess.PIPE309 )310 match = re.search(r"^(\d+)\.(\d+)\.\d+", output.stdout.decode())311312 if match is not None:
129 unmodified lines
442 if not isinstance(param, Argument):443 return False444445 assert param.name is not None444 value = ctx.params[param.name]446 # Will be None if expose_value is False.447 value = ctx.params.get(param.name)448 return (449 param.nargs == -1450 or ctx.get_parameter_source(param.name) is not ParameterSource.COMMANDLINE451 or (
67 unmodified lines
519520 ctx = cmd.make_context(name, args, parent=ctx, resilient_parsing=True)521 args = ctx.protected_args + ctx.args522 else:523 sub_ctx = ctx524525 while args:526 name, cmd, args = command.resolve_command(ctx, args)527528 if cmd is None:
65 unmodified lines
modified:src/click/termui.py+3 added-6 removed
1import inspect2import io3import itertools4import os4import sys5import typing as t6from gettext import gettext as _78from ._compat import isatty9from ._compat import strip_ansi11from ._compat import WIN10from .exceptions import Abort11from .exceptions import UsageError12from .globals import resolve_color_default13from .types import Choice
426 unmodified lines
440 .. versionadded:: 2.0441 """442 if not isatty(sys.stdout):443 return446 if WIN:447 os.system("cls")448 else:449 sys.stdout.write("\033[2J\033[1;1H")444445 # ANSI escape \033[2J clears the screen, \033[1;1H moves the cursor446 echo("\033[2J\033[1;1H", nl=False)447448449def _interpret_color(450 color: t.Union[int, t.Tuple[int, int, int], str], offset: int = 0451) -> str:452 if isinstance(color, int):
332 unmodified lines
modified:src/click/testing.py+1 added-1 removed
181 unmodified lines
182 echo_stdin: bool = False,183 mix_stderr: bool = True,184 ) -> None:185 self.charset = charset186 self.env = env or {}186 self.env: t.Mapping[str, t.Optional[str]] = env or {}187 self.echo_stdin = echo_stdin188 self.mix_stderr = mix_stderr189190 def get_default_prog_name(self, cli: "BaseCommand") -> str:
289 unmodified lines
modified:src/click/types.py+49 added-30 removed
1import os2import stat3import sys4import typing as t5from datetime import datetime6from gettext import gettext as _7from gettext import ngettext89from ._compat import _get_argv_encoding9from ._compat import get_filesystem_encoding10from ._compat import open_stream11from .exceptions import BadParameter12from .utils import format_filename13from .utils import LazyFile14from .utils import safecall1516if t.TYPE_CHECKING:
145 unmodified lines
162163164class FuncParamType(ParamType):165 def __init__(self, func: t.Callable[[t.Any], t.Any]) -> None:165 self.name = func.__name__166 self.name: str = func.__name__167 self.func = func168169 def to_info_dict(self) -> t.Dict[str, t.Any]:170 info_dict = super().to_info_dict()
36 unmodified lines
207 enc = _get_argv_encoding()208 try:209 value = value.decode(enc)210 except UnicodeError:210 fs_enc = get_filesystem_encoding()211 fs_enc = sys.getfilesystemencoding()212 if fs_enc != enc:213 try:214 value = value.decode(fs_enc)215 except UnicodeError:
137 unmodified lines
353354 name = "datetime"355356 def __init__(self, formats: t.Optional[t.Sequence[str]] = None):356 self.formats = formats or ["%Y-%m-%d", "%Y-%m-%dT%H:%M:%S", "%Y-%m-%d %H:%M:%S"]357 self.formats: t.Sequence[str] = formats or [358 "%Y-%m-%d",359 "%Y-%m-%dT%H:%M:%S",360 "%Y-%m-%d %H:%M:%S",361 ]362363 def to_info_dict(self) -> t.Dict[str, t.Any]:364 info_dict = super().to_info_dict()365 info_dict["formats"] = self.formats
300 unmodified lines
666 See :ref:`file-args` for more information.667 """668669 name = "filename"665 envvar_list_splitter = os.path.pathsep670 envvar_list_splitter: t.ClassVar[str] = os.path.pathsep671672 def __init__(673 self,674 mode: str = "r",
12 unmodified lines
687 info_dict = super().to_info_dict()688 info_dict.update(mode=self.mode, encoding=self.encoding)689 return info_dict690686 def resolve_lazy_flag(self, value: t.Any) -> bool:691 def resolve_lazy_flag(self, value: "t.Union[str, os.PathLike[str]]") -> bool:692 if self.lazy is not None:693 return self.lazy689 if value == "-":694 if os.fspath(value) == "-":695 return False696 elif "w" in self.mode:697 return True698 return False699700 def convert(696 self, value: t.Any, param: t.Optional["Parameter"], ctx: t.Optional["Context"]697 ) -> t.Any:698 try:699 if hasattr(value, "read") or hasattr(value, "write"):700 return value701 self,702 value: t.Union[str, "os.PathLike[str]", t.IO[t.Any]],703 param: t.Optional["Parameter"],704 ctx: t.Optional["Context"],705 ) -> t.IO[t.Any]:706 if _is_file_like(value):707 return value708709 value = t.cast("t.Union[str, os.PathLike[str]]", value)710711 try:712 lazy = self.resolve_lazy_flag(value)713714 if lazy:715 lf = LazyFile(
21 unmodified lines
737 ctx.call_on_close(safecall(f.flush))738739 return f740 except OSError as e: # noqa: B014731 self.fail(f"'{os.fsdecode(value)}': {e.strerror}", param, ctx)741 self.fail(f"'{format_filename(value)}': {e.strerror}", param, ctx)742743 def shell_complete(744 self, ctx: "Context", param: "Parameter", incomplete: str745 ) -> t.List["CompletionItem"]:
10 unmodified lines
756757 return [CompletionItem(incomplete, type="file")]758759760def _is_file_like(value: t.Any) -> "te.TypeGuard[t.IO[t.Any]]":761 return hasattr(value, "read") or hasattr(value, "write")762763764class Path(ParamType):765 """The ``Path`` type is similar to the :class:`File` type, but766 returns the filename instead of an open file. Various checks can be767 enabled to validate the type of file and permissions.
25 unmodified lines
793 .. versionchanged:: 6.0794 Added the ``allow_dash`` parameter.795 """796783 envvar_list_splitter = os.path.pathsep797 envvar_list_splitter: t.ClassVar[str] = os.path.pathsep798799 def __init__(800 self,801 exists: bool = False,
16 unmodified lines
818 self.allow_dash = allow_dash819 self.type = path_type820821 if self.file_okay and not self.dir_okay:808 self.name = _("file")822 self.name: str = _("file")823 elif self.dir_okay and not self.file_okay:824 self.name = _("directory")825 else:826 self.name = _("path")
9 unmodified lines
836 allow_dash=self.allow_dash,837 )838 return info_dict839826 def coerce_path_result(self, rv: t.Any) -> t.Any:827 if self.type is not None and not isinstance(rv, self.type):840 def coerce_path_result(841 self, value: "t.Union[str, os.PathLike[str]]"842 ) -> "t.Union[str, bytes, os.PathLike[str]]":843 if self.type is not None and not isinstance(value, self.type):844 if self.type is str:829 rv = os.fsdecode(rv)845 return os.fsdecode(value)846 elif self.type is bytes:831 rv = os.fsencode(rv)847 return os.fsencode(value)848 else:833 rv = self.type(rv)849 return t.cast("os.PathLike[str]", self.type(value))850835 return rv851 return value852853 def convert(838 self, value: t.Any, param: t.Optional["Parameter"], ctx: t.Optional["Context"]839 ) -> t.Any:854 self,855 value: "t.Union[str, os.PathLike[str]]",856 param: t.Optional["Parameter"],857 ctx: t.Optional["Context"],858 ) -> "t.Union[str, bytes, os.PathLike[str]]":859 rv = value860861 is_dash = self.file_okay and self.allow_dash and rv in (b"-", "-")862
11 unmodified lines
874 if not self.exists:875 return self.coerce_path_result(rv)876 self.fail(877 _("{name} {filename!r} does not exist.").format(859 name=self.name.title(), filename=os.fsdecode(value)878 name=self.name.title(), filename=format_filename(value)879 ),880 param,881 ctx,882 )883884 if not self.file_okay and stat.S_ISREG(st.st_mode):885 self.fail(886 _("{name} {filename!r} is a file.").format(868 name=self.name.title(), filename=os.fsdecode(value)887 name=self.name.title(), filename=format_filename(value)888 ),889 param,890 ctx,891 )892 if not self.dir_okay and stat.S_ISDIR(st.st_mode):893 self.fail(894 _("{name} '{filename}' is a directory.").format(876 name=self.name.title(), filename=os.fsdecode(value)895 name=self.name.title(), filename=format_filename(value)896 ),897 param,898 ctx,899 )900901 if self.readable and not os.access(rv, os.R_OK):902 self.fail(903 _("{name} {filename!r} is not readable.").format(885 name=self.name.title(), filename=os.fsdecode(value)904 name=self.name.title(), filename=format_filename(value)905 ),906 param,907 ctx,908 )909910 if self.writable and not os.access(rv, os.W_OK):911 self.fail(912 _("{name} {filename!r} is not writable.").format(894 name=self.name.title(), filename=os.fsdecode(value)913 name=self.name.title(), filename=format_filename(value)914 ),915 param,916 ctx,917 )918919 if self.executable and not os.access(value, os.X_OK):920 self.fail(921 _("{name} {filename!r} is not executable.").format(903 name=self.name.title(), filename=os.fsdecode(value)922 name=self.name.title(), filename=format_filename(value)923 ),924 param,925 ctx,926 )
33 unmodified lines
960 :param types: a list of types that should be used for the tuple items.961 """962963 def __init__(self, types: t.Sequence[t.Union[t.Type[t.Any], ParamType]]) -> None:945 self.types = [convert_type(ty) for ty in types]964 self.types: t.Sequence[ParamType] = [convert_type(ty) for ty in types]965966 def to_info_dict(self) -> t.Dict[str, t.Any]:967 info_dict = super().to_info_dict()968 info_dict["types"] = [t.to_info_dict() for t in self.types]
121 unmodified lines
modified:src/click/utils.py+56 added-17 removed
2 unmodified lines
3import sys4import typing as t5from functools import update_wrapper6from types import ModuleType7from types import TracebackType89from ._compat import _default_text_stderr10from ._compat import _default_text_stdout11from ._compat import _find_binary_writer12from ._compat import auto_wrap_for_ansi13from ._compat import binary_streams13from ._compat import get_filesystem_encoding14from ._compat import open_stream15from ._compat import should_strip_ansi16from ._compat import strip_ansi17from ._compat import text_streams
28 unmodified lines
46def make_str(value: t.Any) -> str:47 """Converts a value into a valid string."""48 if isinstance(value, bytes):49 try:50 return value.decode(get_filesystem_encoding())50 return value.decode(sys.getfilesystemencoding())51 except UnicodeError:52 return value.decode("utf-8", "replace")53 return str(value)54
56 unmodified lines
111 """112113 def __init__(114 self,115 filename: str,115 filename: t.Union[str, "os.PathLike[str]"],116 mode: str = "r",117 encoding: t.Optional[str] = None,118 errors: t.Optional[str] = "strict",119 atomic: bool = False,120 ):121 self.name = filename121 self.name: str = os.fspath(filename)122 self.mode = mode123 self.encoding = encoding124 self.errors = errors125 self.atomic = atomic126 self._f: t.Optional[t.IO[t.Any]]127 self.should_close: bool128128 if filename == "-":129 if self.name == "-":130 self._f, self.should_close = open_stream(filename, mode, encoding, errors)131 else:132 if "r" in mode:133 # Open and close the file in case we're opening it for
8 unmodified lines
142143 def __repr__(self) -> str:144 if self._f is not None:145 return repr(self._f)145 return f"<unopened file '{self.name}' {self.mode}>"146 return f"<unopened file '{format_filename(self.name)}' {self.mode}>"147148 def open(self) -> t.IO[t.Any]:149 """Opens the file if it's not yet open. This call might fail with150 a :exc:`FileError`. Not handling this error will produce an error
26 unmodified lines
177178 def __enter__(self) -> "LazyFile":179 return self180180 def __exit__(self, *_: t.Any) -> None:181 def __exit__(182 self,183 exc_type: t.Optional[t.Type[BaseException]],184 exc_value: t.Optional[BaseException],185 tb: t.Optional[TracebackType],186 ) -> None:187 self.close_intelligently()188189 def __iter__(self) -> t.Iterator[t.AnyStr]:190 self.open()
1 unmodified line
192193194class KeepOpenFile:195 def __init__(self, file: t.IO[t.Any]) -> None:190 self._file = file196 self._file: t.IO[t.Any] = file197198 def __getattr__(self, name: str) -> t.Any:199 return getattr(self._file, name)200201 def __enter__(self) -> "KeepOpenFile":202 return self203198 def __exit__(self, *_: t.Any) -> None:204 def __exit__(205 self,206 exc_type: t.Optional[t.Type[BaseException]],207 exc_value: t.Optional[BaseException],208 tb: t.Optional[TracebackType],209 ) -> None:210 pass211212 def __repr__(self) -> str:213 return repr(self._file)
52 unmodified lines
266 file = _default_text_stderr()267 else:268 file = _default_text_stdout()269270 # There are no standard streams attached to write to. For example,271 # pythonw on Windows.272 if file is None:273 return274275 # Convert non bytes/text into the native string type.276 if message is not None and not isinstance(message, (str, bytes, bytearray)):277 out: t.Optional[t.Union[str, bytes]] = str(message)278 else:
122 unmodified lines
401 return f402403404def format_filename(389 filename: t.Union[str, bytes, "os.PathLike[t.AnyStr]"], shorten: bool = False405 filename: "t.Union[str, bytes, os.PathLike[str], os.PathLike[bytes]]",406 shorten: bool = False,407) -> str:391 """Formats a filename for user display. The main purpose of this392 function is to ensure that the filename can be displayed at all. This393 will decode the filename to unicode if necessary in a way that it will394 not fail. Optionally, it can shorten the filename to not include the395 full path to the filename.408 """Format a filename as a string for display. Ensures the filename can be409 displayed by replacing any invalid bytes or surrogate escapes in the name410 with the replacement character ``�``.411412 Invalid bytes or surrogate escapes will raise an error when written to a413 stream with ``errors="strict". This will typically happen with ``stdout``414 when the locale is something like ``en_GB.UTF-8``.415416 Many scenarios *are* safe to write surrogates though, due to PEP 538 and417 PEP 540, including:418419 - Writing to ``stderr``, which uses ``errors="backslashreplace"``.420 - The system has ``LANG=C.UTF-8``, ``C``, or ``POSIX``. Python opens421 stdout and stderr with ``errors="surrogateescape"``.422 - None of ``LANG/LC_*`` are set. Python assumes ``LANG=C.UTF-8``.423 - Python is started in UTF-8 mode with ``PYTHONUTF8=1`` or ``-X utf8``.424 Python opens stdout and stderr with ``errors="surrogateescape"``.425426 :param filename: formats a filename for UI display. This will also convert427 the filename into unicode without failing.428 :param shorten: this optionally shortens the filename to strip of the429 path that leads up to it.430 """431 if shorten:432 filename = os.path.basename(filename)433 else:434 filename = os.fspath(filename)435405 return os.fsdecode(filename)436 if isinstance(filename, bytes):437 filename = filename.decode(sys.getfilesystemencoding(), "replace")438 else:439 filename = filename.encode("utf-8", "surrogateescape").decode(440 "utf-8", "replace"441 )442443 return filename444445446def get_app_dir(app_name: str, roaming: bool = True, force_posix: bool = False) -> str:447 r"""Returns the config folder for the application. The default behavior448 is to return whatever is most appropriate for the operating system.449
98 unmodified lines
548549 # The value of __package__ indicates how Python was called. It may550 # not exist if a setuptools script is installed as an egg. It may be551 # set incorrectly for entry points created with pip on Windows.552 # It is set to "" inside a Shiv or PEX zipapp.514 if getattr(_main, "__package__", None) is None or (553 if getattr(_main, "__package__", None) in {None, ""} or (554 os.name == "nt"555 and _main.__package__ == ""556 and not os.path.exists(path)557 and os.path.exists(f"{path}.exe")
67 unmodified lines
modified:tests/conftest.py-19 removed
1import os2import tempfile31import pytest23from click.testing import CliRunner456@pytest.fixture(scope="function")7def runner(request):8 return CliRunner()121314def _check_symlinks_supported():15 with tempfile.TemporaryDirectory(prefix="click-pytest-") as tempdir:16 target = os.path.join(tempdir, "target")17 open(target, "w").close()18 link = os.path.join(tempdir, "link")1920 try:21 os.symlink(target, link)22 return True23 except OSError:24 return False252627symlinks_supported = _check_symlinks_supported()
modified:tests/test_arguments.py+20 added
379 unmodified lines
380381 result = runner.invoke(cli, ["arg1", "cmd", "arg2", "subcmd", "--help"])382 assert not result.exception383 assert "Usage: cli ARG1 cmd ARG2 subcmd [OPTIONS]" in result.output384385386def test_when_argument_decorator_is_used_multiple_times_cls_is_preserved():387 class CustomArgument(click.Argument):388 pass389390 reusable_argument = click.argument("art", cls=CustomArgument)391392 @click.command()393 @reusable_argument394 def foo(arg):395 pass396397 @click.command()398 @reusable_argument399 def bar(arg):400 pass401402 assert isinstance(foo.params[0], CustomArgument)403 assert isinstance(bar.params[0], CustomArgument)
modified:tests/test_command_decorators.py+20 added
9 unmodified lines
10 assert result.exception is None11 assert result.output == "hello\n"121314def test_custom_command_no_parens(runner):15 class CustomCommand(click.Command):16 pass1718 class CustomGroup(click.Group):19 command_class = CustomCommand2021 @click.group(cls=CustomGroup)22 def grp():23 pass2425 @grp.command26 def cli():27 click.echo("hello custom command class")2829 result = runner.invoke(cli)30 assert result.exception is None31 assert result.output == "hello custom command class\n"323334def test_group_no_parens(runner):35 @click.group36 def grp():37 click.echo("grp1")
34 unmodified lines
modified:tests/test_commands.py+12 added-14 removed
93 unmodified lines
94 is not None95 )969798def test_help_truncation(runner):99 @click.command()100 def cli():101 """This is a command with truncated help.102 \f103104 This text should be truncated.105 """106107 result = runner.invoke(cli, ["--help"])108 assert result.exit_code == 0109 assert "This is a command with truncated help." in result.output11011198def test_no_args_is_help(runner):99 @click.command(no_args_is_help=True)100 def cli():101 pass
294 unmodified lines
396 pass397398 runner.invoke(group, ["command1"])399 assert opt_prefixes == {"-", "--", "~", "+"}400401402@pytest.mark.parametrize("exc", (EOFError, KeyboardInterrupt))403def test_abort_exceptions_with_disabled_standalone_mode(runner, exc):404 @click.command()405 def cli():406 raise exc("catch me!")407408 rv = runner.invoke(cli, standalone_mode=False)409 assert rv.exit_code == 1410 assert isinstance(rv.exception.__cause__, exc)411 assert rv.exception.__cause__.args == ("catch me!",)
modified:tests/test_defaults.py+21 added
36 unmodified lines
3738 result = runner.invoke(cli, [])39 assert not result.exception40 assert result.output.splitlines() == ["<1|2>", "<3|4>"]414243def test_multiple_flag_default(runner):44 """Default default for flags when multiple=True should be empty tuple."""4546 @click.command47 # flag due to secondary token48 @click.option("-y/-n", multiple=True)49 # flag due to is_flag50 @click.option("-f", is_flag=True, multiple=True)51 # flag due to flag_value52 @click.option("-v", "v", flag_value=1, multiple=True)53 @click.option("-q", "v", flag_value=-1, multiple=True)54 def cli(y, f, v):55 return y, f, v5657 result = runner.invoke(cli, standalone_mode=False)58 assert result.return_value == ((), (), ())5960 result = runner.invoke(cli, ["-y", "-n", "-f", "-v", "-q"], standalone_mode=False)61 assert result.return_value == ((True, False), (True,), (1, -1))
modified:tests/test_formatting.py+20 added
294 unmodified lines
295 " --help Show this message and exit.",296 ]297298299def test_truncating_docstring_no_help(runner):300 @click.command()301 @click.pass_context302 def cli(ctx):303 """304 \f305306 This text should be truncated.307 """308309 result = runner.invoke(cli, ["--help"], terminal_width=60)310 assert not result.exception311 assert result.output.splitlines() == [312 "Usage: cli [OPTIONS]",313 "",314 "Options:",315 " --help Show this message and exit.",316 ]317318319def test_removing_multiline_marker(runner):320 @click.group()321 def cli():322 pass
46 unmodified lines
modified:tests/test_options.py-4 removed
909 unmodified lines
910 ("kwargs", "message"),911 [912 ({"count": True, "multiple": True}, "'count' is not valid with 'multiple'."),913 ({"count": True, "is_flag": True}, "'count' is not valid with 'is_flag'."),914 (915 {"multiple": True, "is_flag": True},916 "'multiple' is not valid with 'is_flag', use 'count'.",917 ),914 ],915)916def test_invalid_flag_combinations(runner, kwargs, message):917 with pytest.raises(TypeError) as e:
3 unmodified lines
modified:tests/test_types.py+109 added-5 removed
1import os.path2import pathlib3import tempfile45import pytest5from conftest import symlinks_supported67import click8from click import FileError91011@pytest.mark.parametrize(12 ("type", "value", "expect"),
91 unmodified lines
104 assert result.exception is None105 assert result.return_value == expect106107108def _symlinks_supported():109 with tempfile.TemporaryDirectory(prefix="click-pytest-") as tempdir:110 target = os.path.join(tempdir, "target")111 open(target, "w").close()112 link = os.path.join(tempdir, "link")113114 try:115 os.symlink(target, link)116 return True117 except OSError:118 return False119120121@pytest.mark.skipif(108 not symlinks_supported, reason="The current OS or FS doesn't support symlinks."122 not _symlinks_supported(), reason="The current OS or FS doesn't support symlinks."123)124def test_path_resolve_symlink(tmp_path, runner):125 test_file = tmp_path / "file"112 test_file_str = os.fsdecode(test_file)126 test_file_str = os.fspath(test_file)127 test_file.write_text("")128129 path_type = click.Path(resolve_path=True)130 param = click.Argument(["a"], type=path_type)
3 unmodified lines
134 test_dir.mkdir()135136 abs_link = test_dir / "abs"137 abs_link.symlink_to(test_file)124 abs_rv = path_type.convert(os.fsdecode(abs_link), param, ctx)138 abs_rv = path_type.convert(os.fspath(abs_link), param, ctx)139 assert abs_rv == test_file_str140141 rel_link = test_dir / "rel"142 rel_link.symlink_to(pathlib.Path("..") / "file")129 rel_rv = path_type.convert(os.fsdecode(rel_link), param, ctx)143 rel_rv = path_type.convert(os.fspath(rel_link), param, ctx)144 assert rel_rv == test_file_str145146147def _non_utf8_filenames_supported():148 with tempfile.TemporaryDirectory(prefix="click-pytest-") as tempdir:149 try:150 f = open(os.path.join(tempdir, "\udcff"), "w")151 except OSError:152 return False153154 f.close()155 return True156157158@pytest.mark.skipif(159 not _non_utf8_filenames_supported(),160 reason="The current OS or FS doesn't support non-UTF-8 filenames.",161)162def test_path_surrogates(tmp_path, monkeypatch):163 monkeypatch.chdir(tmp_path)164 type = click.Path(exists=True)165 path = pathlib.Path("\udcff")166167 with pytest.raises(click.BadParameter, match="'�' does not exist"):168 type.convert(path, None, None)169170 type = click.Path(file_okay=False)171 path.touch()172173 with pytest.raises(click.BadParameter, match="'�' is a file"):174 type.convert(path, None, None)175176 path.unlink()177 type = click.Path(dir_okay=False)178 path.mkdir()179180 with pytest.raises(click.BadParameter, match="'�' is a directory"):181 type.convert(path, None, None)182183 path.rmdir()184185 def no_access(*args, **kwargs):186 """Test environments may be running as root, so we have to fake the result of187 the access tests that use os.access188 """189 p = args[0]190 assert p == path, f"unexpected os.access call on file not under test: {p!r}"191 return False192193 path.touch()194 type = click.Path(readable=True)195196 with pytest.raises(click.BadParameter, match="'�' is not readable"):197 with monkeypatch.context() as m:198 m.setattr(os, "access", no_access)199 type.convert(path, None, None)200201 type = click.Path(readable=False, writable=True)202203 with pytest.raises(click.BadParameter, match="'�' is not writable"):204 with monkeypatch.context() as m:205 m.setattr(os, "access", no_access)206 type.convert(path, None, None)207208 type = click.Path(readable=False, executable=True)209210 with pytest.raises(click.BadParameter, match="'�' is not executable"):211 with monkeypatch.context() as m:212 m.setattr(os, "access", no_access)213 type.convert(path, None, None)214215 path.unlink()216217218@pytest.mark.parametrize(219 "type",220 [221 click.File(mode="r"),222 click.File(mode="r", lazy=True),223 ],224)225def test_file_surrogates(type, tmp_path):226 path = tmp_path / "\udcff"227228 with pytest.raises(click.BadParameter, match="�': No such file or directory"):229 type.convert(path, None, None)230231232def test_file_error_surrogates():233 message = FileError(filename="\udcff").format_message()234 assert message == "Could not open file '�': unknown error"
modified:tests/test_utils.py+11 added-4 removed
41 unmodified lines
42 click.echo("hello", file=f)43 assert f.getvalue() == "hello\n"444546def test_echo_no_streams(monkeypatch, runner):47 """echo should not fail when stdout and stderr are None with pythonw on Windows."""48 with runner.isolation():49 sys.stdout = None50 sys.stderr = None51 click.echo("test")52 click.echo("test", err=True)535455@pytest.mark.parametrize(56 ("styles", "ref"),57 [58 ({"fg": "black"}, "\x1b[30mx y\x1b[0m"),
47 unmodified lines
106 assert click.format_filename(b"foo.txt") == "foo.txt"107 assert click.format_filename(b"/x/foo.txt") == "/x/foo.txt"108 assert click.format_filename("/x/foo.txt") == "/x/foo.txt"109 assert click.format_filename("/x/foo.txt", shorten=True) == "foo.txt"110 assert click.format_filename(b"/x/\xff.txt", shorten=True) == "�.txt"111102 # filesystem encoding on windows permits this.103 if not WIN:104 assert click.format_filename(b"/x/foo\xff.txt", shorten=True) == "foo\udcff.txt"112106113def test_prompts(runner):114 @click.command()115 def test():116 if click.confirm("Foo"):
334 unmodified lines
451 (str(pathlib.Path("/foo/bar/example.py")), None, "example.py"),452 ("example", None, "example"),453 (str(pathlib.Path("example/__main__.py")), "example", "python -m example"),454 (str(pathlib.Path("example/cli.py")), "example", "python -m example.cli"),455 (str(pathlib.Path("./example")), "", "example"),456 ],457)458def test_detect_program_name(path, main, expected):459 assert click.utils._detect_program_name(path, _main=MockMain(main)) == expected
48 unmodified lines
modified:.pre-commit-config.yaml+1 added-1 removed
1 unmodified line
2 autoupdate_branch: "8.1.x"3 autoupdate_schedule: monthly4repos:5 - repo: https://github.com/asottile/pyupgrade6 rev: v3.7.06 rev: v3.8.07 hooks:8 - id: pyupgrade9 args: ["--py37-plus"]10 - repo: https://github.com/asottile/reorder-python-imports
21 unmodified lines
modified:CHANGES.rst+26 added-3 removed
11 unmodified lines
1213Version 8.1.414-------------1516Unreleased16Released 2023-07-061718- Replace all ``typing.Dict`` occurrences to ``typing.MutableMapping`` for19 parameter hints. :issue:`2255`19 parameter hints. :issue:`2255`20- Improve type hinting for decorators and give all generic types parameters.21 :issue:`2398`22- Fix return value and type signature of `shell_completion.add_completion_class` function. :pr:`2421`22- Fix return value and type signature of `shell_completion.add_completion_class`23 function. :pr:`2421`24- Bash version detection doesn't fail on Windows. :issue:`2461`25- Completion works if there is a dot (``.``) in the program name. :issue:`2166`26- Improve type annotations for pyright type checker. :issue:`2268`27- Improve responsiveness of ``click.clear()``. :issue:`2284`28- Improve command name detection when using Shiv or PEX. :issue:`2332`29- Avoid showing empty lines if command help text is empty. :issue:`2368`30- ZSH completion script works when loaded from ``fpath``. :issue:`2344`.31- ``EOFError`` and ``KeyboardInterrupt`` tracebacks are not suppressed when32 ``standalone_mode`` is disabled. :issue:`2380`33- ``@group.command`` does not fail if the group was created with a custom34 ``command_class``. :issue:`2416`35- ``multiple=True`` is allowed for flag options again and does not require36 setting ``default=()``. :issue:`2246, 2292, 2295`37- Make the decorators returned by ``@argument()`` and ``@option()`` reusable when the38 ``cls`` parameter is used. :issue:`2294`39- Don't fail when writing filenames to streams with strict errors. Replace invalid40 bytes with the replacement character (``�``). :issue:`2395`41- Remove unnecessary attempt to detect MSYS2 environment. :issue:`2355`42- Remove outdated and unnecessary detection of App Engine environment. :pr:`2554`43- ``echo()`` does not fail when no streams are attached, such as with ``pythonw`` on44 Windows. :issue:`2415`45- Argument with ``expose_value=False`` do not cause completion to fail. :issue:`2336`464748Version 8.1.349-------------
1040 unmodified lines