Merge pull request #1549 from ewjoachim/default-map-show-default-1548
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by David Lord · committed by GitHub · parents c067af7, 78a62b3 · Browse files · 3 files·+70 added−24 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
3 files+70 added−24 removed
- tests:+12 added−0 removed
- other:+58 added−24 removed
Provenance
- Commit
7332f00- Tree
03c7a00- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
c067af7- Parent 2
78a62b3
3 files changed+70 added−24 removed
modified:src/click/core.py+54 added-23 removed
1 import enum2 import errno3-import inspect3 import os4 import sys5 from contextlib import contextmanager6 from contextlib import ExitStack604 unmodified lines611 if rv is None:612 self.obj = rv = object_type()613 return rv614 616- def lookup_default(self, name):617- """Looks up the default for a parameter name. This by default618- looks into the :attr:`default_map` if available.615+ def lookup_default(self, name, call=True):616+ """Get the default for a parameter from :attr:`default_map`.617+618+ :param name: Name of the parameter.619+ :param call: If the default is a callable, call it. Disable to620+ return the callable instead.621+622+ .. versionchanged:: 8.0623+ Added the ``call`` parameter.624 """625 if self.default_map is not None:621- rv = self.default_map.get(name)622- if callable(rv):623- rv = rv()624- return rv626+ value = self.default_map.get(name)627 628+ if call and callable(value):629+ return value()630+631+ return value632+633 def fail(self, message):634 """Aborts the execution of the program with a specific error635 message.636 1289 unmodified lines1926 if self.nargs != 1:1927 metavar += "..."1928 return metavar1929 1923- def get_default(self, ctx):1924- """Given a context variable this calculates the default value."""1925- # Otherwise go with the regular default.1926- if callable(self.default):1927- rv = self.default()1928- else:1929- rv = self.default1930- return self.type_cast_value(ctx, rv)1930+ def get_default(self, ctx, call=True):1931+ """Get the default for the parameter. Tries1932+ :meth:`Context.lookup_value` first, then the local default.1933 1934+ :param ctx: Current context.1935+ :param call: If the default is a callable, call it. Disable to1936+ return the callable instead.1937+1938+ .. versionchanged:: 8.01939+ Looks at ``ctx.default_map`` first.1940+1941+ .. versionchanged:: 8.01942+ Added the ``call`` parameter.1943+ """1944+ value = ctx.lookup_default(self.name, call=False)1945+1946+ if value is None:1947+ value = self.default1948+1949+ if callable(value):1950+ if not call:1951+ # Don't type cast the callable.1952+ return value1953+1954+ value = value()1955+1956+ return self.type_cast_value(ctx, value)1957+1958 def add_to_parser(self, parser, ctx):1959 pass1960 1961 def consume_value(self, ctx, opts):418 unmodified lines2380 if isinstance(envvar, (list, tuple))2381 else envvar2382 )2383 extra.append(f"env var: {var_str}")2384+2385+ default_value = self.get_default(ctx, call=False)2386+2358- if self.default is not None and (self.show_default or ctx.show_default):2387+ if default_value is not None and (self.show_default or ctx.show_default):2388 if isinstance(self.show_default, str):2389 default_string = f"({self.show_default})"2361- elif isinstance(self.default, (list, tuple)):2362- default_string = ", ".join(str(d) for d in self.default)2363- elif inspect.isfunction(self.default):2390+ elif isinstance(default_value, (list, tuple)):2391+ default_string = ", ".join(str(d) for d in default_value)2392+ elif callable(default_value):2393 default_string = "(dynamic)"2394 elif self.is_bool_flag and self.secondary_opts:2395 # For boolean flags that have distinct True/False opts,2396 # use the opt without prefix instead of the value.2397 default_string = split_opt(2398 (self.opts if self.default else self.secondary_opts)[0]2399 )[1]2400 else:2372- default_string = self.default2401+ default_string = default_value2402+2403 extra.append(f"default: {default_string}")2404 2405 if isinstance(self.type, _NumberRangeBase):2406 range_str = self.type._describe_range()8 unmodified lines2415 help = f"{help} [{extra_str}]" if help else f"[{extra_str}]"2416 2417 return ("; " if any_prefix_is_slash else " / ").join(rv), help2418 2389- def get_default(self, ctx):2419+ def get_default(self, ctx, call=True):2420 # If we're a non boolean flag our default is more complex because2421 # we need to look at all flags in the same group to figure out2422 # if we're the the default one in which case we return the flag2423 # value as default.2424 if self.is_flag and not self.is_bool_flag:2425 for param in ctx.command.params:2426 if param.name == self.name and param.default:2427 return param.flag_value2428+2429 return None2430 2400- return super().get_default(ctx)2431+ return super().get_default(ctx, call=call)2432 2433 def prompt_for_value(self, ctx):2434 """This is an alternative flow that can be activated in the full2435 value processing if a value does not exist. It will prompt the131 unmodified linesmodified:tests/test_options.py+12 added
186 unmodified lines187 assert "foo, bar" in result.output188 assert "1, 2" in result.output189 190 191+def test_show_default_default_map(runner):192+ @click.command()193+ @click.option("--arg", default="a", show_default=True)194+ def cmd(arg):195+ click.echo(arg)196+197+ result = runner.invoke(cmd, ["--help"], default_map={"arg": "b"})198+199+ assert not result.exception200+ assert "[default: b]" in result.output201+202+203 def test_multiple_default_type():204 opt = click.Option(["-a"], multiple=True, default=(1, 2))205 assert opt.nargs == 1206 assert opt.multiple454 unmodified linesmodified:CHANGES.rst+4 added-1 removed
132 unmodified lines133 empty tuple. :issue:`472`134 - Handle empty env vars as though the option were not passed. This135 extends the change introduced in 7.1 to be consistent in more cases.136 :issue:`1285`137+- ``Parameter.get_default()`` checks ``Context.default_map`` to138+ handle overrides consistently in help text, ``invoke()``, and139+ prompts. :issue:`1548`140 141 142 Version 7.1.2143 -------------40 unmodified lines184 - Always return one of the passed choices for ``click.Choice``185 :issue:`1277`, :pr:`1318`186 - Add ``no_args_is_help`` option to ``click.Command``, defaults to187 False :pr:`1167`185-- Add ``show_defaults`` parameter to ``Context`` to enable showing188+- Add ``show_default`` parameter to ``Context`` to enable showing189 defaults globally. :issue:`1018`190 - Handle ``env MYPATH=''`` as though the option were not passed.191 :issue:`1196`192 - It is once again possible to call ``next(bar)`` on an active586 unmodified lines