diff --git a/doc/whatsnew/fragments/7202.bugfix b/doc/whatsnew/fragments/7202.bugfix new file mode 100644 index 00000000000..4c29748ac99 --- /dev/null +++ b/doc/whatsnew/fragments/7202.bugfix @@ -0,0 +1,3 @@ +Fix crash when regex option raises a `re.error` exception. + +Closes #7202 diff --git a/pylint/config/argument.py b/pylint/config/argument.py index 3c295151764..7dcdd737a89 100644 --- a/pylint/config/argument.py +++ b/pylint/config/argument.py @@ -99,6 +99,18 @@ def _py_version_transformer(value: str) -> tuple[int, ...]: return version +def _regex_transformer(value: str) -> Pattern[str]: + """Return `re.compile(value)`.""" + try: + return re.compile(value) + except re.error as e: + msg = ( + f"\nProvided regular expression: {e.pattern}\n" + f"Error beginning at index {e.pos}: {e.msg}" + ) + raise argparse.ArgumentTypeError(msg) + + def _regexp_csv_transfomer(value: str) -> Sequence[Pattern[str]]: """Transforms a comma separated list of regular expressions.""" patterns: list[Pattern[str]] = [] @@ -130,7 +142,7 @@ def _regexp_paths_csv_transfomer(value: str) -> Sequence[Pattern[str]]: "non_empty_string": _non_empty_string_transformer, "path": _path_transformer, "py_version": _py_version_transformer, - "regexp": re.compile, + "regexp": _regex_transformer, "regexp_csv": _regexp_csv_transfomer, "regexp_paths_csv": _regexp_paths_csv_transfomer, "string": pylint_utils._unquote, diff --git a/tests/config/test_config.py b/tests/config/test_config.py index 47891aee250..c96bcd9724d 100644 --- a/tests/config/test_config.py +++ b/tests/config/test_config.py @@ -111,6 +111,20 @@ def test_unknown_py_version(capsys: CaptureFixture) -> None: assert "the-newest has an invalid format, should be a version string." in output.err +def test_regex_error(capsys: CaptureFixture) -> None: + """Check that we correctly error when an an option is passed whose value is an invalid regular expression.""" + with pytest.raises(SystemExit): + Run( + [str(EMPTY_MODULE), r"--function-rgx=[\p{Han}a-z_][\p{Han}a-z0-9_]{2,30}$"], + exit=False, + ) + output = capsys.readouterr() + assert ( + "Provided regular expression: [\\p{Han}a-z_][\\p{Han}a-z0-9_]{2,30}$\nError beginning at index 1: bad escape \\p" + in output.err + ) + + def test_short_verbose(capsys: CaptureFixture) -> None: """Check that we correctly handle the -v flag.""" Run([str(EMPTY_MODULE), "-v"], exit=False)