Skip to content
Myr

get default before processing value

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

This ensures the default value is processed like other values. Some type converters were adjusted to accept values that are already the correct type. Use parameter source instead of value to determine if argument was supplied on the command line during completion. Add a parameter source for values from prompt.

authored by David Lord · committed by David Lord · parent 94cc293 · Browse files · 7 files+118 added−85 removed
This commit

State

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

Diff stats

7 files+118 added−85 removed

  • tests:+28 added−17 removed
  • other:+90 added−68 removed

7 files+118 added−85 removed

modified:src/click/core.py+32 added-29 removed
150 unmodified lines
151 DEFAULT = enum.auto()152 """Used the default specified by the parameter."""153 DEFAULT_MAP = enum.auto()154 """Used a default provided by :attr:`Context.default_map`."""155 PROMPT = enum.auto()156 """Used a prompt to confirm a default or provide a value."""157158159class Context:160 """The context is a special internal object that holds state relevant
117 unmodified lines
278 self.info_name = info_name279 #: Map of parameter names to their parsed values. Parameters280 #: with ``expose_value=False`` are not stored.281 self.params = {}280 # This tracks the actual param objects that were parsed, even if281 # they didn't expose a value. Used by completion system to know282 # what parameters to exclude.283 self._seen_params = set()282 #: the leftover arguments.283 self.args = []284 #: protected arguments. These are arguments that are prepended285 #: to `args` when certain parsing scenarios are encountered but
449 unmodified lines
735736 :param name: The name of the parameter.737 :rtype: ParameterSource738 """741 return self._parameter_source[name]739 return self._parameter_source.get(name)740741742class BaseCommand:743 """The base command implements the minimal API contract of commands.
536 unmodified lines
1280 for param in self.get_params(ctx):1281 if (1282 not isinstance(param, Option)1283 or param.hidden1286 or (not param.multiple and param in ctx._seen_params)1284 or (1285 not param.multiple1286 and ctx.get_parameter_source(param.name)1287 is ParameterSource.COMMANDLINE1288 )1289 ):1290 continue12911292 results.extend(
634 unmodified lines
1927 if value is None:1928 value = ctx.lookup_default(self.name)1929 source = ParameterSource.DEFAULT_MAP19301929 if value is not None:1930 ctx.set_parameter_source(self.name, source)1931 if value is None:1932 value = self.get_default(ctx)1933 source = ParameterSource.DEFAULT19341932 return value1935 return value, source19361937 def type_cast_value(self, ctx, value):1938 """Given a value this runs it properly through the type system.1939 This automatically handles things like `nargs` and `multiple` as
37 unmodified lines
19771978 def full_process_value(self, ctx, value):1979 value = self.process_value(ctx, value)19801978 if value is None and not ctx.resilient_parsing:1979 value = self.get_default(ctx)19801981 if value is not None:1982 ctx.set_parameter_source(self.name, ParameterSource.DEFAULT)19831981 if self.required and self.value_is_missing(value):1982 raise MissingParameter(ctx=ctx, param=self)19831984 # For bounded nargs (!= -1), validate the number of values.
36 unmodified lines
2021 return rv20222023 def handle_parse_result(self, ctx, opts, args):2024 with augment_usage_errors(ctx, param=self):2028 value = self.consume_value(ctx, opts)2025 value, source = self.consume_value(ctx, opts)2026 ctx.set_parameter_source(self.name, source)20272028 try:2029 value = self.full_process_value(ctx, value)20302031 if self.callback is not None:2032 value = self.callback(ctx, self, value)2033 except Exception:2034 if not ctx.resilient_parsing:2035 raise20362037 value = None2035 if self.callback is not None:2036 try:2037 value = self.callback(ctx, self, value)2038 except Exception:2039 if not ctx.resilient_parsing:2040 raise20382039 if self.expose_value:2040 ctx.params[self.name] = value20412045 if value is not None:2046 ctx._seen_params.add(self)20472042 return value, args20432044 def get_help_record(self, ctx):2045 pass
370 unmodified lines
2416 if self.multiple and self.nargs != 1:2417 rv = batch(rv, self.nargs)2418 return rv24192426 def full_process_value(self, ctx, value):2427 if value is None and self.prompt is not None and not ctx.resilient_parsing:2428 return self.prompt_for_value(ctx)2420 def consume_value(self, ctx, opts):2421 value, source = super().consume_value(ctx, opts)24222430 return super().full_process_value(ctx, value)2423 # The value wasn't set, or used the param's default, prompt if2424 # prompting is enabled.2425 if (2426 source in {None, ParameterSource.DEFAULT}2427 and self.prompt is not None2428 and not ctx.resilient_parsing2429 ):2430 value = self.prompt_for_value(ctx)2431 source = ParameterSource.PROMPT24322433 return value, source243424352436class Argument(Parameter):2437 """Arguments are positional parameters to a command. They generally2438 provide fewer features than options but can have infinite ``nargs``2439 and are required by default.
61 unmodified lines
modified:src/click/shell_completion.py+19 added-18 removed
2 unmodified lines
34from .core import Argument5from .core import MultiCommand6from .core import Option7from .core import ParameterSource8from .parser import split_arg_string9from .utils import echo1011
383 unmodified lines
395 """396 return _available_shells.get(shell)397398398def _is_incomplete_argument(values, param):399def _is_incomplete_argument(ctx, param):400 """Determine if the given parameter is an argument that can still401 accept values.402402 :param values: Dict of param names and values parsed from the403 command line args.403 :param ctx: Invocation context for the command represented by the404 parsed complete args.405 :param param: Argument object being checked.406 """407 if not isinstance(param, Argument):408 return False409409 value = values[param.name]410 value = ctx.params[param.name]411 return (412 param.nargs == -1413 or ctx.get_parameter_source(param.name) is not ParameterSource.COMMANDLINE414 or (415 param.nargs > 1416 and isinstance(value, (tuple, list))417 and len(value) < param.nargs418 )419 )420411 if value is None:412 return True421414 if param.nargs == -1:415 return True416417 if isinstance(value, list) and param.nargs > 1 and len(value) < param.nargs:418 return True419420 return False421422422def _start_of_option(value):423 """Check if the value looks like the start of an option."""424 return value and not value[0].isalnum()425
95 unmodified lines
521 # command will provide option name completions.522 if "--" not in args and _start_of_option(incomplete):523 return ctx.command, incomplete524525 params = ctx.command.get_params(ctx)526527 # If the last complete arg is an option name with an incomplete528 # value, the option will provide value completions.528 for param in ctx.command.get_params(ctx):529 for param in params:530 if _is_incomplete_option(args, param):531 return param, incomplete532533 # It's not an option name or value. The first argument without a534 # parsed value will provide value completions.534 for param in ctx.command.get_params(ctx):535 if _is_incomplete_argument(ctx.params, param):535 for param in params:536 if _is_incomplete_argument(ctx, param):537 return param, incomplete538539 # There were no unparsed arguments, the command may be a group that540 # will provide command name completions.
1 unmodified line
modified:src/click/types.py+24 added-20 removed
179 unmodified lines
180 value = value.decode("utf-8", "replace")181 else:182 value = value.decode("utf-8", "replace")183 return value184 return value184 return str(value)185186 def __repr__(self):187 return "STRING"188
65 unmodified lines
254255 if normed_value in normed_choices:256 return normed_choices[normed_value]257258 self.fail(259 f"invalid choice: {value}. (choose from {', '.join(self.choices)})",260 param,261 ctx,262 )258 one_of = "one of " if len(self.choices) > 1 else ""259 choices_str = ", ".join(repr(c) for c in self.choices)260 self.fail(f"{value!r} is not {one_of}{choices_str}.", param, ctx)261262 def __repr__(self):263 return f"Choice({list(self.choices)})"264
52 unmodified lines
317 except ValueError:318 return None319320 def convert(self, value, param, ctx):323 # Exact match321 if isinstance(value, datetime):322 return value323324 for format in self.formats:325 dtime = self._try_to_convert_date(value, format)326 if dtime:327 return dtime325 converted = self._try_to_convert_date(value, format)326327 if converted is not None:328 return converted329330 plural = "s" if len(self.formats) > 1 else ""331 formats_str = ", ".join(repr(f) for f in self.formats)332 self.fail(330 f"invalid datetime format: {value}. (choose from {', '.join(self.formats)})"333 f"{value!r} does not match the format{plural} {formats_str}.", param, ctx334 )335336 def __repr__(self):337 return "DateTime"
5 unmodified lines
343 def convert(self, value, param, ctx):344 try:345 return self._number_class(value)346 except ValueError:344 self.fail(f"{value} is not a valid {self.name}", param, ctx)347 self.fail(f"{value!r} is not a valid {self.name}.", param, ctx)348349350class _NumberRangeBase(_NumberParamTypeBase):351 def __init__(self, min=None, max=None, min_open=False, max_open=False, clamp=False):
145 unmodified lines
497class BoolParamType(ParamType):498 name = "boolean"499500 def convert(self, value, param, ctx):498 if isinstance(value, bool):501 if value in {False, True}:502 return bool(value)503504 norm = value.strip().lower()505
2 unmodified lines
508509 if norm in {"0", "false", "f", "no", "n", "off"}:510 return False511509 self.fail(f"{value!r} is not a valid boolean value.", param, ctx)512 self.fail(f"{value!r} is not a valid boolean.", param, ctx)513514 def __repr__(self):515 return "BOOL"516
3 unmodified lines
520521 def convert(self, value, param, ctx):522 import uuid523524 if isinstance(value, uuid.UUID):525 return value526527 value = value.strip()528529 try:530 return uuid.UUID(value)531 except ValueError:524 self.fail(f"{value} is not a valid UUID value", param, ctx)532 self.fail(f"{value!r} is not a valid UUID.", param, ctx)533534 def __repr__(self):535 return "UUID"536
80 unmodified lines
617 else:618 ctx.call_on_close(safecall(f.flush))619 return f620 except OSError as e: # noqa: B014613 self.fail(614 f"Could not open file: {filename_to_ui(value)}: {get_strerror(e)}",615 param,616 ctx,617 )621 self.fail(f"{filename_to_ui(value)!r}: {get_strerror(e)}", param, ctx)622623 def shell_complete(self, ctx, param, incomplete):624 """Return a special completion marker that tells the completion625 system to use the shell to provide file path completions.
292 unmodified lines
modified:tests/test_basic.py+10 added-14 removed
145 unmodified lines
146 assert "FOO:[46]" in result.output147148 result = runner.invoke(cli, ["--foo=bar"])149 assert result.exception150 assert "Invalid value for '--foo': bar is not a valid integer" in result.output150 assert "Invalid value for '--foo': 'bar' is not a valid integer." in result.output151152153def test_uuid_option(runner):154 @click.command()
13 unmodified lines
168 assert "U:[821592c1-c50e-4971-9cd6-e89dc6832f86]" in result.output169170 result = runner.invoke(cli, ["--u=bar"])171 assert result.exception172 assert "Invalid value for '--u': bar is not a valid UUID value" in result.output172 assert "Invalid value for '--u': 'bar' is not a valid UUID." in result.output173174175def test_float_option(runner):176 @click.command()
11 unmodified lines
188 assert "FOO:[23.5]" in result.output189190 result = runner.invoke(cli, ["--foo=bar"])191 assert result.exception192 assert "Invalid value for '--foo': bar is not a valid float" in result.output192 assert "Invalid value for '--foo': 'bar' is not a valid float." in result.output193194195def test_boolean_option(runner):196 for default in True, False:
105 unmodified lines
302 with runner.isolated_filesystem():303 os.mkdir("example.txt")304 result_in = runner.invoke(input_non_lazy, ["--file=example.txt"])305 assert result_in.exit_code == 2306 assert (307 "Invalid value for '--file': Could not open file: example.txt"308 in result_in.output309 )306 assert "Invalid value for '--file': 'example.txt'" in result_in.output307308309def test_path_option(runner):310 @click.command()
53 unmodified lines
364365 result = runner.invoke(cli, ["--method=meh"])366 assert result.exit_code == 2367 assert (371 "Invalid value for '--method': invalid choice: meh."372 " (choose from foo, bar, baz)" in result.output368 "Invalid value for '--method': 'meh' is not one of 'foo', 'bar', 'baz'."369 in result.output370 )371372 result = runner.invoke(cli, ["--help"])373 assert "--method [foo|bar|baz]" in result.output
11 unmodified lines
385386 result = runner.invoke(cli, ["meh"])387 assert result.exit_code == 2388 assert (392 "Invalid value for '{foo|bar|baz}': invalid choice: meh. "393 "(choose from foo, bar, baz)" in result.output389 "Invalid value for '{foo|bar|baz}': 'meh' is not one of 'foo',"390 " 'bar', 'baz'." in result.output391 )392393 result = runner.invoke(cli, ["--help"])394 assert "{foo|bar|baz}" in result.output
15 unmodified lines
410411 result = runner.invoke(cli, ["--start_date=2015-09"])412 assert result.exit_code == 2413 assert (417 "Invalid value for '--start_date':"418 " invalid datetime format: 2015-09."419 " (choose from %Y-%m-%d, %Y-%m-%dT%H:%M:%S, %Y-%m-%d %H:%M:%S)"414 "Invalid value for '--start_date': '2015-09' does not match the formats"415 " '%Y-%m-%d', '%Y-%m-%dT%H:%M:%S', '%Y-%m-%d %H:%M:%S'."416 ) in result.output417418 result = runner.invoke(cli, ["--help"])419 assert (
111 unmodified lines
modified:tests/test_formatting.py+1 added-1 removed
193 unmodified lines
194 assert result.output.splitlines() == [195 "Usage: cmd [OPTIONS] metavar",196 "Try 'cmd --help' for help.",197 "",198 "Error: Invalid value for 'metavar': 3.14 is not a valid integer",198 "Error: Invalid value for 'metavar': '3.14' is not a valid integer.",199 ]200201202def test_formatting_usage_error_nested(runner):
150 unmodified lines
modified:tests/test_shell_completion.py+17 added-2 removed
88 unmodified lines
89 assert _get_words(cli, ["x"], "a") == ["a1", "a2"]90 assert _get_words(cli, ["x", "b"], "d") == ["d"]919293def test_argument_default():94 cli = Command(95 "cli",96 add_help_option=False,97 params=[98 Argument(["a"], type=Choice(["a"]), default="a"),99 Argument(["b"], type=Choice(["b"]), default="b"),100 ],101 )102 assert _get_words(cli, [], "") == ["a"]103 assert _get_words(cli, ["a"], "b") == ["b"]104 # ignore type validation105 assert _get_words(cli, ["x"], "b") == ["b"]106107108def test_type_choice():109 cli = Command("cli", params=[Option(["-c"], type=Choice(["a1", "a2", "b"]))])110 assert _get_words(cli, ["-c"], "") == ["a1", "a2", "b"]111 assert _get_words(cli, ["-c"], "a") == ["a1", "a2"]
21 unmodified lines
133 Option(["--on/--off"]),134 Argument(["a"], type=Choice(["a1", "a2", "b"])),135 ],136 )122 assert _get_words(cli, ["type"], "--") == ["--on", "--off"]137 assert _get_words(cli, [], "--") == ["--on", "--off"]138 # flag option doesn't take value, use choice argument124 assert _get_words(cli, ["x", "--on"], "a") == ["a1", "a2"]139 assert _get_words(cli, ["--on"], "a") == ["a1", "a2"]140141142def test_option_custom():143 def custom(ctx, param, incomplete):
163 unmodified lines
modified:CHANGES.rst+15 added-1 removed
109 unmodified lines
110- Extra context settings (``obj=...``, etc.) are passed on to the111 completion system. :issue:`942`112- Include ``--help`` option in completion. :pr:`1504`113- ``ParameterSource`` is an ``enum.Enum`` subclass. :issue:`1530`114- Boolean type strips surrounding space before converting.114- Boolean and UUID types strip surrounding space before converting.115 :issue:`1605`116- Adjusted error message from parameter type validation to be more117 consistent. Quotes are used to distinguish the invalid value.118 :issue:`1605`119- The default value for a parameter with ``nargs`` > 1 and120 ``multiple=True`` must be a list of tuples. :issue:`1649`121- When getting the value for a parameter, the default is tried in the122 same section as other sources to ensure consistent processing.123 :issue:`1649`124- All parameter types accept a value that is already the correct type.125 :issue:`1649`126- For shell completion, an argument is considered incomplete if its127 value did not come from the command line args. :issue:`1649`128- Added ``ParameterSource.PROMPT`` to track parameter values that were129 prompted for. :issue:`1649`130131132Version 7.1.2133-------------
635 unmodified lines