diff --git a/codespell_lib/_codespell.py b/codespell_lib/_codespell.py index f5d9c7595d..e94581974f 100644 --- a/codespell_lib/_codespell.py +++ b/codespell_lib/_codespell.py @@ -299,23 +299,24 @@ def open_with_chardet( break self.encdetector.close() encoding = self.encdetector.result["encoding"] - try: - f = open(filename, encoding=encoding, newline="") + with open(filename, encoding=encoding or "", newline="") as f: + return self.get_lines(f), f.encoding except UnicodeDecodeError: - print(f"ERROR: Could not detect encoding: {filename}", file=sys.stderr) - raise + if not self.quiet_level & QuietLevels.ENCODING: + print( + f'WARNING: Cannot decode file using encoding "{encoding}": ' + f"{filename}", + file=sys.stderr, + ) except LookupError: - print( - f"ERROR: Don't know how to handle encoding {encoding}: {filename}", - file=sys.stderr, - ) - raise - else: - lines = self.get_lines(f) - f.close() - - return lines, f.encoding + if not self.quiet_level & QuietLevels.ENCODING: + print( + f"WARNING: Don't know how to handle encoding {encoding}: " + f"{filename}", + file=sys.stderr, + ) + return self.open_with_internal(filename) def open_with_internal( self, filename: str diff --git a/tests/test_basic.py b/tests/test_basic.py index b0abdf9d5c..eabbae7eaa 100644 --- a/tests/test_basic.py +++ b/tests/test_basic.py @@ -21,6 +21,7 @@ EX_DATAERR, EX_OK, EX_USAGE, + FileOpener, _builtin_dictionaries, uri_regex_def, ) @@ -766,6 +767,32 @@ def test_unknown_encoding_chardet( assert cs.main("--hard-encoding-detection", fname) == 0 +@pytest.mark.parametrize("detected_encoding", ["ascii", None, "unknown-codec"]) +@pytest.mark.parametrize("quiet_level", [0, 1]) +def test_chardet_falls_back_when_detected_encoding_fails( + detected_encoding: Optional[str], + quiet_level: int, + tmp_path: Path, + capsys: pytest.CaptureFixture[str], +) -> None: + """If chardet picks an encoding that cannot decode the file, try utf-8.""" + fname = tmp_path / "tmp" + fname.write_bytes("na\u00efve\nspeling\n".encode()) + opener = FileOpener(False, quiet_level, None) + opener.use_chardet = True + + opener.encdetector = mock.Mock(done=True, result={"encoding": detected_encoding}) + lines, encoding = opener.open(str(fname)) + assert encoding == "utf-8" + assert any("speling" in "".join(chunk) for _ignored, _lineno, chunk in lines) + captured = capsys.readouterr() + if quiet_level: + assert not captured.err + else: + assert str(detected_encoding) in captured.err + assert "WARNING" in captured.err + + def test_ignore( tmp_path: Path, capsys: pytest.CaptureFixture[str],