Skip to content

Fall back to utf-8 when chardet's encoding cannot decode a file - #4030

Open
ekanshul wants to merge 5 commits into
codespell-project:mainfrom
ekanshul:fix-3985-chardet-encoding-fallback
Open

ekanshul wants to merge 5 commits into
codespell-project:mainfrom
ekanshul:fix-3985-chardet-encoding-fallback

Conversation

@ekanshul

Copy link
Copy Markdown
Contributor

Fixes #3985

--hard-encoding-detection crashed when chardet chose an encoding that later failed to decode the file. open() itself rarely raises UnicodeDecodeError; the failure happens while reading, and there was no fallback.

The chardet path now:

  • treats a missing/unknown encoding as a decode failure
  • lets read-time UnicodeDecodeError and LookupError propagate
  • warns and falls back to the existing utf-8 / iso-8859-1 opener

A test feeds a fake detector that reports ascii for a UTF-8 file containing naïve plus a typo, and checks that the file is still scanned as utf-8.

--hard-encoding-detection crashed if chardet picked an encoding that
failed while reading, because only open() was wrapped and there was
no fallback. Catch UnicodeDecodeError and LookupError from the
chardet path, warn, and reuse the utf-8 / iso-8859-1 opener.

Fixes codespell-project#3985
Comment thread codespell_lib/_codespell.py Outdated
Comment on lines +253 to +254
encoding = getattr(self, "detected_encoding", None)
if not self.quiet_level & QuietLevels.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.

I may be missing something, but I believe encoding belongs inside the if:

Suggested change
encoding = getattr(self, "detected_encoding", None)
if not self.quiet_level & QuietLevels.ENCODING:
if not self.quiet_level & QuietLevels.ENCODING:
encoding = getattr(self, "detected_encoding", None)

But where exactly is detected_encoding defined?

Comment thread codespell_lib/_codespell.py Outdated
return self.open_with_chardet(filename)
try:
return self.open_with_chardet(filename)
except (UnicodeDecodeError, LookupError):

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.

Why merge the UnicodeDecodeError/LookupError conditionals of the initial code into a single one?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Fallback to utf-8 or iso-8859-1 if decoding using chardet-detected encoding fails

2 participants