Skip to content

Read declared PO charset before decoding header comments - #1495

Open
manav4u wants to merge 1 commit into
python-babel:masterfrom
manav4u:fix-po-header-charset-bootstrap
Open

manav4u wants to merge 1 commit into
python-babel:masterfrom
manav4u:fix-po-header-charset-bootstrap

Conversation

@manav4u

@manav4u manav4u commented Nov 26, 2026

Copy link
Copy Markdown

Binary read_po() starts decoding with UTF-8 and only applies the catalog's declared charset after parsing the header entry. A non-UTF8 translator comment or metadata value before Content-Type therefore raises UnicodeDecodeError before the declaration can take effect.

Babel can produce the input itself:

from io import BytesIO
from babel.messages import Catalog, pofile

catalog = Catalog(locale='fr', charset='iso-8859-1', header_comment='# René')
catalog.add('drink', 'café')
out = BytesIO()
pofile.write_po(out, catalog)
pofile.read_po(BytesIO(out.getvalue()))  # UnicodeDecodeError on current master

The same problem occurs with Vim's French catalog, which declares ISO-8859-15 and has non-ASCII translator comments before its header.

Buffer the first binary header entry, read its declared charset, then replay the original lines through the existing parser. Text streams and explicit charset calls keep their current behavior. The scan stops at the first entry and does not search translated message text for a charset. Placeholder CHARSET, unknown-codec errors, single-use iterators and existing malformed-header errors are covered.

Validation:

  • 30 added public-API cases fail before the fix; the PO-read test file passes 77 cases after. A separate new-helper lookahead test is not counted as a behavioral reproducer.
  • Full suites on Python 3.10 and 3.14, Linux/TZ=UTC: 8334 passed, 3 skipped, 2 xfailed each.
  • 933 authentic catalog paths checked. Ten previously failing paths, nine distinct contents, now match an explicit-charset reference including comments and metadata. No previously successful catalogs changed. A separate Big5 file still has an invalid date and is not claimed fixed.
  • Ruff and diff checks pass. Mypy reports the same 15 pre-existing diagnostics on base and patch.

This was found during a real-catalog roundtrip investigation. The fix and tests were prepared with AI assistance and executed locally. The independent MO metadata fix in #1375 is outside this patch.

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants