Skip to content

Commit

Permalink
Fix crash when regex option raises a re.error exception.
Browse files Browse the repository at this point in the history
  • Loading branch information
mbyrnepr2 committed Jul 25, 2022
1 parent 8ccb526 commit c43153d
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 1 deletion.
3 changes: 3 additions & 0 deletions doc/whatsnew/fragments/7202.bugfix
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Fix crash when regex option raises a `re.error` exception.

Closes #7202
14 changes: 13 additions & 1 deletion pylint/config/argument.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]] = []
Expand Down Expand Up @@ -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,
Expand Down
14 changes: 14 additions & 0 deletions tests/config/test_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down

0 comments on commit c43153d

Please sign in to comment.