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
Provenance
- Commit
e79c2b4- Tree
84fd274- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent
94cc293
7 files changed+118 added−85 removed
modified:src/click/core.py+32 added-29 removed
150 unmodified lines151 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."""157 158 159 class Context:160 """The context is a special internal object that holds state relevant117 unmodified lines278 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 but449 unmodified lines735 736 :param name: The name of the parameter.737 :rtype: ParameterSource738 """741- return self._parameter_source[name]739+ return self._parameter_source.get(name)740 741 742 class BaseCommand:743 """The base command implements the minimal API contract of commands.536 unmodified lines1280 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 continue1291 1292 results.extend(634 unmodified lines1927 if value is None:1928 value = ctx.lookup_default(self.name)1929 source = ParameterSource.DEFAULT_MAP1930 1929- 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.DEFAULT1934 1932- return value1935+ return value, source1936 1937 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` as37 unmodified lines1977 1978 def full_process_value(self, ctx, value):1979 value = self.process_value(ctx, value)1980 1978- if value is None and not ctx.resilient_parsing:1979- value = self.get_default(ctx)1980-1981- if value is not None:1982- ctx.set_parameter_source(self.name, ParameterSource.DEFAULT)1983-1981 if self.required and self.value_is_missing(value):1982 raise MissingParameter(ctx=ctx, param=self)1983 1984 # For bounded nargs (!= -1), validate the number of values.36 unmodified lines2021 return rv2022 2023 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)2027+2028 try:2029 value = self.full_process_value(ctx, value)2030+2031+ if self.callback is not None:2032+ value = self.callback(ctx, self, value)2033 except Exception:2034 if not ctx.resilient_parsing:2035 raise2036+2037 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- raise2038 2039 if self.expose_value:2040 ctx.params[self.name] = value2041 2045- if value is not None:2046- ctx._seen_params.add(self)2047-2042 return value, args2043 2044 def get_help_record(self, ctx):2045 pass370 unmodified lines2416 if self.multiple and self.nargs != 1:2417 rv = batch(rv, self.nargs)2418 return rv2419 2426- 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)2422 2430- 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.PROMPT2432 2433+ return value, source2434 2435+2436 class 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 linesmodified:src/click/shell_completion.py+19 added-18 removed
2 unmodified lines3 4 from .core import Argument5 from .core import MultiCommand6 from .core import Option7+from .core import ParameterSource8 from .parser import split_arg_string9 from .utils import echo10 11 383 unmodified lines395 """396 return _available_shells.get(shell)397 398 398-def _is_incomplete_argument(values, param):399+def _is_incomplete_argument(ctx, param):400 """Determine if the given parameter is an argument that can still401 accept values.402 402- :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 False409 409- 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+ )420 411- if value is None:412- return True421 414- if param.nargs == -1:415- return True416-417- if isinstance(value, list) and param.nargs > 1 and len(value) < param.nargs:418- return True419-420- return False421-422-422 def _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 lines521 # command will provide option name completions.522 if "--" not in args and _start_of_option(incomplete):523 return ctx.command, incomplete524 525+ params = ctx.command.get_params(ctx)526+527 # 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, incomplete532 533 # 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, incomplete538 539 # There were no unparsed arguments, the command may be a group that540 # will provide command name completions.1 unmodified linemodified:src/click/types.py+24 added-20 removed
179 unmodified lines180 value = value.decode("utf-8", "replace")181 else:182 value = value.decode("utf-8", "replace")183 return value184- return value184+ return str(value)185 186 def __repr__(self):187 return "STRING"188 65 unmodified lines254 255 if normed_value in normed_choices:256 return normed_choices[normed_value]257 258- 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)261 262 def __repr__(self):263 return f"Choice({list(self.choices)})"264 52 unmodified lines317 except ValueError:318 return None319 320 def convert(self, value, param, ctx):323- # Exact match321+ if isinstance(value, datetime):322+ return value323+324 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)326 327+ if converted is not None:328+ return converted329+330+ 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 )335 336 def __repr__(self):337 return "DateTime"5 unmodified lines343 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)348 349 350 class _NumberRangeBase(_NumberParamTypeBase):351 def __init__(self, min=None, max=None, min_open=False, max_open=False, clamp=False):145 unmodified lines497 class BoolParamType(ParamType):498 name = "boolean"499 500 def convert(self, value, param, ctx):498- if isinstance(value, bool):501+ if value in {False, True}:502 return bool(value)503 504 norm = value.strip().lower()505 2 unmodified lines508 509 if norm in {"0", "false", "f", "no", "n", "off"}:510 return False511 509- 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)513 514 def __repr__(self):515 return "BOOL"516 3 unmodified lines520 521 def convert(self, value, param, ctx):522 import uuid523 524+ if isinstance(value, uuid.UUID):525+ return value526+527+ value = value.strip()528+529 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)533 534 def __repr__(self):535 return "UUID"536 80 unmodified lines617 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)622 623 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 linesmodified:tests/test_basic.py+10 added-14 removed
145 unmodified lines146 assert "FOO:[46]" in result.output147 148 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.output151 152 153 def test_uuid_option(runner):154 @click.command()13 unmodified lines168 assert "U:[821592c1-c50e-4971-9cd6-e89dc6832f86]" in result.output169 170 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.output173 174 175 def test_float_option(runner):176 @click.command()11 unmodified lines188 assert "FOO:[23.5]" in result.output189 190 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.output193 194 195 def test_boolean_option(runner):196 for default in True, False:105 unmodified lines302 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.output307 308 309 def test_path_option(runner):310 @click.command()53 unmodified lines364 365 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 )371 372 result = runner.invoke(cli, ["--help"])373 assert "--method [foo|bar|baz]" in result.output11 unmodified lines385 386 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 )392 393 result = runner.invoke(cli, ["--help"])394 assert "{foo|bar|baz}" in result.output15 unmodified lines410 411 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.output417 418 result = runner.invoke(cli, ["--help"])419 assert (111 unmodified linesmodified:tests/test_formatting.py+1 added-1 removed
193 unmodified lines194 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 ]200 201 202 def test_formatting_usage_error_nested(runner):150 unmodified linesmodified:tests/test_shell_completion.py+17 added-2 removed
88 unmodified lines89 assert _get_words(cli, ["x"], "a") == ["a1", "a2"]90 assert _get_words(cli, ["x", "b"], "d") == ["d"]91 92 93+def 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"]106+107+108 def 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 lines133 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"]140 141 142 def test_option_custom():143 def custom(ctx, param, incomplete):163 unmodified linesmodified:CHANGES.rst+15 added-1 removed
109 unmodified lines110 - 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`130 131 132 Version 7.1.2133 -------------635 unmodified lines