From 2d3f77fbc8173233bca2cf53eb2d60affff4d87c Mon Sep 17 00:00:00 2001 From: abu-tahir-0 Date: Fri, 20 Nov 2026 17:37:46 +0530 Subject: [PATCH] fix: tolerate placeholder nplurals values in PO headers xgettext emits 'nplurals=INTEGER; plural=EXPRESSION;' in POT templates. read_po() called int() on the literal 'INTEGER' and raised ValueError, making such templates impossible to parse. Fall back to the default of two plurals when the value is not an integer, and add a regression test. --- babel/messages/catalog.py | 6 +++++- tests/messages/test_pofile.py | 20 ++++++++++++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/babel/messages/catalog.py b/babel/messages/catalog.py index 0e7417020..2a9fce856 100644 --- a/babel/messages/catalog.py +++ b/babel/messages/catalog.py @@ -591,7 +591,11 @@ def _set_mime_headers(self, headers: Iterable[tuple[str, str]]) -> None: self.charset = params['charset'].lower() elif name == 'plural-forms': params = parse_separated_header(f" ;{value}") - self._num_plurals = int(params.get('nplurals', 2)) + num_plurals = params.get('nplurals', 2) + try: + self._num_plurals = int(num_plurals) + except (TypeError, ValueError): + self._num_plurals = 2 self._plural_expr = params.get('plural', '(n != 1)') elif name == 'pot-creation-date': # Keep last value instead of crashing on blank values diff --git a/tests/messages/test_pofile.py b/tests/messages/test_pofile.py index 00e439b7c..47069ddb4 100644 --- a/tests/messages/test_pofile.py +++ b/tests/messages/test_pofile.py @@ -36,6 +36,26 @@ def test_read_po_preserves_repeated_comment_lines(prefix, attribute, obsolete): assert getattr(message, attribute) == comments +def test_read_po_tolerates_placeholder_plural_forms(): + source = ( + 'msgid ""\n' + 'msgstr ""\n' + '"Content-Type: text/plain; charset=UTF-8\\n"\n' + '"Plural-Forms: nplurals=INTEGER; plural=EXPRESSION;\\n"\n' + "\n" + 'msgid "Hello"\n' + 'msgid_plural "Hellos"\n' + 'msgstr[0] ""\n' + 'msgstr[1] ""\n' + ) + + catalog = pofile.read_po(StringIO(source)) + + assert catalog.num_plurals == 2 + assert catalog.plural_expr == 'EXPRESSION' + assert catalog['Hello'].id == ('Hello', 'Hellos') + + @pytest.mark.parametrize('attribute', ['auto_comments', 'user_comments']) def test_wrapped_comments_roundtrip(attribute): catalog = Catalog()