add ability to provide non-flag option without value
Before adoption: this commit came in with the history the project adopted, so no landing records it.
use flag_value or prompt if an option is given without a value
authored by Amy · committed by David Lord · parent 7332f00 · Browse files · 6 files·+215 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
6 files+215 added−24 removed
- tests:+82 added−0 removed
- other:+133 added−24 removed
Provenance
- Commit
d314f45- Tree
6ced204- Author
Amy <leiamy12@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent
7332f00
6 files changed+215 added−24 removed
modified:docs/options.rst+51 added
431 unmodified lines432 433 It is advised that prompt not be used in conjunction with the multiple434 flag set to True. Instead, prompt in the function interactively.435 436+By default, the user will be prompted for an input if one was not passed437+through the command line. To turn this behavior off, see438+:ref:`optional-value`.439 440+441 Password Prompts442 ----------------443 444 Click also supports hidden prompts and asking for confirmation. This is403 unmodified lines848 849 invoke(roll, args=['--rolls=42'])850 println()851 invoke(roll, args=['--rolls=2d12'])852+853+854+.. _optional-value:855+856+Optional Value857+--------------858+859+Providing the value to an option can be made optional, in which case860+providing only the option's flag without a value will either show a861+prompt or use its ``flag_value``.862+863+Setting ``is_flag=False, flag_value=value`` tells Click that the option864+can still be passed a value, but if only the flag is given the865+``flag_value`` is used.866+867+.. click:example::868+869+ @click.command()870+ @click.option("--name", is_flag=False, flag_value="Flag", default="Default")871+ def hello(name):872+ click.echo(f"Hello, {name}!")873+874+.. click:run::875+876+ invoke(hello, args=[])877+ invoke(hello, args=["--name", "Value"])878+ invoke(hello, args=["--name"])879+880+If the option has ``prompt`` enabled, then setting881+``prompt_required=False`` tells Click to only show the prompt if the882+option's flag is given, instead of if the option is not provided at all.883+884+.. click:example::885+886+ @click.command()887+ @click.option('--name', prompt=True, prompt_required=False, default="Default")888+ def hello(name):889+ click.echo(f"Hello {name}!")890+891+.. click:run::892+893+ invoke(hello)894+ invoke(hello, args=["--name", "Value"])895+ invoke(hello, args=["--name"], input="Prompt")896+897+If ``required=True``, then the option will still prompt if it is not898+given, but it will also prompt if only the flag is given.modified:src/click/core.py+36 added-2 removed
16 unmodified lines17 from .formatting import HelpFormatter18 from .formatting import join_options19 from .globals import pop_context20 from .globals import push_context21+from .parser import _flag_needs_value22 from .parser import OptionParser23 from .parser import split_opt24 from .termui import confirm25 from .termui import prompt2122 unmodified lines2148 prompted for input. If set to `True` the prompt will be the2149 option name capitalized.2150 :param confirmation_prompt: if set then the value will need to be confirmed2151 if it was prompted for.2152+ :param prompt_required: If set to ``False``, the user will be2153+ prompted for input only when the option was specified as a flag2154+ without a value.2155 :param hide_input: if this is `True` then the input on the prompt will be2156 hidden from the user. This is useful for password2157 input.2158 :param is_flag: forces this option to act as a flag. The default is21 unmodified lines2180 param_decls=None,2181 show_default=False,2182 prompt=False,2183 confirmation_prompt=False,2184+ prompt_required=True,2185 hide_input=False,2186 is_flag=None,2187 flag_value=None,2188 multiple=False,16 unmodified lines2205 else:2206 prompt_text = prompt2207 self.prompt = prompt_text2208 self.confirmation_prompt = confirmation_prompt2209+ self.prompt_required = prompt_required2210 self.hide_input = hide_input2211 self.hidden = hidden2212 2207- # Flags2213+ # If prompt is enabled but not required, then the option can be2214+ # used as a flag to indicate using prompt or flag_value.2215+ self._flag_needs_value = self.prompt is not None and not self.prompt_required2216+2217 if is_flag is None:2218 if flag_value is not None:2219+ # Implicitly a flag because flag_value was set.2220 is_flag = True2221+ elif self._flag_needs_value:2222+ # Not a flag, but when used as a flag it shows a prompt.2223+ is_flag = False2224 else:2225+ # Implicitly a flag because flag options were given.2226 is_flag = bool(self.secondary_opts)2227+ elif is_flag is False and not self._flag_needs_value:2228+ # Not a flag, and prompt is not enabled, can be used as a2229+ # flag if flag_value is set.2230+ self._flag_needs_value = flag_value is not None2231+2232 if is_flag and default_is_missing:2233 self.default = False2234+2235 if flag_value is None:2236 flag_value = not self.default2237+2238 self.is_flag = is_flag2239 self.flag_value = flag_value2240+2241 if self.is_flag and isinstance(self.flag_value, bool) and type in [None, bool]:2242 self.type = BOOL2243 self.is_bool_flag = True2244 else:262 unmodified lines2507 2508 def consume_value(self, ctx, opts):2509 value, source = super().consume_value(ctx, opts)2510 2511+ # The parser will emit a sentinel value if the option can be2512+ # given as a flag without a value. This is different from None2513+ # to distinguish from the flag not being given at all.2514+ if value is _flag_needs_value:2515+ if self.prompt is not None and not ctx.resilient_parsing:2516+ value = self.prompt_for_value(ctx)2517+ source = ParameterSource.PROMPT2518+ else:2519+ value = self.flag_value2520+ source = ParameterSource.COMMANDLINE2521+2522 # The value wasn't set, or used the param's default, prompt if2523 # prompting is enabled.2491- if (2524+ elif (2525 source in {None, ParameterSource.DEFAULT}2526 and self.prompt is not None2527+ and (self.required or self.prompt_required)2528 and not ctx.resilient_parsing2529 ):2530 value = self.prompt_for_value(ctx)2531 source = ParameterSource.PROMPT69 unmodified linesmodified:src/click/parser.py+39 added-22 removed
27 unmodified lines28 from .exceptions import BadOptionUsage29 from .exceptions import NoSuchOption30 from .exceptions import UsageError31 32+# Sentinel value that indicates an option was passed as a flag without a33+# value but is not a flag option. Option.consume_value uses this to34+# prompt or use the flag_value.35+_flag_needs_value = object()36 37+38 def _unpack_args(args, nargs_spec):39 """Given an iterable of arguments and an iterable of nargs specifications,40 it returns a tuple with all the unpacked arguments at the first index41 and all remaining arguments as the second.43 unmodified lines85 86 return tuple(rv), list(args)87 88 84-def _error_opt_args(nargs, opt):85- if nargs == 1:86- raise BadOptionUsage(opt, f"{opt} option requires an argument")87- raise BadOptionUsage(opt, f"{opt} option requires {nargs} arguments")88-89-89 def split_opt(opt):90 first = opt[:1]91 if first.isalnum():92 return "", opt248 unmodified lines341 # consumed.342 if explicit_value is not None:343 state.rargs.insert(0, explicit_value)344 346- nargs = option.nargs347- if len(state.rargs) < nargs:348- _error_opt_args(nargs, opt)349- elif nargs == 1:350- value = state.rargs.pop(0)351- else:352- value = tuple(state.rargs[:nargs])353- del state.rargs[:nargs]345+ value = self._get_value_from_state(opt, option, state)346 347 elif explicit_value is not None:348 raise BadOptionUsage(opt, f"{opt} option does not take a value")349 24 unmodified lines374 if i < len(arg):375 state.rargs.insert(0, arg[i:])376 stop = True377 386- nargs = option.nargs387- if len(state.rargs) < nargs:388- _error_opt_args(nargs, opt)389- elif nargs == 1:390- value = state.rargs.pop(0)391- else:392- value = tuple(state.rargs[:nargs])393- del state.rargs[:nargs]378+ value = self._get_value_from_state(opt, option, state)379 380 else:381 value = None382 8 unmodified lines391 # that can be achieved while still ignoring unknown arguments.392 if self.ignore_unknown_options and unknown_options:393 state.largs.append(f"{prefix}{''.join(unknown_options)}")394 395+ def _get_value_from_state(self, option_name, option, state):396+ nargs = option.nargs397+398+ if len(state.rargs) < nargs:399+ if option.obj._flag_needs_value:400+ # Option allows omitting the value.401+ value = _flag_needs_value402+ else:403+ n_str = "an argument" if nargs == 1 else f"{nargs} arguments"404+ raise BadOptionUsage(405+ option_name, f"{option_name} option requires {n_str}."406+ )407+ elif nargs == 1:408+ next_rarg = state.rargs[0]409+410+ if (411+ option.obj._flag_needs_value412+ and isinstance(next_rarg, str)413+ and next_rarg[:1] in self._opt_prefixes414+ and len(next_rarg) > 1415+ ):416+ # The next arg looks like the start of an option, don't417+ # use it as the value if omitting the value is allowed.418+ value = _flag_needs_value419+ else:420+ value = state.rargs.pop(0)421+ else:422+ value = tuple(state.rargs[:nargs])423+ del state.rargs[:nargs]424+425+ return value426+427 def _process_opts(self, arg, state):428 explicit_value = None429 # Long option handling happens in two parts. The first part is430 # supporting explicitly attached values. In any case, we will try24 unmodified linesmodified:tests/test_options.py+31 added
656 unmodified lines657 )658 ctx = click.Context(click.Command("test"))659 message = opt.get_help_record(ctx)[1]660 assert "[default: False]" in message661+662+663+@pytest.mark.parametrize(664+ ("args", "expect"),665+ [666+ (None, (None, None, ())),667+ (["--opt"], ("flag", None, ())),668+ (["--opt", "-a", 42], ("flag", "42", ())),669+ (["--opt", "test", "-a", 42], ("test", "42", ())),670+ (["--opt=test", "-a", 42], ("test", "42", ())),671+ (["-o"], ("flag", None, ())),672+ (["-o", "-a", 42], ("flag", "42", ())),673+ (["-o", "test", "-a", 42], ("test", "42", ())),674+ (["-otest", "-a", 42], ("test", "42", ())),675+ (["a", "b", "c"], (None, None, ("a", "b", "c"))),676+ (["--opt", "a", "b", "c"], ("a", None, ("b", "c"))),677+ (["--opt", "test"], ("test", None, ())),678+ (["-otest", "a", "b", "c"], ("test", None, ("a", "b", "c"))),679+ (["--opt=test", "a", "b", "c"], ("test", None, ("a", "b", "c"))),680+ ],681+)682+def test_option_with_optional_value(runner, args, expect):683+ @click.command()684+ @click.option("-o", "--opt", is_flag=False, flag_value="flag")685+ @click.option("-a")686+ @click.argument("b", nargs=-1)687+ def cli(opt, a, b):688+ return opt, a, b689+690+ result = runner.invoke(cli, args, standalone_mode=False, catch_exceptions=False)691+ assert result.return_value == expectmodified:tests/test_termui.py+51 added
383 unmodified lines384 @pytest.mark.skipif(platform.system() == "Windows", reason="No sed on Windows.")385 def test_fast_edit(runner):386 result = click.edit("a\nb", editor="sed -i~ 's/$/Test/'")387 assert result == "aTest\nbTest\n"388+389+390+@pytest.mark.parametrize(391+ ("prompt_required", "required", "args", "expect"),392+ [393+ (True, False, None, "prompt"),394+ (True, False, ["-v"], "-v option requires an argument"),395+ (False, True, None, "prompt"),396+ (False, True, ["-v"], "prompt"),397+ ],398+)399+def test_prompt_required_with_required(runner, prompt_required, required, args, expect):400+ @click.command()401+ @click.option("-v", prompt=True, prompt_required=prompt_required, required=required)402+ def cli(v):403+ click.echo(str(v))404+405+ result = runner.invoke(cli, args, input="prompt")406+ assert expect in result.output407+408+409+@pytest.mark.parametrize(410+ ("args", "expect"),411+ [412+ # Flag not passed, don't prompt.413+ pytest.param(None, None, id="no flag"),414+ # Flag and value passed, don't prompt.415+ pytest.param(["-v", "value"], "value", id="short sep value"),416+ pytest.param(["--value", "value"], "value", id="long sep value"),417+ pytest.param(["-vvalue"], "value", id="short join value"),418+ pytest.param(["--value=value"], "value", id="long join value"),419+ # Flag without value passed, prompt.420+ pytest.param(["-v"], "prompt", id="short no value"),421+ pytest.param(["--value"], "prompt", id="long no value"),422+ # Don't use next option flag as value.423+ pytest.param(["-v", "-o", "42"], ("prompt", "42"), id="no value opt"),424+ ],425+)426+def test_prompt_required_false(runner, args, expect):427+ @click.command()428+ @click.option("-v", "--value", prompt=True, prompt_required=False)429+ @click.option("-o")430+ def cli(value, o):431+ if o is not None:432+ return value, o433+434+ return value435+436+ result = runner.invoke(cli, args=args, input="prompt", standalone_mode=False)437+ assert result.exception is None438+ assert result.return_value == expectmodified:CHANGES.rst+7 added
135 unmodified lines136 :issue:`1285`137 - ``Parameter.get_default()`` checks ``Context.default_map`` to138 handle overrides consistently in help text, ``invoke()``, and139 prompts. :issue:`1548`140+- Add ``prompt_required`` param to ``Option``. When set to ``False``,141+ the user will only be prompted for an input if no value was passed.142+ :issue:`736`143+- Providing the value to an option can be made optional through144+ ``is_flag=False``, and the value can instead be prompted for or145+ passed in as a default value.146+ :issue:`549, 736, 764, 921, 1015, 1618`147 148 149 Version 7.1.2150 -------------635 unmodified lines