From 19e076f0afbac7bf94536f34648461d7a0f05817 Mon Sep 17 00:00:00 2001 From: KotlinIsland <65446343+kotlinisland@users.noreply.github.com> Date: Thu, 28 Mar 2024 09:45:59 +1000 Subject: [PATCH] show envvar in error hint --- CHANGES.rst | 2 ++ src/click/core.py | 9 ++++++--- tests/test_options.py | 16 ++++++++++++++++ 3 files changed, 24 insertions(+), 3 deletions(-) diff --git a/CHANGES.rst b/CHANGES.rst index 7f1530ab4..9c140599b 100644 --- a/CHANGES.rst +++ b/CHANGES.rst @@ -31,6 +31,8 @@ Unreleased - When generating a command's name from a decorated function's name, the suffixes ``_command``, ``_cmd``, ``_group``, and ``_grp`` are removed. :issue:`2322` +- If ``show_envvar`` then show env var in error messages. + :issue:`2695` Version 8.1.7 diff --git a/src/click/core.py b/src/click/core.py index a7625fad9..3174f7cd5 100644 --- a/src/click/core.py +++ b/src/click/core.py @@ -2332,7 +2332,10 @@ def get_error_hint(self, ctx: Context) -> str: indicate which param caused the error. """ hint_list = self.opts or [self.human_readable_name] - return " / ".join(f"'{x}'" for x in hint_list) + result = " / ".join(f"'{x}'" for x in hint_list) + if self.show_envvar: + result += f" (env var: '{self.envvar}')" + return result def shell_complete(self, ctx: Context, incomplete: str) -> list[CompletionItem]: """Return a list of completions for the incomplete value. If a @@ -2372,8 +2375,8 @@ class Option(Parameter): For single option boolean flags, the default remains hidden if its value is ``False``. :param show_envvar: Controls if an environment variable should be - shown on the help page. Normally, environment variables are not - shown. + shown on the help page and error messages. + Normally, environment variables are not shown. :param prompt: If set to ``True`` or a non empty string then the user will be prompted for input. If set to ``True`` the prompt will be the option name capitalized. diff --git a/tests/test_options.py b/tests/test_options.py index 91249b234..a14db5fd1 100644 --- a/tests/test_options.py +++ b/tests/test_options.py @@ -527,6 +527,22 @@ def cmd(foo): assert "bar" in choices +def test_missing_envvar(runner): + cli = click.Command( + "cli", params=[click.Option(["--foo"], envvar="bar", required=True)] + ) + result = runner.invoke(cli) + assert result.exit_code == 2 + assert "Error: Missing option '--foo'." in result.output + cli = click.Command( + "cli", + params=[click.Option(["--foo"], envvar="bar", show_envvar=True, required=True)], + ) + result = runner.invoke(cli) + assert result.exit_code == 2 + assert "Error: Missing option '--foo' (env var: 'bar')." in result.output + + def test_case_insensitive_choice(runner): @click.command() @click.option("--foo", type=click.Choice(["Orange", "Apple"], case_sensitive=False))