Skip to content

Commit

Permalink
Check value of command-line options
Browse files Browse the repository at this point in the history
  • Loading branch information
DimitriPapadopoulos committed Jun 2, 2024
1 parent 1b6f7eb commit 251976f
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 4 deletions.
20 changes: 17 additions & 3 deletions codespell_lib/_codespell.py
Original file line number Diff line number Diff line change
Expand Up @@ -348,6 +348,20 @@ def _supports_ansi_colors() -> bool:
return False


def _check_positive_int(value: str) -> int:
try:
i = int(value)
except ValueError:

Check warning on line 354 in codespell_lib/_codespell.py

View check run for this annotation

Codecov / codecov/patch

codespell_lib/_codespell.py#L354

Added line #L354 was not covered by tests
# same message as argparse type
message = f"invalid {int.__name__} value: {value!r}"
raise argparse.ArgumentTypeError(message)

Check warning on line 357 in codespell_lib/_codespell.py

View check run for this annotation

Codecov / codecov/patch

codespell_lib/_codespell.py#L356-L357

Added lines #L356 - L357 were not covered by tests
if i < 0:
# message similar to argparse choices
message = f"invalid choice: {value} (choose a positive integer)"
raise argparse.ArgumentTypeError(message)

Check warning on line 361 in codespell_lib/_codespell.py

View check run for this annotation

Codecov / codecov/patch

codespell_lib/_codespell.py#L360-L361

Added lines #L360 - L361 were not covered by tests
return i


def parse_options(
args: Sequence[str],
) -> Tuple[argparse.Namespace, argparse.ArgumentParser, List[str]]:
Expand Down Expand Up @@ -557,21 +571,21 @@ def parse_options(
parser.add_argument(
"-A",
"--after-context",
type=int,
type=_check_positive_int,
metavar="LINES",
help="print LINES of trailing context",
)
parser.add_argument(
"-B",
"--before-context",
type=int,
type=_check_positive_int,
metavar="LINES",
help="print LINES of leading context",
)
parser.add_argument(
"-C",
"--context",
type=int,
type=_check_positive_int,
metavar="LINES",
help="print LINES of surrounding context",
)
Expand Down
1 change: 0 additions & 1 deletion codespell_lib/tests/test_basic.py
Original file line number Diff line number Diff line change
Expand Up @@ -237,7 +237,6 @@ def test_interactivity(
try:
assert cs.main(fname) == 0, "empty file"
fname.write_text("abandonned\n")
assert cs.main("-i", "-1", fname) == 1, "bad"
with FakeStdin("y\n"):
assert cs.main("-i", "3", fname) == 1
with FakeStdin("n\n"):
Expand Down

0 comments on commit 251976f

Please sign in to comment.