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 Nov 24, 2024
1 parent 9f8ef00 commit ff319ab
Showing 1 changed file with 17 additions and 3 deletions.
20 changes: 17 additions & 3 deletions codespell_lib/_codespell.py
Original file line number Diff line number Diff line change
Expand Up @@ -372,6 +372,20 @@ def _supports_ansi_colors() -> bool:
return False


def _check_positive_int(value: str) -> int:
try:
i = int(value)
except ValueError:
# same message as argparse type
message = f"invalid {int.__name__} value: {value!r}"
raise argparse.ArgumentTypeError(message)
if i < 0:
# message similar to argparse choices
message = f"invalid choice: {value} (choose a positive integer)"
raise argparse.ArgumentTypeError(message)
return i


def parse_options(
args: Sequence[str],
) -> Tuple[argparse.Namespace, argparse.ArgumentParser, List[str]]:
Expand Down Expand Up @@ -598,21 +612,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

0 comments on commit ff319ab

Please sign in to comment.