diff --git a/CHANGELOG.md b/CHANGELOG.md index 2cc99e9..5f7bfd8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,10 @@ ## 0.26 +### 0.26.1 + +- fix: Default formatting when value is None/Empty and formatter is supplied. + ### 0.26.0 - feat: Add `Default` object with associated fallback semantics for sequences of default handlers. diff --git a/pyproject.toml b/pyproject.toml index c2bada3..4d171e4 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "cappa" -version = "0.26.0" +version = "0.26.1" description = "Declarative CLI argument parser." urls = {repository = "https://github.com/dancardin/cappa"} diff --git a/src/cappa/default.py b/src/cappa/default.py index f59236f..3018da5 100644 --- a/src/cappa/default.py +++ b/src/cappa/default.py @@ -222,11 +222,18 @@ def from_unknown(cls, value: str | bool | Self) -> Self: return cls(show=bool(value)) def format_default(self, default: Default, default_format: str = "") -> str: - if not self.show or default.default in (None, Empty): + if not self.show: return "" - default_value = self.format.format(default=default.default) - return default_format.format(default=default_value) + default_raw_value = default.default + if default_raw_value in (None, Empty): + default_raw_value = "" + + default_formatted_value = self.format.format(default=default_raw_value) + if default_formatted_value == "": + return default_formatted_value + + return default_format.format(default=default_formatted_value) PromptType = rich.prompt.Prompt diff --git a/tests/arg/test_show_default.py b/tests/arg/test_show_default.py index 130f114..9f78073 100644 --- a/tests/arg/test_show_default.py +++ b/tests/arg/test_show_default.py @@ -1,5 +1,6 @@ from __future__ import annotations +import re from dataclasses import dataclass import pytest @@ -98,3 +99,16 @@ class Command: stdout = CapsysOutput.from_capsys(capsys).stdout.replace(" ", "") assert "[FOO](Default:!asdf!)" in stdout + + +@backends +def test_static(backend, capsys): + @dataclass + class Command: + foo: Annotated[str | None, cappa.Arg(show_default="always show")] = None + + with pytest.raises(cappa.HelpExit): + parse(Command, "--help", backend=backend) + + stdout = CapsysOutput.from_capsys(capsys).stdout + assert re.search(r"\[FOO\]\s+\(Default: always show\)", stdout)