diff --git a/babel/messages/catalog.py b/babel/messages/catalog.py index 564b2c7c8..e43a28c02 100644 --- a/babel/messages/catalog.py +++ b/babel/messages/catalog.py @@ -10,7 +10,6 @@ import re -from cgi import parse_header from collections import OrderedDict from datetime import datetime, time as time_ from difflib import get_close_matches @@ -225,6 +224,13 @@ class TranslationError(Exception): # FIRST AUTHOR , YEAR. #""" +def parse_separated_header(value: str): + # Adapted from https://peps.python.org/pep-0594/#cgi + from email.message import Message + m = Message() + m['content-type'] = value + return dict(m.get_params()) + class Catalog: """Representation of a message catalog.""" @@ -424,11 +430,11 @@ def _set_mime_headers(self, headers): elif name == 'language-team': self.language_team = value elif name == 'content-type': - mimetype, params = parse_header(value) + params = parse_separated_header(value) if 'charset' in params: self.charset = params['charset'].lower() elif name == 'plural-forms': - _, params = parse_header(' ;' + value) + params = parse_separated_header(' ;' + value) self._num_plurals = int(params.get('nplurals', 2)) self._plural_expr = params.get('plural', '(n != 1)') elif name == 'pot-creation-date': diff --git a/tests/messages/test_pofile.py b/tests/messages/test_pofile.py index 73a7b0ebb..99e59babc 100644 --- a/tests/messages/test_pofile.py +++ b/tests/messages/test_pofile.py @@ -69,6 +69,17 @@ def test_applies_specified_encoding_during_read(self): catalog = pofile.read_po(buf, locale='de_DE') assert catalog.get('foo').string == 'bär' + def test_encoding_header_read(self): + buf = BytesIO(b'msgid ""\nmsgstr ""\n"Content-Type: text/plain; charset=mac_roman\\n"\n') + catalog = pofile.read_po(buf, locale='xx_XX') + assert catalog.charset == 'mac_roman' + + def test_plural_forms_header_parsed(self): + buf = BytesIO(b'msgid ""\nmsgstr ""\n"Plural-Forms: nplurals=42; plural=(n % 11);\\n"\n') + catalog = pofile.read_po(buf, locale='xx_XX') + assert catalog.plural_expr == '(n % 11)' + assert catalog.num_plurals == 42 + def test_read_multiline(self): buf = StringIO(r'''msgid "" "Here's some text that\n"