Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

show env var in error hint #2696

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGES.rst
Expand Up @@ -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
Expand Down
10 changes: 8 additions & 2 deletions src/click/core.py
Expand Up @@ -2372,8 +2372,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.
Expand Down Expand Up @@ -2551,6 +2551,12 @@ def to_info_dict(self) -> dict[str, t.Any]:
)
return info_dict

def get_error_hint(self, ctx: Context) -> str:
result = super().get_error_hint(ctx)
if self.show_envvar:
result += f" (env var: '{self.envvar}')"
return result

def _parse_decls(
self, decls: cabc.Sequence[str], expose_value: bool
) -> tuple[str | None, list[str], list[str]]:
Expand Down
16 changes: 16 additions & 0 deletions tests/test_options.py
Expand Up @@ -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))
Expand Down