Give a UserWarning when Parameter is overriden by name (#2397)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Ed Rogers · committed by GitHub · parent fcd8503 · Browse files · 4 files·+73 added−4 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
4 files+73 added−4 removed
- tests:+46 added−0 removed
- other:+27 added−4 removed
Provenance
- Commit
3800083- Tree
73b9463- Author
Ed Rogers <edrogers@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
fcd8503
4 files changed+73 added−4 removed
modified:src/click/core.py+25 added-4 removed
6 unmodified lines7 import os8 import sys9 import typing as t10 from collections import abc11+from collections import Counter12 from contextlib import AbstractContextManager13 from contextlib import contextmanager14 from contextlib import ExitStack15 from functools import update_wrapper941 unmodified lines957 self.format_usage(ctx, formatter)958 return formatter.getvalue().rstrip("\n")959 960 def get_params(self, ctx: Context) -> list[Parameter]:960- rv = self.params961+ params = self.params962 help_option = self.get_help_option(ctx)963 964 if help_option is not None:964- rv = [*rv, help_option]965+ params = [*params, help_option]966 966- return rv967+ if __debug__:968+ import warnings969 970+ opts = [opt for param in params for opt in param.opts]971+ opts_counter = Counter(opts)972+ duplicate_opts = (opt for opt, count in opts_counter.items() if count > 1)973+974+ for duplicate_opt in duplicate_opts:975+ warnings.warn(976+ (977+ f"The parameter {duplicate_opt} is used more than once. "978+ "Remove its duplicate as parameters should be unique."979+ ),980+ stacklevel=3,981+ )982+983+ return params984+985 def format_usage(self, ctx: Context, formatter: HelpFormatter) -> None:986 """Writes the usage line into the formatter.987 988 This is a low-level method called by :meth:`get_usage`.1000 unmodified lines1989 given. Takes ``ctx, param, incomplete`` and must return a list1990 of :class:`~click.shell_completion.CompletionItem` or a list of1991 strings.1992 1993+ .. versionchanged:: 8.21994+ Adding duplicate parameter names to a :class:`~click.core.Command` will1995+ result in a ``UserWarning`` being shown.1996+1997 .. versionchanged:: 8.01998 ``process_value`` validates required parameters and bounded1999 ``nargs``, and invokes the parameter callback before returning2000 the value. This allows the callback to validate prompts.993 unmodified lines2994 name = name.replace("-", "_").lower()2995 else:2996 raise TypeError(2997 "Arguments take exactly one parameter declaration, got"2977- f" {len(decls)}."2998+ f" {len(decls)}: {decls}."2999 )3000 return name, [arg], []3001 3002 def get_usage_pieces(self, ctx: Context) -> list[str]:31 unmodified linesmodified:tests/test_arguments.py+20 added
399 unmodified lines400 pass401 402 assert isinstance(foo.params[0], CustomArgument)403 assert isinstance(bar.params[0], CustomArgument)404+405+406+@pytest.mark.parametrize(407+ "args_one,args_two",408+ [409+ (410+ ("aardvark",),411+ ("aardvark",),412+ ),413+ ],414+)415+def test_duplicate_names_warning(runner, args_one, args_two):416+ @click.command()417+ @click.argument(*args_one)418+ @click.argument(*args_two)419+ def cli(one, two):420+ pass421+422+ with pytest.warns(UserWarning):423+ runner.invoke(cli, [])modified:tests/test_options.py+26 added
987 unmodified lines988 assert f"[{'|'.join([str(i) for i in choices])}]" in result.output989 990 result = runner.invoke(cli_without_choices, ["--help"])991 assert metavars in result.output992+993+994+@pytest.mark.parametrize(995+ "opts_one,opts_two",996+ [997+ # No duplicate shortnames998+ (999+ ("-a", "--aardvark"),1000+ ("-a", "--avocado"),1001+ ),1002+ # No duplicate long names1003+ (1004+ ("-a", "--aardvark"),1005+ ("-b", "--aardvark"),1006+ ),1007+ ],1008+)1009+def test_duplicate_names_warning(runner, opts_one, opts_two):1010+ @click.command()1011+ @click.option(*opts_one)1012+ @click.option(*opts_two)1013+ def cli(one, two):1014+ pass1015+1016+ with pytest.warns(UserWarning):1017+ runner.invoke(cli, [])modified:CHANGES.rst+2 added
47 unmodified lines48 - ``Context.close`` will be called on exit. This results in all49 ``Context.call_on_close`` callbacks and context managers added via50 ``Context.with_resource`` to be closed on exit as well. :pr:`2680`51 - Add ``ProgressBar(hidden: bool)`` to allow hiding the progressbar. :issue:`2609`52+- A ``UserWarning`` will be shown when multiple parameters attempt to use the53+ same name. :issue:`2396``54 55 56 Version 8.1.857 -------------1116 unmodified lines