Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 15 additions & 14 deletions codespell_lib/_codespell.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please minimize changes, don't change existing code without reason:

Suggested change
with open(filename, encoding=encoding or "", newline="") as f:
with open(filename, encoding=encoding, newline="") as f:

Also, why add this inside the try? It doesn't improve the code in any way, just makes it less precise.

                return self.get_lines(f), f.encoding

Which LLM did you use to obtain such changes?

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}": '

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please don't split this string, changes need to be minimal.

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}: "

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please don't split this string, changes need to be minimal.

f"{filename}",
file=sys.stderr,
)
return self.open_with_internal(filename)

def open_with_internal(
self, filename: str
Expand Down
27 changes: 27 additions & 0 deletions tests/test_basic.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
EX_DATAERR,
EX_OK,
EX_USAGE,
FileOpener,
_builtin_dictionaries,
uri_regex_def,
)
Expand Down Expand Up @@ -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],
Expand Down
Loading