Skip to content
Myr

Merge branch '8.0.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 e430161, d607120 · Browse files · 18 files+172 added−66 removed
This commit

State

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

Diff stats

18 files+172 added−66 removed

  • tests:+52 added−1 removed
  • other:+120 added−65 removed

18 files+172 added−66 removed

modified:docs/advanced.rst+5 added-1 removed
33 unmodified lines
3435.. click:example::3637 class AliasedGroup(click.Group):3838 def get_command(self, ctx, cmd_name):39 rv = click.Group.get_command(self, ctx, cmd_name)40 if rv is not None:41 return rv
4 unmodified lines
46 elif len(matches) == 1:47 return click.Group.get_command(self, ctx, matches[0])48 ctx.fail(f"Too many matches: {', '.join(sorted(matches))}")4950 def resolve_command(self, ctx, args):51 # always return the full command name52 _, cmd, args = super().resolve_command(ctx, args)53 return cmd.name, cmd, args5455And it can then be used like this:5657.. click:example::58
430 unmodified lines
modified:docs/parameters.rst+8 added-7 removed
116 unmodified lines
117 class BasedIntParamType(click.ParamType):118 name = "integer"119120 def convert(self, value, param, ctx):121 if isinstance(value, int):122 return value123124 try:125 if value[:2].lower() == "0x":126 return int(value[2:], 16)127 elif value[:1] == "0":128 return int(value, 8)129 return int(value, 10)127 except TypeError:128 self.fail(129 "expected string for int() conversion, got "130 f"{value!r} of type {type(value).__name__}",131 param,132 ctx,133 )130 except ValueError:131 self.fail(f"{value!r} is not a valid integer", param, ctx)132133 BASED_INT = BasedIntParamType()
1 unmodified line
135The :attr:`~ParamType.name` attribute is optional and is used for136documentation. Call :meth:`~ParamType.fail` if conversion fails. The137``param`` and ``ctx`` arguments may be ``None`` in some cases such as138prompts.139140Values from user input or the command line will be strings, but default141values and Python arguments may already be the correct type. The custom142type should check at the top if the value is already valid and pass it143through to support those cases.
modified:examples/aliases/aliases.py+5 added
65 unmodified lines
66 elif len(matches) == 1:67 return click.Group.get_command(self, ctx, matches[0])68 ctx.fail(f"Too many matches: {', '.join(sorted(matches))}")6970 def resolve_command(self, ctx, args):71 # always return the command's name, not the alias72 _, cmd, args = super().resolve_command(ctx, args)73 return cmd.name, cmd, args747576def read_config(ctx, param, value):77 """Callback that is used whenever --config is passed. We use this to78 always load the correct config. This means that the config is loaded79 even if the group itself never executes so our aliases stay always
64 unmodified lines
modified:requirements/dev.txt-4 removed
34 unmodified lines
35idna==2.1036 # via requests37imagesize==1.2.038 # via sphinx39importlib-metadata==4.0.140 # via -r requirements/tests.in39iniconfig==1.1.140 # via pytest41jinja2==2.11.342 # via sphinx
89 unmodified lines
132virtualenv==20.4.6133 # via134 # pre-commit135 # tox138zipp==3.4.1139 # via importlib-metadata136137# The following packages are considered to be unsafe in a requirements file:138# pip139# setuptools
modified:requirements/tests.in-1 removed
1pytest2importlib_metadata
modified:requirements/tests.txt-4 removed
4 unmodified lines
5# pip-compile requirements/tests.in6#7attrs==21.2.08 # via pytest9importlib-metadata==4.0.110 # via -r requirements/tests.in9iniconfig==1.1.110 # via pytest11packaging==20.912 # via pytest
6 unmodified lines
19pytest==6.2.420 # via -r requirements/tests.in21toml==0.10.222 # via pytest25zipp==3.4.126 # via importlib-metadata
modified:src/click/_termui_impl.py+4 added-4 removed
30 unmodified lines
31 BEFORE_BAR = "\r\033[?25l"32 AFTER_BAR = "\033[?25h\n"333435class ProgressBar:35class ProgressBar(t.Generic[V]):36 def __init__(37 self,38 iterable: t.Optional[t.Iterable[V]],39 length: t.Optional[int] = None,
9 unmodified lines
49 file: t.Optional[t.TextIO] = None,50 color: t.Optional[bool] = None,51 update_min_steps: int = 1,52 width: int = 30,53 ):53 ) -> None:54 self.fill_char = fill_char55 self.empty_char = empty_char56 self.bar_template = bar_template57 self.info_sep = info_sep
42 unmodified lines
100101 def __exit__(self, exc_type, exc_value, tb): # type: ignore102 self.render_finish()103104 def __iter__(self) -> t.Iterable[V]:104 def __iter__(self) -> t.Iterator[V]:105 if not self.entered:106 raise RuntimeError("You need to use progress bars in a with block.")107 self.render_progress()108 return self.generator()
3 unmodified lines
112 # returned by iter(self); use that to define next(). This works113 # because `self.iter` is an iterable consumed by that generator,114 # so it is re-entry safe. Calling `next(self.generator())`115 # twice works and does "what you want".116 return next(iter(self)) # type: ignore116 return next(iter(self))117118 def render_finish(self) -> None:119 if self.is_hidden:120 return
597 unmodified lines
modified:src/click/core.py+48 added-23 removed
11 unmodified lines
12from gettext import gettext as _13from gettext import ngettext14from itertools import repeat1516from . import types17from ._unicodefun import _verify_python_env18from .exceptions import Abort19from .exceptions import BadParameter20from .exceptions import ClickException
9 unmodified lines
30from .parser import split_opt31from .termui import confirm32from .termui import prompt33from .termui import style33from .types import _NumberRangeBase34from .types import BOOL35from .types import convert_type36from .types import IntRange37from .types import ParamType34from .utils import _detect_program_name35from .utils import _expand_args36from .utils import echo37from .utils import make_default_short_help
954 unmodified lines
992 args: t.Optional[t.Sequence[str]] = None,993 prog_name: t.Optional[str] = None,994 complete_var: t.Optional[str] = None,995 standalone_mode: bool = True,996 windows_expand_args: bool = True,997 **extra: t.Any,998 ) -> t.Any:999 """This is the way to invoke a script with all the bells and1000 whistles as a command line application. This will always terminate
20 unmodified lines
1021 this is set to `False` they will be1022 propagated to the caller and the return1023 value of this function is the return value1024 of :meth:`invoke`.1025 :param windows_expand_args: Expand glob patterns, user dir, and1026 env vars in command line args on Windows.1027 :param extra: extra keyword arguments are forwarded to the context1028 constructor. See :class:`Context` for more information.10291030 .. versionchanged:: 8.0.11031 Added the ``windows_expand_args`` parameter to allow1032 disabling command line arg expansion on Windows.10331034 .. versionchanged:: 8.01035 When taking arguments from ``sys.argv`` on Windows, glob1036 patterns, user dir, and env vars are expanded.1037
6 unmodified lines
10441045 if args is None:1046 args = sys.argv[1:]10471045 if os.name == "nt":1048 if os.name == "nt" and windows_expand_args:1049 args = _expand_args(args)1050 else:1051 args = list(args)1052
670 unmodified lines
1723 if cmd is None and not ctx.resilient_parsing:1724 if split_opt(cmd_name)[0]:1725 self.parse_args(ctx, ctx.args)1726 ctx.fail(_("No such command {name!r}.").format(name=original_cmd_name))1724 return cmd.name if cmd else None, cmd, args[1:]1727 return cmd_name if cmd else None, cmd, args[1:]17281729 def get_command(self, ctx: Context, cmd_name: str) -> t.Optional[Command]:1730 """Given a context and a command name, this returns a1731 :class:`Command` object if it exists or returns `None`.
280 unmodified lines
20122013 def __init__(2014 self,2015 param_decls: t.Optional[t.Sequence[str]] = None,2013 type: t.Optional[t.Union["ParamType", t.Any]] = None,2016 type: t.Optional[t.Union[types.ParamType, t.Any]] = None,2017 required: bool = False,2018 default: t.Optional[t.Union[t.Any, t.Callable[[], t.Any]]] = None,2019 callback: t.Optional[t.Callable[[Context, "Parameter", t.Any], t.Any]] = None,2020 nargs: t.Optional[int] = None,
16 unmodified lines
2037 ) -> None:2038 self.name, self.opts, self.secondary_opts = self._parse_decls(2039 param_decls or (), expose_value2040 )2041 self.type = types.convert_type(type, default)20422039 self.type = convert_type(type, default)20402043 # Default nargs to what the type tells us if we have that2044 # information available.2045 if nargs is None:2046 if self.type.is_composite:
155 unmodified lines
2202 :param ctx: Current context.2203 :param call: If the default is a callable, call it. Disable to2204 return the callable instead.22052206 .. versionchanged:: 8.0.12207 Type casting can fail in resilient parsing mode. Invalid2208 defaults will not prevent showing help text.22092210 .. versionchanged:: 8.02211 Looks at ``ctx.default_map`` first.22122213 .. versionchanged:: 8.0
10 unmodified lines
2224 return value22252226 value = value()22272228 try:2222 return self.type_cast_value(ctx, value)2229 return self.type_cast_value(ctx, value)2230 except BadParameter:2231 if ctx.resilient_parsing:2232 return value22332234 raise22352236 def add_to_parser(self, parser: OptionParser, ctx: Context) -> None:2237 raise NotImplementedError()22382239 def consume_value(
210 unmodified lines
2450 variable in case a prefix is defined on the2451 context.2452 :param help: the help string.2453 :param hidden: hide this option from help outputs.24542455 .. versionchanged:: 8.0.12456 ``type`` is detected from ``flag_value`` if given.2457 """24582459 param_type_name = "option"2460
9 unmodified lines
2470 flag_value: t.Optional[t.Any] = None,2471 multiple: bool = False,2472 count: bool = False,2473 allow_from_autoenv: bool = True,2459 type: t.Optional[t.Union["ParamType", t.Any]] = None,2474 type: t.Optional[t.Union[types.ParamType, t.Any]] = None,2475 help: t.Optional[str] = None,2476 hidden: bool = False,2477 show_choices: bool = True,2478 show_envvar: bool = False,
42 unmodified lines
25212522 if flag_value is None:2523 flag_value = not self.default25242525 if is_flag and type is None:2526 # Re-guess the type from the flag value instead of the2527 # default.2528 self.type = types.convert_type(None, flag_value)25292530 self.is_flag: bool = is_flag2531 self.is_bool_flag = isinstance(self.type, types.BoolParamType)2532 self.flag_value: t.Any = flag_value25332513 if self.is_flag and isinstance(self.flag_value, bool) and type in [None, bool]:2514 self.type: "ParamType" = BOOL2515 self.is_bool_flag = True2516 else:2517 self.is_bool_flag = False25182534 # Counting2535 self.count = count2536 if count:2537 if type is None:2523 self.type = IntRange(min=0)2538 self.type = types.IntRange(min=0)2539 if default_is_missing:2540 self.default = 025412542 self.allow_from_autoenv = allow_from_autoenv
173 unmodified lines
2716 else ", ".join(str(d) for d in envvar)2717 )2718 extra.append(_("env var: {var}").format(var=var_str))27192720 # Temporarily enable resilient parsing to avoid type casting2721 # failing for the default. Might be possible to extend this to2722 # help formatting in general.2723 resilient = ctx.resilient_parsing2724 ctx.resilient_parsing = True27252726 try:2705 default_value = self.get_default(ctx, call=False)2727 default_value = self.get_default(ctx, call=False)2728 finally:2729 ctx.resilient_parsing = resilient27302731 show_default_is_str = isinstance(self.show_default, str)27322733 if show_default_is_str or (2734 default_value is not None and (self.show_default or ctx.show_default)2735 ):2736 if show_default_is_str:2712 default_string: t.Union[str, t.Any] = f"({self.show_default})"2737 default_string = f"({self.show_default})"2738 elif isinstance(default_value, (list, tuple)):2739 default_string = ", ".join(str(d) for d in default_value)2740 elif callable(default_value):2741 default_string = _("(dynamic)")
3 unmodified lines
2745 default_string = split_opt(2746 (self.opts if self.default else self.secondary_opts)[0]2747 )[1]2748 else:2724 default_string = default_value2749 default_string = str(default_value)27502751 extra.append(_("default: {default}").format(default=default_string))27522728 if isinstance(self.type, _NumberRangeBase):2753 if isinstance(self.type, types._NumberRangeBase):2754 range_str = self.type._describe_range()27552756 if range_str:2757 extra.append(range_str)
200 unmodified lines
modified:src/click/decorators.py+5 added-10 removed
328 unmodified lines
329 Add the ``package_name`` parameter, and the ``%(package)s``330 value for messages.331332 .. versionchanged:: 8.0333 Use :mod:`importlib.metadata` instead of ``pkg_resources``.333 Use :mod:`importlib.metadata` instead of ``pkg_resources``. The334 version is detected based on the package name, not the entry335 point name. The Python package name must match the installed336 package name, or be passed with ``package_name=``.337 """338 if message is None:339 message = _("%(prog)s, version %(version)s")340
31 unmodified lines
372 try:373 from importlib import metadata # type: ignore374 except ImportError:375 # Python < 3.8373 try:374 import importlib_metadata as metadata # type: ignore376 import importlib_metadata as metadata # type: ignore375 except ImportError:376 metadata = None377378 if metadata is None:379 raise RuntimeError(380 "Install 'importlib_metadata' to get the version on Python < 3.8."381 )382378 try:379 version = metadata.version(package_name) # type: ignore380 except metadata.PackageNotFoundError: # type: ignore381 raise RuntimeError(
56 unmodified lines
modified:src/click/parser.py+3 added-1 removed
231 unmodified lines
232 name=self.dest, nargs=self.nargs233 )234 )235236 if self.nargs == -1 and self.obj.envvar is not None:236 if self.nargs == -1 and self.obj.envvar is not None and value == ():237 # Replace empty tuple with None so that a value from the238 # environment may be tried.239 value = None240241 state.opts[self.dest] = value # type: ignore242 state.order.append(self.obj)
287 unmodified lines
modified:src/click/termui.py+1 added-1 removed
316 unmodified lines
317 width: int = 36,318 file: t.Optional[t.TextIO] = None,319 color: t.Optional[bool] = None,320 update_min_steps: int = 1,321) -> "ProgressBar":321) -> "ProgressBar[V]":322 """This function creates an iterable context manager that can be used323 to iterate over something while showing a progress bar. It will324 either iterate over the `iterable` or `length` items (that are counted325 up). While iteration happens, this function will print a rendered
482 unmodified lines
modified:src/click/types.py+1 added-4 removed
998 unmodified lines
9991000 if ty is float:1001 return FLOAT10021003 # Booleans are only okay if not guessed. For is_flag options with1004 # flag_value, default=True indicates which flag_value is the1005 # default.1006 if ty is bool and not guessed_type:1003 if ty is bool:1004 return BOOL10051006 if guessed_type:1007 return STRING
45 unmodified lines
modified:tests/test_arguments.py+13 added
192 unmodified lines
193 else:194 assert result.return_value == expect195196197def test_nargs_envvar_only_if_values_empty(runner):198 @click.command()199 @click.argument("arg", envvar="X", nargs=-1)200 def cli(arg):201 return arg202203 result = runner.invoke(cli, ["a", "b"], standalone_mode=False)204 assert result.return_value == ("a", "b")205206 result = runner.invoke(cli, env={"X": "a"}, standalone_mode=False)207 assert result.return_value == ("a",)208209210def test_empty_nargs(runner):211 @click.command()212 @click.argument("arg", nargs=-1)213 def cmd(arg):
166 unmodified lines
modified:tests/test_basic.py+17 added
545 unmodified lines
546547 result = runner.invoke(cli, ["--help"])548 assert "Summary line without period" in result.output549 assert "Here is a sentence." not in result.output550551552def test_help_invalid_default(runner):553 cli = click.Command(554 "cli",555 params=[556 click.Option(557 ["-a"],558 type=click.Path(exists=True),559 default="not found",560 show_default=True,561 ),562 ],563 )564 result = runner.invoke(cli, ["--help"])565 assert result.exit_code == 0566 assert "default: not found" in result.output
modified:tests/test_commands.py+14 added
283 unmodified lines
284 class AliasedGroup(click.Group):285 def get_command(self, ctx, cmd_name):286 return push287288 def resolve_command(self, ctx, args):289 _, command, args = super().resolve_command(ctx, args)290 return command.name, command, args291292 cli = AliasedGroup()293294 @cli.command()295 def push():
3 unmodified lines
299 assert not result.exception300 assert result.output.startswith("Usage: root push [OPTIONS]")301302303def test_group_add_command_name(runner):304 cli = click.Group("cli")305 cmd = click.Command("a", params=[click.Option(["-x"], required=True)])306 cli.add_command(cmd, "b")307 # Check that the command is accessed through the registered name,308 # not the original name.309 result = runner.invoke(cli, ["b"], default_map={"b": {"x": 3}})310 assert result.exit_code == 0311312313def test_unprocessed_options(runner):314 @click.command(context_settings=dict(ignore_unknown_options=True))315 @click.argument("args", nargs=-1, type=click.UNPROCESSED)316 @click.option("--verbose", "-v", count=True)
36 unmodified lines
modified:tests/test_options.py+8 added-1 removed
551 unmodified lines
552553554def test_argument_custom_class(runner):555 class CustomArgument(click.Argument):556 def get_default(self, ctx):556 def get_default(self, ctx, call=True):557 """a dumb override of a default value for testing"""558 return "I am a default"559560 @click.command()
194 unmodified lines
755 return opt, a, b756757 result = runner.invoke(cli, args, standalone_mode=False, catch_exceptions=False)758 assert result.return_value == expect759760761def test_type_from_flag_value():762 param = click.Option(["-a", "x"], default=True, flag_value=4)763 assert param.type is click.INT764 param = click.Option(["-b", "x"], flag_value=8)765 assert param.type is click.INT
modified:CHANGES.rst+33 added-4 removed
4 unmodified lines
56Unreleased789Version 8.0.19Version 8.0.210-------------1112Unreleased131415Version 8.0.116-------------1718Released 2021-05-191920- Mark top-level names as exported so type checking understand imports21 in user projects. :issue:`1879`22- Annotate ``Context.obj`` as ``Any`` so type checking allows all23 operations on the arbitrary object. :issue:`1885`24- Fix some types that weren't available in Python 3.6.0. :issue:`1882`25- Fix type checking for iterating over ``ProgressBar`` object.26 :issue:`1892`27- The ``importlib_metadata`` backport package is installed on Python <28 3.8. :issue:`1889`29- Arguments with ``nargs=-1`` only use env var value if no command30 line values are given. :issue:`1903`31- Flag options guess their type from ``flag_value`` if given, like32 regular options do from ``default``. :issue:`1886`33- Added documentation that custom parameter types may be passed34 already valid values in addition to strings. :issue:`1898`35- Resolving commands returns the name that was given, not36 ``command.name``, fixing an unintended change to help text and37 ``default_map`` lookups. When using patterns like ``AliasedGroup``,38 override ``resolve_command`` to change the name that is returned if39 needed. :issue:`1895`40- If a default value is invalid, it does not prevent showing help41 text. :issue:`1889`42- Pass ``windows_expand_args=False`` when calling the main command to43 disable pattern expansion on Windows. There is no way to escape44 patterns in CMD, so if the program needs to pass them on as-is then45 expansion must be disabled. :issue:`1901`464748Version 8.0.049-------------
9 unmodified lines
59 parameter. :issue:`1264`, :pr:`1329`60- Add an optional parameter to ``ProgressBar.update`` to set the61 ``current_item``. :issue:`1226`, :pr:`1332`62- ``version_option`` uses ``importlib.metadata`` (or the36 ``importlib_metadata`` backport) instead of ``pkg_resources``.37 :issue:`1582`63 ``importlib_metadata`` backport) instead of ``pkg_resources``. The64 version is detected based on the package name, not the entry point65 name. The Python package name must match the installed package66 name, or be passed with ``package_name=``. :issue:`1582`67- If validation fails for a prompt with ``hide_input=True``, the value68 is not shown in the error message. :issue:`1460`69- An ``IntRange`` or ``FloatRange`` option shows the accepted range in70 its help text. :issue:`1525`, :pr:`1303`
78 unmodified lines
149 - The ``autocompletion`` parameter for options and arguments is150 renamed to ``shell_complete``. The function must take151 ``ctx, param, incomplete``, must do matching rather than return152 all values, and must return a list of strings or a list of124 ``ShellComplete``. The old name and behavior is deprecated and153 ``CompletionItem``. The old name and behavior is deprecated and154 will be removed in 8.1.155 - The env var values used to start completion have changed order.156 The shell now comes first, such as ``{shell}_source`` rather157 than ``source_{shell}``, and is always required.
748 unmodified lines
modified:setup.py+7 added-1 removed
1from setuptools import setup23setup(name="click", install_requires=["colorama; platform_system == 'Windows'"])3setup(4 name="click",5 install_requires=[6 "colorama; platform_system == 'Windows'",7 "importlib-metadata; python_version < '3.8'",8 ],9)