diff --git a/doc/whatsnew/fragments/7522.bugfix b/doc/whatsnew/fragments/7522.bugfix new file mode 100644 index 0000000000..f4fa9da1af --- /dev/null +++ b/doc/whatsnew/fragments/7522.bugfix @@ -0,0 +1,3 @@ +Fixed an issue where ``syntax-error`` couldn't be raised on files with invalid encodings. + +Closes #7522 diff --git a/pylint/lint/pylinter.py b/pylint/lint/pylinter.py index 28ad79e4ca..cb528c5df7 100644 --- a/pylint/lint/pylinter.py +++ b/pylint/lint/pylinter.py @@ -1013,9 +1013,12 @@ def get_ast( data, modname, filepath ) except astroid.AstroidSyntaxError as ex: + line = getattr(ex.error, "lineno", None) + if line is None: + line = 0 self.add_message( "syntax-error", - line=getattr(ex.error, "lineno", 0), + line=line, col_offset=getattr(ex.error, "offset", None), args=f"Parsing failed: '{ex.error}'", confidence=HIGH, diff --git a/tests/regrtest_data/invalid_encoding.py b/tests/regrtest_data/invalid_encoding.py new file mode 100644 index 0000000000..d508d19df8 --- /dev/null +++ b/tests/regrtest_data/invalid_encoding.py @@ -0,0 +1 @@ +# -*- coding: lala -*- diff --git a/tests/test_self.py b/tests/test_self.py index c382edb196..a69b45aaf0 100644 --- a/tests/test_self.py +++ b/tests/test_self.py @@ -1191,6 +1191,11 @@ def test_ignore_path_recursive_current_dir(self) -> None: code=0, ) + def test_syntax_error_invalid_encoding(self) -> None: + module = join(HERE, "regrtest_data", "invalid_encoding.py") + expected_output = "unknown encoding" + self._test_output([module, "-E"], expected_output=expected_output) + class TestCallbackOptions: """Test for all callback options we support."""