Skip to content

Commit

Permalink
Fix % for docstrings in bool flags
Browse files Browse the repository at this point in the history
  • Loading branch information
brentyi committed Jan 8, 2022
1 parent d5da406 commit e2dd680
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 13 deletions.
19 changes: 14 additions & 5 deletions dcargs/_arguments.py
Original file line number Diff line number Diff line change
Expand Up @@ -195,11 +195,20 @@ def _bool_flags(arg: ArgumentDefinition) -> _ArgumentTransformOutput:

# Populate helptext for boolean flags => don't show default value, which can be
# confusing.
helptext = _docstrings.get_field_docstring(arg.parent_class, arg.field.name)
arg = dataclasses.replace(
arg,
help=helptext if helptext is not None else "",
)
docstring_help = _docstrings.get_field_docstring(arg.parent_class, arg.field.name)
if docstring_help is not None:
# Note that the percent symbol needs some extra handling in argparse.
# https://stackoverflow.com/questions/21168120/python-argparse-errors-with-in-help-string
docstring_help = docstring_help.replace("%", "%%")
arg = dataclasses.replace(
arg,
help=docstring_help,
)
else:
arg = dataclasses.replace(
arg,
help="",
)

if arg.default is None:
return (
Expand Down
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

setup(
name="dcargs",
version="0.0.10",
version="0.0.11",
description="Portable, reusable, strongly typed CLIs from dataclass definitions",
long_description=long_description,
long_description_content_type="text/markdown",
Expand Down
11 changes: 4 additions & 7 deletions tests/test_docstrings.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,12 +73,12 @@ class Config:
assert " --x INT An optional variable. (default: None)\n" in helptext


def test_helptext_hard_string():
def test_helptext_hard_bool():
@dataclasses.dataclass
class HelptextHardString:
# fmt: off
x: str = (
"This docstring may be tougher to parse!"
x: bool = (
False
)
"""Helptext. 2% milk."""
# fmt: on
Expand All @@ -91,10 +91,7 @@ class HelptextHardString:
with contextlib.redirect_stdout(f):
dcargs.parse(HelptextHardString, args=["--help"])
helptext = f.getvalue()
assert (
"--x STR Helptext. 2% milk. (default: This docstring may be tougher to parse!)\n"
in helptext
)
assert "--x Helptext. 2% milk.\n" in helptext


def test_helptext_with_inheritance():
Expand Down

0 comments on commit e2dd680

Please sign in to comment.