Skip to content

Commit

Permalink
Added functionality to set flag_value correctly when using envvar (#2788
Browse files Browse the repository at this point in the history
)

Co-authored-by: Andreas Backx <[email protected]>
  • Loading branch information
chips-wq and AndreasBackx authored Nov 3, 2024
1 parent 3800083 commit 1787497
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 3 deletions.
3 changes: 3 additions & 0 deletions CHANGES.rst
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,9 @@ Unreleased
- Add ``ProgressBar(hidden: bool)`` to allow hiding the progressbar. :issue:`2609`
- A ``UserWarning`` will be shown when multiple parameters attempt to use the
same name. :issue:`2396``
- When using ``Option.envvar`` with ``Option.flag_value``, the ``flag_value``
will always be used instead of the value of the environment variable.
:issue:`2746` :pr:`2788`


Version 8.1.8
Expand Down
12 changes: 9 additions & 3 deletions src/click/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -2430,15 +2430,19 @@ class Option(Parameter):
:param hidden: hide this option from help outputs.
:param attrs: Other command arguments described in :class:`Parameter`.
.. versionchanged:: 8.1.0
.. versionchanged:: 8.2
``envvar`` used with ``flag_value`` will always use the ``flag_value``,
previously it would use the value of the environment variable.
.. versionchanged:: 8.1
Help text indentation is cleaned here instead of only in the
``@option`` decorator.
.. versionchanged:: 8.1.0
.. versionchanged:: 8.1
The ``show_default`` parameter overrides
``Context.show_default``.
.. versionchanged:: 8.1.0
.. versionchanged:: 8.1
The default of a single option boolean flag is not shown if the
default value is ``False``.
Expand Down Expand Up @@ -2864,6 +2868,8 @@ def resolve_envvar_value(self, ctx: Context) -> str | None:
rv = super().resolve_envvar_value(ctx)

if rv is not None:
if self.is_flag and self.flag_value:
return str(self.flag_value)
return rv

if (
Expand Down
13 changes: 13 additions & 0 deletions tests/test_arguments.py
Original file line number Diff line number Diff line change
Expand Up @@ -198,6 +198,19 @@ def cmd(arg):
assert result.return_value == expect


def test_envvar_flag_value(runner):
@click.command()
# is_flag is implicitly true
@click.option("--upper", flag_value="upper", envvar="UPPER")
def cmd(upper):
click.echo(upper)
return upper

# For whatever value of the `env` variable, if it exists, the flag should be `upper`
result = runner.invoke(cmd, env={"UPPER": "whatever"})
assert result.output.strip() == "upper"


def test_nargs_envvar_only_if_values_empty(runner):
@click.command()
@click.argument("arg", envvar="X", nargs=-1)
Expand Down

0 comments on commit 1787497

Please sign in to comment.