Skip to content

Commit 8bfa0a8

Browse files
committed
Preserve repeated comment lines when reading PO files
1 parent 6ba6701 commit 8bfa0a8

2 files changed

Lines changed: 35 additions & 2 deletions

File tree

babel/messages/pofile.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -216,11 +216,13 @@ def _add_message(self) -> None:
216216
string,
217217
self.locations,
218218
self.flags,
219-
self.auto_comments,
220-
self.user_comments,
221219
lineno=self.offset + 1,
222220
context=msgctxt,
223221
)
222+
# PO comments are physical lines, including repeated wrapped fragments.
223+
# Preserve them instead of deduplicating them in Message.__init__.
224+
message.auto_comments = self.auto_comments
225+
message.user_comments = self.user_comments
224226
if self.obsolete:
225227
if not self.ignore_obsolete:
226228
self.catalog.obsolete[self.catalog._key_for(msgid, msgctxt)] = message

tests/messages/test_pofile.py

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,37 @@
2020
from babel.messages.pofile import _enclose_filename_if_necessary, _extract_locations
2121

2222

23+
@pytest.mark.parametrize(
24+
('prefix', 'attribute'),
25+
[('#.', 'auto_comments'), ('#', 'user_comments')],
26+
)
27+
@pytest.mark.parametrize('obsolete', [False, True])
28+
def test_read_po_preserves_repeated_comment_lines(prefix, attribute, obsolete):
29+
comments = ['KEY:', 'first.long.key', 'KEY:', 'second.long.key']
30+
source = '\n'.join(f'{prefix} {line}' for line in comments) + '\n'
31+
message_prefix = '#~ ' if obsolete else ''
32+
source += f'{message_prefix}msgid "Example"\n{message_prefix}msgstr ""\n'
33+
34+
catalog = pofile.read_po(StringIO(source))
35+
message = catalog.obsolete['Example'] if obsolete else catalog['Example']
36+
assert getattr(message, attribute) == comments
37+
38+
39+
@pytest.mark.parametrize('attribute', ['auto_comments', 'user_comments'])
40+
def test_wrapped_comments_roundtrip(attribute):
41+
catalog = Catalog()
42+
comments = ['KEY: ' + 'foo.' * 20, 'KEY: ' + 'bar.' * 20]
43+
catalog.add('Example', **{attribute: comments})
44+
first = BytesIO()
45+
pofile.write_po(first, catalog, omit_header=True)
46+
first.seek(0)
47+
48+
restored = pofile.read_po(first)
49+
second = BytesIO()
50+
pofile.write_po(second, restored, omit_header=True)
51+
assert second.getvalue() == first.getvalue()
52+
53+
2354
def test_enclosed_filenames_in_location_comment():
2455
catalog = Catalog()
2556
catalog.add("foo", lineno=2, locations=[("main 1.py", 1)], string="")

0 commit comments

Comments
 (0)