Skip to content

Replace read_str_coding with tokenize.detect_encoding() - #976

Open
NathanTian wants to merge 1 commit into
python-rope:masterfrom
NathanTian:replace-read-str-coding-tokenize
Open

NathanTian wants to merge 1 commit into
python-rope:masterfrom
NathanTian:replace-read-str-coding-tokenize

Conversation

@NathanTian

Copy link
Copy Markdown

Description

Replaces the custom PEP 263 regex + _find_coding() implementation in rope.base.fscommands.read_str_coding() with the standard library tokenize.detect_encoding(), enabling proper UTF-8 BOM (utf-8-sig) detection and handling across reads, edits, and undo/redo history.

Fixes #975

Summary of Changes

  • rope/base/fscommands.py:
    • Replaced CODING_LINE_PATTERN / _find_coding() with tokenize.detect_encoding() in read_str_coding().
    • Added lazy _iter_first_two_lines() splitting only on CRLF/LF/CR (preserving PEP 263 \f on line 1 and avoiding full-file scans on large files), while sanitizing non-ASCII characters on str inputs (preserving a leading U+FEFF BOM) so str inputs with non-UTF-8 coding cookies work cleanly on Python 3.14.1+.
    • Validated detected codecs with "a".encode(encoding) to reject non-text/unusable codecs (e.g. rot_13, undefined) consistently across Python versions, and added a Python < 3.14.1 fallback for valid non-UTF-8 files containing non-ASCII bytes on the coding line itself (e.g. cp1252).
    • Added _decode_data_with_encoding() and prevented duplicate BOM emission in unicode_to_file_data() when utf-8-sig is inferred from a leading U+FEFF.
  • rope/base/resources.py & rope/base/change.py:
    • Tracked UTF-8 BOM presence from raw file bytes (File._has_bom) and preserved it across File.write(), ChangeContents.do()/undo(), and persisted history (4-tuple serialization in ChangeToData / DataToChange).
    • Maintained byte-exact backward compatibility when replaying legacy 3-tuple history records created prior to this change.
  • ropetest/projecttest.py & CHANGELOG.md:
    • Re-enabled test_file_encoding_reading_for_notepad_styles (previously disabled as xxx_test_...).
    • Added unit tests covering BOM + UTF-8 cookie reading, BOM + newline preservation across edit/undo/persisted history, leading body U+FEFF, legacy 3-tuple history replay, cp1252 non-ASCII coding lines, non-text/undefined codecs, and conflicting BOM + coding cookies.
    • Updated CHANGELOG.md under # **Upcoming release**.

Note on Conflicting BOM + Coding Cookie Behavior

Regarding the question in #975 about files with both a UTF-8 BOM and a conflicting non-UTF-8 coding cookie (e.g. \xef\xbb\xbf# -*- coding: latin-1 -*-):

  • read_str_coding() catches SyntaxError / LookupError / UnicodeError and returns None, so File.read() / _decode_data() preserves Rope's existing tolerant fallback (utf-8 -> latin1) for arbitrary/non-Python files.
  • Parsing the file as a Python module (PyModule / ast.parse()) still raises ModuleSyntaxError, matching CPython's behavior.

Happy to adjust this if you prefer File.read() to raise ModuleDecodeError on BOM/cookie conflicts instead.

Verification

  • black --check rope/ — 96 files unchanged
  • pytest -q — 2,188 passed, 11 skipped, 5 xfailed

Checklist (delete if not relevant):

  • I have added tests that prove my fix is effective or that my feature works
  • I have updated CHANGELOG.md

This branch has not been deployed

No deployments
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.

Replace read_str_coding to use tokenize.detect_encoding()

1 participant