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
Provenance
- Commit
29df879- Tree
b4a9204- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent 1
e430161- Parent 2
d607120
18 files changed+172 added−66 removed
modified:docs/advanced.rst+5 added-1 removed
33 unmodified lines34 35 .. click:example::36 37 class AliasedGroup(click.Group):38-38 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 rv4 unmodified lines46 elif len(matches) == 1:47 return click.Group.get_command(self, ctx, matches[0])48 ctx.fail(f"Too many matches: {', '.join(sorted(matches))}")49 50+ 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, args54+55 And it can then be used like this:56 57 .. click:example::58 430 unmodified linesmodified:docs/parameters.rst+8 added-7 removed
116 unmodified lines117 class BasedIntParamType(click.ParamType):118 name = "integer"119 120 def convert(self, value, param, ctx):121+ if isinstance(value, int):122+ return value123+124 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)132 133 BASED_INT = BasedIntParamType()1 unmodified line135 The :attr:`~ParamType.name` attribute is optional and is used for136 documentation. Call :meth:`~ParamType.fail` if conversion fails. The137 ``param`` and ``ctx`` arguments may be ``None`` in some cases such as138 prompts.139+140+Values from user input or the command line will be strings, but default141+values and Python arguments may already be the correct type. The custom142+type should check at the top if the value is already valid and pass it143+through to support those cases.modified:examples/aliases/aliases.py+5 added
65 unmodified lines66 elif len(matches) == 1:67 return click.Group.get_command(self, ctx, matches[0])68 ctx.fail(f"Too many matches: {', '.join(sorted(matches))}")69 70+ 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, args74 75+76 def 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 always64 unmodified linesmodified:requirements/dev.txt-4 removed
34 unmodified lines35 idna==2.1036 # via requests37 imagesize==1.2.038 # via sphinx39-importlib-metadata==4.0.140- # via -r requirements/tests.in39 iniconfig==1.1.140 # via pytest41 jinja2==2.11.342 # via sphinx89 unmodified lines132 virtualenv==20.4.6133 # via134 # pre-commit135 # tox138-zipp==3.4.1139- # via importlib-metadata136 137 # The following packages are considered to be unsafe in a requirements file:138 # pip139 # setuptoolsmodified:requirements/tests.in-1 removed
1 pytest2-importlib_metadatamodified:requirements/tests.txt-4 removed
4 unmodified lines5 # pip-compile requirements/tests.in6 #7 attrs==21.2.08 # via pytest9-importlib-metadata==4.0.110- # via -r requirements/tests.in9 iniconfig==1.1.110 # via pytest11 packaging==20.912 # via pytest6 unmodified lines19 pytest==6.2.420 # via -r requirements/tests.in21 toml==0.10.222 # via pytest25-zipp==3.4.126- # via importlib-metadatamodified:src/click/_termui_impl.py+4 added-4 removed
30 unmodified lines31 BEFORE_BAR = "\r\033[?25l"32 AFTER_BAR = "\033[?25h\n"33 34 35-class ProgressBar:35+class ProgressBar(t.Generic[V]):36 def __init__(37 self,38 iterable: t.Optional[t.Iterable[V]],39 length: t.Optional[int] = None,9 unmodified lines49 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_sep42 unmodified lines100 101 def __exit__(self, exc_type, exc_value, tb): # type: ignore102 self.render_finish()103 104- 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 lines112 # 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))117 118 def render_finish(self) -> None:119 if self.is_hidden:120 return597 unmodified linesmodified:src/click/core.py+48 added-23 removed
11 unmodified lines12 from gettext import gettext as _13 from gettext import ngettext14 from itertools import repeat15 16+from . import types17 from ._unicodefun import _verify_python_env18 from .exceptions import Abort19 from .exceptions import BadParameter20 from .exceptions import ClickException9 unmodified lines30 from .parser import split_opt31 from .termui import confirm32 from .termui import prompt33 from .termui import style33-from .types import _NumberRangeBase34-from .types import BOOL35-from .types import convert_type36-from .types import IntRange37-from .types import ParamType34 from .utils import _detect_program_name35 from .utils import _expand_args36 from .utils import echo37 from .utils import make_default_short_help954 unmodified lines992 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 terminate20 unmodified lines1021 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.1029 1030+ .. versionchanged:: 8.0.11031+ Added the ``windows_expand_args`` parameter to allow1032+ disabling command line arg expansion on Windows.1033+1034 .. versionchanged:: 8.01035 When taking arguments from ``sys.argv`` on Windows, glob1036 patterns, user dir, and env vars are expanded.1037 6 unmodified lines1044 1045 if args is None:1046 args = sys.argv[1:]1047 1045- 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 lines1723 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:]1728 1729 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 lines2012 2013 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 lines2037 ) -> 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)2042 2039- self.type = convert_type(type, default)2040-2043 # 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 lines2202 :param ctx: Current context.2203 :param call: If the default is a callable, call it. Disable to2204 return the callable instead.2205 2206+ .. versionchanged:: 8.0.12207+ Type casting can fail in resilient parsing mode. Invalid2208+ defaults will not prevent showing help text.2209+2210 .. versionchanged:: 8.02211 Looks at ``ctx.default_map`` first.2212 2213 .. versionchanged:: 8.010 unmodified lines2224 return value2225 2226 value = value()2227 2228+ 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 value2233 2234+ raise2235+2236 def add_to_parser(self, parser: OptionParser, ctx: Context) -> None:2237 raise NotImplementedError()2238 2239 def consume_value(210 unmodified lines2450 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.2454+2455+ .. versionchanged:: 8.0.12456+ ``type`` is detected from ``flag_value`` if given.2457 """2458 2459 param_type_name = "option"2460 9 unmodified lines2470 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 lines2521 2522 if flag_value is None:2523 flag_value = not self.default2524 2525+ 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)2529+2530 self.is_flag: bool = is_flag2531+ self.is_bool_flag = isinstance(self.type, types.BoolParamType)2532 self.flag_value: t.Any = flag_value2533 2513- 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 = False2518-2534 # 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 = 02541 2542 self.allow_from_autoenv = allow_from_autoenv173 unmodified lines2716 else ", ".join(str(d) for d in envvar)2717 )2718 extra.append(_("env var: {var}").format(var=var_str))2719 2720+ # 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 = True2725+2726+ 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 = resilient2730+2731 show_default_is_str = isinstance(self.show_default, str)2732 2733 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 lines2745 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)2750 2751 extra.append(_("default: {default}").format(default=default_string))2752 2728- if isinstance(self.type, _NumberRangeBase):2753+ if isinstance(self.type, types._NumberRangeBase):2754 range_str = self.type._describe_range()2755 2756 if range_str:2757 extra.append(range_str)200 unmodified linesmodified:src/click/decorators.py+5 added-10 removed
328 unmodified lines329 Add the ``package_name`` parameter, and the ``%(package)s``330 value for messages.331 332 .. 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 lines372 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 = None377 378- if metadata is None:379- raise RuntimeError(380- "Install 'importlib_metadata' to get the version on Python < 3.8."381- )382-378 try:379 version = metadata.version(package_name) # type: ignore380 except metadata.PackageNotFoundError: # type: ignore381 raise RuntimeError(56 unmodified linesmodified:src/click/parser.py+3 added-1 removed
231 unmodified lines232 name=self.dest, nargs=self.nargs233 )234 )235 236- 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 = None240 241 state.opts[self.dest] = value # type: ignore242 state.order.append(self.obj)287 unmodified linesmodified:src/click/termui.py+1 added-1 removed
316 unmodified lines317 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 rendered482 unmodified linesmodified:src/click/types.py+1 added-4 removed
998 unmodified lines999 1000 if ty is float:1001 return FLOAT1002 1003- # 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 BOOL1005 1006 if guessed_type:1007 return STRING45 unmodified linesmodified:tests/test_arguments.py+13 added
192 unmodified lines193 else:194 assert result.return_value == expect195 196 197+def 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 arg202+203+ result = runner.invoke(cli, ["a", "b"], standalone_mode=False)204+ assert result.return_value == ("a", "b")205+206+ result = runner.invoke(cli, env={"X": "a"}, standalone_mode=False)207+ assert result.return_value == ("a",)208+209+210 def test_empty_nargs(runner):211 @click.command()212 @click.argument("arg", nargs=-1)213 def cmd(arg):166 unmodified linesmodified:tests/test_basic.py+17 added
545 unmodified lines546 547 result = runner.invoke(cli, ["--help"])548 assert "Summary line without period" in result.output549 assert "Here is a sentence." not in result.output550+551+552+def 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.outputmodified:tests/test_commands.py+14 added
283 unmodified lines284 class AliasedGroup(click.Group):285 def get_command(self, ctx, cmd_name):286 return push287 288+ def resolve_command(self, ctx, args):289+ _, command, args = super().resolve_command(ctx, args)290+ return command.name, command, args291+292 cli = AliasedGroup()293 294 @cli.command()295 def push():3 unmodified lines299 assert not result.exception300 assert result.output.startswith("Usage: root push [OPTIONS]")301 302 303+def 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 == 0311+312+313 def 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 linesmodified:tests/test_options.py+8 added-1 removed
551 unmodified lines552 553 554 def 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"559 560 @click.command()194 unmodified lines755 return opt, a, b756 757 result = runner.invoke(cli, args, standalone_mode=False, catch_exceptions=False)758 assert result.return_value == expect759+760+761+def 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.INTmodified:CHANGES.rst+33 added-4 removed
4 unmodified lines5 6 Unreleased7 8 9-Version 8.0.19+Version 8.0.210 -------------11 12 Unreleased13 14+15+Version 8.0.116+-------------17+18+Released 2021-05-1919+20 - 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`46 47 48 Version 8.0.049 -------------9 unmodified lines59 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 lines149 - 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 linesmodified:setup.py+7 added-1 removed
1 from setuptools import setup2 3-setup(name="click", install_requires=["colorama; platform_system == 'Windows'"])3+setup(4+ name="click",5+ install_requires=[6+ "colorama; platform_system == 'Windows'",7+ "importlib-metadata; python_version < '3.8'",8+ ],9+)