option callback is invoked when validating prompt value
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Saif807380 · committed by David Lord · parent 98e471f · Browse files · 5 files·+50 added−30 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
5 files+50 added−30 removed
- tests:+18 added−2 removed
- other:+32 added−28 removed
Provenance
- Commit
05c38db- Tree
6cd500c- Author
Saif807380 <saif1204kazi@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent
98e471f
5 files changed+50 added−30 removed
modified:docs/options.rst+12 added-7 removed
826 unmodified lines827 828 .. versionchanged:: 2.0829 830 If you want to apply custom validation logic, you can do this in the831-parameter callbacks. These callbacks can both modify values as well as832-raise errors if the validation does not work.831+parameter callbacks. These callbacks can both modify values as well as832+raise errors if the validation does not work. The callback runs after833+type conversion. It is called for all sources, including prompts.834 835 In Click 1.0, you can only raise the :exc:`UsageError` but starting with836 Click 2.0, you can also raise the :exc:`BadParameter` error, which has the837 added advantage that it will automatically format the error message to838 also contain the parameter name.839 839-Example:840-840 .. click:example::841 842 def validate_rolls(ctx, param, value):843+ if isinstance(value, tuple):844+ return value845+846 try:847 rolls, _, dice = value.partition("d")848 return int(dice), int(rolls)849 except ValueError:850 raise click.BadParameter("format must be 'NdM'")851 852 @click.command()851- @click.option("--rolls", callback=validate_rolls, default="1d6")853+ @click.option(854+ "--rolls", type=click.UNPROCESSED, callback=validate_rolls,855+ default="1d6", prompt=True,856+ )857 def roll(rolls):858 sides, times = rolls859 click.echo(f"Rolling a {sides}-sided dice {times} time(s)")860 856-And what it looks like:857-861 .. click:run::862 863 invoke(roll, args=["--rolls=42"])864 println()865 invoke(roll, args=["--rolls=2d12"])866+ println()867+ invoke(roll, input=["42", "2d12"])868 869 870 .. _optional-value:871 43 unmodified linesmodified:src/click/core.py+17 added-20 removed
1767 unmodified lines1768 :param required: controls if this is optional or not.1769 :param default: the default value if omitted. This can also be a callable,1770 in which case it's invoked when the default is needed1771 without any arguments.1772- :param callback: a callback that should be executed after the parameter1773- was matched. This is called as ``fn(ctx, param,1774- value)`` and needs to return the value.1772+ :param callback: A function to further process or validate the value1773+ after type conversion. It is called as ``f(ctx, param, value)``1774+ and must return the value. It is called for all sources,1775+ including prompts.1776 :param nargs: the number of arguments to match. If not ``1`` the return1777 value is a tuple instead of single value. The default for1778 nargs is ``1`` (except if the type is a tuple, then it's1779 the arity of the tuple). If ``nargs=-1``, all remaining13 unmodified lines1793 of :class:`~click.shell_completion.CompletionItem` or a list of1794 strings.1795 1796 .. versionchanged:: 8.01797+ ``process_value`` validates required parameters and bounded1798+ ``nargs``, and invokes the parameter callback before returning1799+ the value. This allows the callback to validate prompts.1800+ ``full_process_value`` is removed.1801+1802+ .. versionchanged:: 8.01803 ``autocompletion`` is renamed to ``shell_complete`` and has new1804 semantics described above. The old name is deprecated and will1805 be removed in 8.1, until then it will be wrapped to match the1806 new requirements.207 unmodified lines2014 return tuple(_convert(x, level - 1) for x in value)2015 2016 return _convert(value, (self.nargs != 1) + bool(self.multiple))2017 2011- def process_value(self, ctx, value):2012- """Given a value and context this runs the logic to convert the2013- value as necessary.2014- """2015- # If the value we were given is None we do nothing. This way2016- # code that calls this can easily figure out if something was2017- # not provided. Otherwise it would be converted into an empty2018- # tuple for multiple invocations which is inconvenient.2019- if value is not None:2020- return self.type_cast_value(ctx, value)2021-2018 def value_is_missing(self, value):2019 if value is None:2020 return True2021 if (self.nargs != 1 or self.multiple) and value == ():2022 return True2023 return False2024 2029- def full_process_value(self, ctx, value):2030- value = self.process_value(ctx, value)2025+ def process_value(self, ctx, value):2026+ if value is not None:2027+ value = self.type_cast_value(ctx, value)2028 2029 if self.required and self.value_is_missing(value):2030 raise MissingParameter(ctx=ctx, param=self)2031 13 unmodified lines2045 f"Argument {self.name!r} takes {self.nargs} values but"2046 f" {len(value)} {were} given."2047 )2048 2049+ if self.callback is not None:2050+ value = self.callback(ctx, self, value)2051+2052 return value2053 2054 def resolve_envvar_value(self, ctx):2055 if self.envvar is None:24 unmodified lines2080 value, source = self.consume_value(ctx, opts)2081 ctx.set_parameter_source(self.name, source)2082 2083 try:2084- value = self.full_process_value(ctx, value)2085-2086- if self.callback is not None:2087- value = self.callback(ctx, self, value)2084+ value = self.process_value(ctx, value)2085 except Exception:2086 if not ctx.resilient_parsing:2087 raise2088 514 unmodified linesmodified:tests/test_arguments.py+1 added-1 removed
226 unmodified lines227 def test_missing_argument_string_cast():228 ctx = click.Context(click.Command(""))229 230 with pytest.raises(click.MissingParameter) as excinfo:231- click.Argument(["a"], required=True).full_process_value(ctx, None)231+ click.Argument(["a"], required=True).process_value(ctx, None)232 233 assert str(excinfo.value) == "missing parameter: a"234 235 139 unmodified linesmodified:tests/test_options.py+17 added-1 removed
374 unmodified lines375 result = runner.invoke(cmd, ["--foo", "42"])376 assert result.output == "42\n"377 378 379+def test_callback_validates_prompt(runner, monkeypatch):380+ def validate(ctx, param, value):381+ if value < 0:382+ raise click.BadParameter("should be positive")383+384+ return value385+386+ @click.command()387+ @click.option("-a", type=int, callback=validate, prompt=True)388+ def cli(a):389+ click.echo(a)390+391+ result = runner.invoke(cli, input="-12\n60\n")392+ assert result.output == "A: -12\nError: should be positive\nA: 60\n60\n"393+394+395 def test_winstyle_options(runner):396 @click.command()397 @click.option("/debug;/no-debug", help="Enables or disables debug mode.")398 def cmd(debug):25 unmodified lines424 def test_missing_option_string_cast():425 ctx = click.Context(click.Command(""))426 427 with pytest.raises(click.MissingParameter) as excinfo:412- click.Option(["-a"], required=True).full_process_value(ctx, None)428+ click.Option(["-a"], required=True).process_value(ctx, None)429 430 assert str(excinfo.value) == "missing parameter: a"431 432 291 unmodified linesmodified:CHANGES.rst+3 added-1 removed
165 unmodified lines166 - Control the location of the temporary directory created by167 ``CLIRunner.isolated_filesystem`` by passing ``temp_dir``. A custom168 directory will not be removed automatically. :issue:`395`169 - ``click.confirm()`` will prompt until input is given if called with170- ``default=None``. :issue:`#1381`170+ ``default=None``. :issue:`1381`171+- Option prompts validate the value with the option's callback in172+ addition to its type. :issue:`457`173 174 175 Version 7.1.2176 -------------635 unmodified lines