Warn when an argument name collide with other parameters
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Fix parsing when a parameter is named `help`, closing #2819
authored by Kevin Deldycke · committed by Kevin Deldycke · parent 8a4ce84 · Browse files · 6 files·+172 added−4 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+172 added−4 removed
- tests:+119 added−1 removed
- other:+53 added−3 removed
Provenance
- Commit
3495fba- Tree
beb6b49- Author
Kevin Deldycke <kevin@deldycke.com>- Committer
Kevin Deldycke <kevin@deldycke.com>- Parent
8a4ce84
6 files changed+172 added−4 removed
modified:docs/documentation.md+1 added-1 removed
320 unmodified lines321 ```322 323 ## Help Parameter Customization324 325-Help parameters are automatically added by Click for any command. The default is `--help` but can be overridden by the context setting {attr}`~Context.help_option_names`. Click also performs automatic conflict resolution on the default help parameter, so if a command itself implements a parameter named `help` then the default help will not be run.325+Help parameters are automatically added by Click for any command. The default is `--help` but can be overridden by the context setting {attr}`~Context.help_option_names`. Click resolves conflicts automatically: an option reusing one of the help option names takes it over, and the default help parameter is dropped once all its names are taken. A parameter merely named `help`, like `click.argument("help")`, does not disable it: both keep working independently.326 327 This example changes the default parameters to `-h` and `--help`328 instead of just `--help`:329 14 unmodified linesmodified:src/click/core.py+44 added-2 removed
53 unmodified lines54 55 F = t.TypeVar("F", bound="t.Callable[..., t.Any]")56 V = t.TypeVar("V")57 58+# Reserved storage name of the automatic help option. No user parameter is59+# expected to claim it.60+_HELP_OPTION_STORAGE_NAME = "_click_default_help"61 62+63 def _complete_visible_commands(64 ctx: Context, incomplete: str65 ) -> cabc.Iterator[tuple[str, Command]]:66 """List all the subcommands of a group that start with the1055 unmodified lines1122 ),1123 stacklevel=3,1124 )1125 1126+ # Options may deliberately share a storage name to compete for1127+ # the same value (feature switches), but an argument sharing a1128+ # name silently overwrites the other parameter's value.1129+ names_counter = Counter(param.name for param in params)1130+ duplicate_names = (1131+ name for name, count in names_counter.items() if count > 11132+ )1133+1134+ for duplicate_name in duplicate_names:1135+ sharers = [param for param in params if param.name == duplicate_name]1136+1137+ if help_option in sharers:1138+ warnings.warn(1139+ (1140+ f"The name {duplicate_name!r} is reserved for the "1141+ "automatic help option. Give the parameter a "1142+ "different name."1143+ ),1144+ stacklevel=3,1145+ )1146+ elif any(isinstance(param, Argument) for param in sharers):1147+ warnings.warn(1148+ (1149+ f"The name {duplicate_name!r} is used by an argument "1150+ "and another parameter. They will overwrite each "1151+ "other's value during parsing. Give each parameter "1152+ "a unique name."1153+ ),1154+ stacklevel=3,1155+ )1156+1157 return params1158 1159 def format_usage(self, ctx: Context, formatter: HelpFormatter) -> None:1160 """Writes the usage line into the formatter.26 unmodified lines1187 """Returns the help option object.1188 1189 Skipped if :attr:`add_help_option` is ``False``.1190 1191+ .. versionchanged:: 8.5.01192+ The help option stores its value under the reserved name1193+ ``_click_default_help``, so a parameter named ``help`` no1194+ longer breaks parsing.1195+1196 .. versionchanged:: 8.1.81197 The help option is now cached to avoid creating it multiple times.1198 """1199 help_option_names = self.get_help_option_names(ctx)8 unmodified lines1208 if self._help_option is None:1209 # Avoid circular import.1210 from .decorators import help_option1211 1172- # Apply help_option decorator and pop resulting option1173- help_option(*help_option_names)(self)1212+ # The help option never exposes its value, so it uses a reserved1213+ # storage name, keeping it clear of user parameters (like an1214+ # argument named "help") that would otherwise clobber its value.1215+ help_option(*help_option_names, _HELP_OPTION_STORAGE_NAME)(self)1216 self._help_option = self.params.pop() # type: ignore[assignment]1217 1218 return self._help_option1219 2504 unmodified linesmodified:tests/test_basic.py+82 added
26 unmodified lines27 assert "I EXECUTED" in result.output28 assert result.exit_code == 029 30 31+@pytest.mark.parametrize(32+ ("help_names", "params", "args", "expected_output"),33+ [34+ (["--help"], [], [], "\n"),35+ (["--help"], [click.Argument(["help"])], ["value"], "value\n"),36+ (37+ ["--help"],38+ [click.Option(["--assist", "help"])],39+ ["--assist", "value"],40+ "value\n",41+ ),42+ (["--man"], [click.Option(["--foo", "man"])], ["--foo", "value"], "value\n"),43+ ],44+ ids=["no-collision", "argument", "option", "custom-flags"],45+)46+def test_param_named_help(runner, help_names, params, args, expected_output):47+ """User parameters never clash with the automatic help option, which48+ stores its value under the reserved ``_click_default_help`` name.49+50+ https://github.com/pallets/click/issues/281951+ """52+ cli = click.Command(53+ "cli",54+ context_settings={"help_option_names": help_names},55+ params=params,56+ callback=lambda **kwargs: click.echo(next(iter(kwargs.values()), None)),57+ )58+59+ ctx = click.Context(cli, help_option_names=help_names)60+ help_option = cli.get_help_option(ctx)61+ assert help_option is not None62+ assert help_option.name == "_click_default_help"63+64+ result = runner.invoke(cli, args)65+ assert result.output == expected_output66+ assert result.exit_code == 067+68+ result = runner.invoke(cli, [help_names[0]])69+ assert "Show this message and exit." in result.output70+ assert result.exit_code == 071+72+73+def test_param_squatting_help_option_name(runner):74+ """Claiming the reserved storage name of the automatic help option75+ triggers a warning.76+ """77+78+ @click.command()79+ @click.argument("_click_default_help")80+ def cli(_click_default_help):81+ click.echo(_click_default_help)82+83+ with pytest.warns(UserWarning, match="reserved for the automatic help option"):84+ result = runner.invoke(cli, ["value"])85+86+ # The collision still breaks parsing, but no longer silently.87+ assert result.exit_code == 288+89+90+def test_option_reusing_help_flag(runner):91+ """An option reusing the ``--help`` flag replaces the automatic help92+ option entirely.93+94+ https://github.com/pallets/click/issues/281995+ """96+97+ @click.command()98+ @click.option("--help", default="default value")99+ def cli(help):100+ click.echo(help)101+102+ assert cli.get_help_option(click.Context(cli)) is None103+104+ result = runner.invoke(cli, [])105+ assert result.output == "default value\n"106+ assert result.exit_code == 0107+108+ result = runner.invoke(cli, ["--help", "custom"])109+ assert result.output == "custom\n"110+ assert result.exit_code == 0111+112+113 def test_repr():114 @click.command()115 def command():116 pass848 unmodified linesmodified:tests/test_info_dict.py+1 added-1 removed
7 unmodified lines8 BOOL_PARAM_TYPE = (click.BOOL, {"param_type": "Bool", "name": "boolean"})9 HELP_OPTION = (10 None,11 {12- "name": "help",12+ "name": "_click_default_help",13 "param_type_name": "option",14 "opts": ["--help"],15 "secondary_opts": [],16 "type": BOOL_PARAM_TYPE[1],299 unmodified linesmodified:tests/test_options.py+36 added
3322 unmodified lines3323 with pytest.warns(UserWarning, match="used more than once"):3324 runner.invoke(cli, [])3325 3326 3327+def test_argument_sharing_param_name_warning(runner):3328+ """An argument sharing its storage name with an option makes both3329+ silently overwrite each other's value, which triggers a warning.3330+ """3331+3332+ @click.command()3333+ @click.option("--foo", "target")3334+ @click.argument("target")3335+ def cli(target):3336+ click.echo(target, nl=False)3337+3338+ with pytest.warns(UserWarning, match="'target' is used by an argument"):3339+ result = runner.invoke(cli, ["--foo", "from_option", "from_argument"])3340+3341+ # The value parsed by the option is lost to the argument's.3342+ assert result.output == "from_argument"3343+ assert result.exit_code == 03344+3345+3346+def test_options_sharing_name_no_warning(runner):3347+ """Options deliberately sharing a storage name (feature switches) are3348+ exempt from the duplicate-name warning. Warnings are errors in this3349+ suite, so a clean run proves none fired.3350+ """3351+3352+ @click.command()3353+ @click.option("--upper", "transformation", flag_value="upper")3354+ @click.option("--lower", "transformation", flag_value="lower")3355+ def cli(transformation):3356+ click.echo(transformation, nl=False)3357+3358+ result = runner.invoke(cli, ["--upper"])3359+ assert result.output == "upper"3360+ assert result.exit_code == 03361+3362+3363 @pytest.mark.parametrize(3364 ("args", "expected"),3365 [3366 (["--with-xyz", "--with-xyz"], True),185 unmodified linesmodified:CHANGES.md+8 added
15 unmodified lines16 does not. The feature set of {func}`version_option` is now frozen; see17 [discussion #3527](https://github.com/pallets/click/discussions/3527). {pr}`3581`18 - `style()` and `secho()` no longer silently drop the 256-color index `0`19 (black) passed as `fg` or `bg`, and now validate color arguments. {pr}`3677`20+- The automatic help option stores its value under the reserved name21+ `_click_default_help` instead of `help`, so a parameter named `help` no22+ longer breaks parsing. The new name is visible in23+ {meth}`Command.to_info_dict` output. Parameters that overwrite each other's24+ value trigger a warning: an argument sharing its name with another25+ parameter, or any parameter claiming the reserved name. Options may still26+ share a name to compete for the same value (feature switches).27+ {issue}`2819` {pr}`3678`28 29 ## Version 8.4.230 31 Released 2026-06-241561 unmodified lines