From f798026ff9693fd0d57ccbc0f2016bc10f5e259d Mon Sep 17 00:00:00 2001 From: Dimitri Papadopoulos <3234522+DimitriPapadopoulos@users.noreply.github.com> Date: Tue, 16 Apr 2024 16:23:03 +0200 Subject: [PATCH] Check value of command-line options --- codespell_lib/_codespell.py | 20 +++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/codespell_lib/_codespell.py b/codespell_lib/_codespell.py index 14bd3edc8e..58923aabf8 100644 --- a/codespell_lib/_codespell.py +++ b/codespell_lib/_codespell.py @@ -348,6 +348,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]]: @@ -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", )