Skip to content

Commit 965523b

Browse files
committed
Use email.Message for pofile header parsing
cgi.parse_header is due to be deprecated Fixes #873
1 parent d0ec73d commit 965523b

File tree

2 files changed

+20
-3
lines changed

2 files changed

+20
-3
lines changed

babel/messages/catalog.py

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,6 @@
1010

1111
import re
1212

13-
from cgi import parse_header
1413
from collections import OrderedDict
1514
from datetime import datetime, time as time_
1615
from difflib import get_close_matches
@@ -225,6 +224,13 @@ class TranslationError(Exception):
225224
# FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.
226225
#"""
227226

227+
def parse_separated_header(value: str):
228+
# Adapted from https://peps.python.org/pep-0594/#cgi
229+
from email.message import Message
230+
m = Message()
231+
m['content-type'] = value
232+
return dict(m.get_params())
233+
228234

229235
class Catalog:
230236
"""Representation of a message catalog."""
@@ -424,11 +430,11 @@ def _set_mime_headers(self, headers):
424430
elif name == 'language-team':
425431
self.language_team = value
426432
elif name == 'content-type':
427-
mimetype, params = parse_header(value)
433+
params = parse_separated_header(value)
428434
if 'charset' in params:
429435
self.charset = params['charset'].lower()
430436
elif name == 'plural-forms':
431-
_, params = parse_header(' ;' + value)
437+
params = parse_separated_header(' ;' + value)
432438
self._num_plurals = int(params.get('nplurals', 2))
433439
self._plural_expr = params.get('plural', '(n != 1)')
434440
elif name == 'pot-creation-date':

tests/messages/test_pofile.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,17 @@ def test_applies_specified_encoding_during_read(self):
6868
catalog = pofile.read_po(buf, locale='de_DE')
6969
self.assertEqual(u'bär', catalog.get('foo').string)
7070

71+
def test_encoding_header_read(self):
72+
buf = BytesIO(b'msgid ""\nmsgstr ""\n"Content-Type: text/plain; charset=mac_roman\\n"\n')
73+
catalog = pofile.read_po(buf, locale='xx_XX')
74+
assert catalog.charset == 'mac_roman'
75+
76+
def test_plural_forms_header_parsed(self):
77+
buf = BytesIO(b'msgid ""\nmsgstr ""\n"Plural-Forms: nplurals=42; plural=(n % 11);\\n"\n')
78+
catalog = pofile.read_po(buf, locale='xx_XX')
79+
assert catalog.plural_expr == '(n % 11)'
80+
assert catalog.num_plurals == 42
81+
7182
def test_read_multiline(self):
7283
buf = StringIO(r'''msgid ""
7384
"Here's some text that\n"

0 commit comments

Comments
 (0)