Skip to content

Commit

Permalink
Merge pull request #191 from DanCardin/dc/default-none-format
Browse files Browse the repository at this point in the history
fix: Default formatting when value is None/Empty and formatter is supplied.
  • Loading branch information
DanCardin authored Dec 24, 2024
2 parents a49bce4 + 8afb682 commit 7b9cd2e
Show file tree
Hide file tree
Showing 4 changed files with 29 additions and 4 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -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"}
Expand Down
13 changes: 10 additions & 3 deletions src/cappa/default.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
14 changes: 14 additions & 0 deletions tests/arg/test_show_default.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from __future__ import annotations

import re
from dataclasses import dataclass

import pytest
Expand Down Expand Up @@ -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)

0 comments on commit 7b9cd2e

Please sign in to comment.