Skip to content
Myr

Fix eagerness of help option generated by `help_option_names` (#2811)

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

authored by Kevin Deldycke · committed by GitHub · parent 273fb90 · Browse files · 3 files+160 added−6 removed
This commit

State

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

Trailers

  • Co-authored-by: Andreas Backx <andreas@backx.org>

Diff stats

3 files+160 added−6 removed

  • tests:+132 added−0 removed
  • other:+28 added−6 removed

3 files+160 added−6 removed

modified:src/click/core.py+25 added-6 removed
38 unmodified lines
3940if t.TYPE_CHECKING:41 import typing_extensions as te4243 from .decorators import HelpOption44 from .shell_completion import CompletionItem4546F = t.TypeVar("F", bound=t.Callable[..., t.Any])47V = t.TypeVar("V")
68 unmodified lines
116def iter_params_for_processing(117 invocation_order: t.Sequence["Parameter"],118 declaration_order: t.Sequence["Parameter"],119) -> t.List["Parameter"]:119 """Given a sequence of parameters in the order as should be considered120 for processing and an iterable of parameters that exist, this returns121 a list in the correct order as they should be processed.120 """Returns all declared parameters in the order they should be processed.121122 The declared parameters are re-shuffled depending on the order in which123 they were invoked, as well as the eagerness of each parameters.124125 The invocation order takes precedence over the declaration order. I.e. the126 order in which the user provided them to the CLI is respected.127128 This behavior and its effect on callback evaluation is detailed at:129 https://click.palletsprojects.com/en/stable/advanced/#callback-evaluation-order130 """131132 def sort_key(item: "Parameter") -> t.Tuple[bool, float]:133 try:
1096 unmodified lines
1230 self.epilog = epilog1231 self.options_metavar = options_metavar1232 self.short_help = short_help1233 self.add_help_option = add_help_option1234 self._help_option: t.Optional[HelpOption] = None1235 self.no_args_is_help = no_args_is_help1236 self.hidden = hidden1237 self.deprecated = deprecated1238
57 unmodified lines
1296 def get_help_option(self, ctx: Context) -> t.Optional["Option"]:1297 """Returns the help option object.12981299 Unless ``add_help_option`` is ``False``.13001301 .. versionchanged:: 8.1.81302 The help option is now cached to avoid creating it multiple times.1303 """1304 help_options = self.get_help_option_names(ctx)13051306 if not help_options or not self.add_help_option:1307 return None13081309 # Cache the help option object in private _help_option attribute to1310 # avoid creating it multiple times. Not doing this will break the1311 # callback odering by iter_params_for_processing(), which relies on1312 # object comparison.1313 if self._help_option is None:1297 # Avoid circular import.1298 from .decorators import HelpOption1314 # Avoid circular import.1315 from .decorators import HelpOption13161300 return HelpOption(help_options)1317 self._help_option = HelpOption(help_options)13181319 return self._help_option13201321 def make_parser(self, ctx: Context) -> OptionParser:1322 """Creates the underlying option parser for this command."""1323 parser = OptionParser(ctx)1324 for param in self.get_params(ctx):
1723 unmodified lines
modified:tests/test_commands.py+132 added
303 unmodified lines
304 result = runner.invoke(cli, ["b"], default_map={"b": {"x": 3}})305 assert result.exit_code == 0306307308@pytest.mark.parametrize(309 ("invocation_order", "declaration_order", "expected_order"),310 [311 # Non-eager options.312 ([], ["-a"], ["-a"]),313 (["-a"], ["-a"], ["-a"]),314 ([], ["-a", "-c"], ["-a", "-c"]),315 (["-a"], ["-a", "-c"], ["-a", "-c"]),316 (["-c"], ["-a", "-c"], ["-c", "-a"]),317 ([], ["-c", "-a"], ["-c", "-a"]),318 (["-a"], ["-c", "-a"], ["-a", "-c"]),319 (["-c"], ["-c", "-a"], ["-c", "-a"]),320 (["-a", "-c"], ["-a", "-c"], ["-a", "-c"]),321 (["-c", "-a"], ["-a", "-c"], ["-c", "-a"]),322 # Eager options.323 ([], ["-b"], ["-b"]),324 (["-b"], ["-b"], ["-b"]),325 ([], ["-b", "-d"], ["-b", "-d"]),326 (["-b"], ["-b", "-d"], ["-b", "-d"]),327 (["-d"], ["-b", "-d"], ["-d", "-b"]),328 ([], ["-d", "-b"], ["-d", "-b"]),329 (["-b"], ["-d", "-b"], ["-b", "-d"]),330 (["-d"], ["-d", "-b"], ["-d", "-b"]),331 (["-b", "-d"], ["-b", "-d"], ["-b", "-d"]),332 (["-d", "-b"], ["-b", "-d"], ["-d", "-b"]),333 # Mixed options.334 ([], ["-a", "-b", "-c", "-d"], ["-b", "-d", "-a", "-c"]),335 (["-a"], ["-a", "-b", "-c", "-d"], ["-b", "-d", "-a", "-c"]),336 (["-b"], ["-a", "-b", "-c", "-d"], ["-b", "-d", "-a", "-c"]),337 (["-c"], ["-a", "-b", "-c", "-d"], ["-b", "-d", "-c", "-a"]),338 (["-d"], ["-a", "-b", "-c", "-d"], ["-d", "-b", "-a", "-c"]),339 (["-a", "-b"], ["-a", "-b", "-c", "-d"], ["-b", "-d", "-a", "-c"]),340 (["-b", "-a"], ["-a", "-b", "-c", "-d"], ["-b", "-d", "-a", "-c"]),341 (["-d", "-c"], ["-a", "-b", "-c", "-d"], ["-d", "-b", "-c", "-a"]),342 (["-c", "-d"], ["-a", "-b", "-c", "-d"], ["-d", "-b", "-c", "-a"]),343 (["-a", "-b", "-c", "-d"], ["-a", "-b", "-c", "-d"], ["-b", "-d", "-a", "-c"]),344 (["-b", "-d", "-a", "-c"], ["-a", "-b", "-c", "-d"], ["-b", "-d", "-a", "-c"]),345 ([], ["-b", "-d", "-e", "-a", "-c"], ["-b", "-d", "-e", "-a", "-c"]),346 (["-a", "-d"], ["-b", "-d", "-e", "-a", "-c"], ["-d", "-b", "-e", "-a", "-c"]),347 (["-c", "-d"], ["-b", "-d", "-e", "-a", "-c"], ["-d", "-b", "-e", "-c", "-a"]),348 ],349)350def test_iter_params_for_processing(351 invocation_order, declaration_order, expected_order352):353 parameters = {354 "-a": click.Option(["-a"]),355 "-b": click.Option(["-b"], is_eager=True),356 "-c": click.Option(["-c"]),357 "-d": click.Option(["-d"], is_eager=True),358 "-e": click.Option(["-e"], is_eager=True),359 }360361 invocation_params = [parameters[opt_id] for opt_id in invocation_order]362 declaration_params = [parameters[opt_id] for opt_id in declaration_order]363 expected_params = [parameters[opt_id] for opt_id in expected_order]364365 assert (366 click.core.iter_params_for_processing(invocation_params, declaration_params)367 == expected_params368 )369370371def test_help_param_priority(runner):372 """Cover the edge-case in which the eagerness of help option was not373 respected, because it was internally generated multiple times.374375 See: https://github.com/pallets/click/pull/2811376 """377378 def print_and_exit(ctx, param, value):379 if value:380 click.echo(f"Value of {param.name} is: {value}")381 ctx.exit()382383 @click.command(context_settings={"help_option_names": ("--my-help",)})384 @click.option("-a", is_flag=True, expose_value=False, callback=print_and_exit)385 @click.option(386 "-b", is_flag=True, expose_value=False, callback=print_and_exit, is_eager=True387 )388 def cli():389 pass390391 # --my-help is properly called and stop execution.392 result = runner.invoke(cli, ["--my-help"])393 assert "Value of a is: True" not in result.stdout394 assert "Value of b is: True" not in result.stdout395 assert "--my-help" in result.stdout396 assert result.exit_code == 0397398 # -a is properly called and stop execution.399 result = runner.invoke(cli, ["-a"])400 assert "Value of a is: True" in result.stdout401 assert "Value of b is: True" not in result.stdout402 assert "--my-help" not in result.stdout403 assert result.exit_code == 0404405 # -a takes precedence over -b and stop execution.406 result = runner.invoke(cli, ["-a", "-b"])407 assert "Value of a is: True" not in result.stdout408 assert "Value of b is: True" in result.stdout409 assert "--my-help" not in result.stdout410 assert result.exit_code == 0411412 # --my-help is eager by default so takes precedence over -a and stop413 # execution, whatever the order.414 for args in [["-a", "--my-help"], ["--my-help", "-a"]]:415 result = runner.invoke(cli, args)416 assert "Value of a is: True" not in result.stdout417 assert "Value of b is: True" not in result.stdout418 assert "--my-help" in result.stdout419 assert result.exit_code == 0420421 # Both -b and --my-help are eager so they're called in the order they're422 # invoked by the user.423 result = runner.invoke(cli, ["-b", "--my-help"])424 assert "Value of a is: True" not in result.stdout425 assert "Value of b is: True" in result.stdout426 assert "--my-help" not in result.stdout427 assert result.exit_code == 0428429 # But there was a bug when --my-help is called before -b, because the430 # --my-help option created by click via help_option_names is internally431 # created twice and is not the same object, breaking the priority order432 # produced by iter_params_for_processing.433 result = runner.invoke(cli, ["--my-help", "-b"])434 assert "Value of a is: True" not in result.stdout435 assert "Value of b is: True" not in result.stdout436 assert "--my-help" in result.stdout437 assert result.exit_code == 0438439440def test_unprocessed_options(runner):441 @click.command(context_settings=dict(ignore_unknown_options=True))442 @click.argument("args", nargs=-1, type=click.UNPROCESSED)443 @click.option("--verbose", "-v", count=True)
100 unmodified lines
modified:CHANGES.rst+3 added
16 unmodified lines
17- Fix ``click.echo(color=...)`` passing ``color`` to coloroma so it can be18 forced on Windows. :issue:`2606`.19- More robust bash version check, fixing problem on Windows with git-bash.20 :issue:`2638`21- Cache the help option generated by the ``help_option_names`` setting to22 respect its eagerness. :pr:`2811`232425Version 8.1.726-------------2728Released 2023-08-17
1100 unmodified lines