Skip to content

Commit

Permalink
show envvar in error hint
Browse files Browse the repository at this point in the history
  • Loading branch information
KotlinIsland committed Mar 28, 2024
1 parent f8857cb commit a5fb545
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 2 deletions.
2 changes: 2 additions & 0 deletions CHANGES.rst
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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

0 comments on commit a5fb545

Please sign in to comment.