Skip to content

Commit 75de78b

Browse files
committed
Use Translation.value & .properties for serialization
1 parent 75e2b53 commit 75de78b

4 files changed

Lines changed: 117 additions & 120 deletions

File tree

‎pontoon/sync/core/translations_to_repo.py‎

Lines changed: 52 additions & 81 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99

1010
from moz.l10n.formats import Format
1111
from moz.l10n.formats.xliff import xliff_is_xcode
12-
from moz.l10n.message import message_from_json, parse_message, serialize_message
12+
from moz.l10n.message import message_from_json, serialize_message
1313
from moz.l10n.model import (
1414
CatchallKey,
1515
Entry,
@@ -22,7 +22,7 @@
2222
SelectMessage,
2323
)
2424
from moz.l10n.paths import L10nConfigPaths, L10nDiscoverPaths
25-
from moz.l10n.resource import parse_resource, serialize_resource
25+
from moz.l10n.resource import serialize_resource
2626

2727
from django.conf import settings
2828
from django.db.models import Q
@@ -236,8 +236,11 @@ def update_changed_resources(
236236
)
237237
res = build_moz_l10n_resource(db_res)
238238
for locale in locales:
239-
lc_scope = f"[{project.slug}:{path}, {locale.code}]"
240-
lc_translations = [tx for tx in translations if tx.locale_id == locale.pk]
239+
lc_translations = {
240+
tuple(tx.entity.key): tx
241+
for tx in translations
242+
if tx.locale_id == locale.pk
243+
}
241244
target_path = paths.format_target_path(target, locale.code)
242245
if not lc_translations and not isfile(target_path):
243246
continue
@@ -249,12 +252,14 @@ def update_changed_resources(
249252
for line in serialize_resource(tr_res, gettext_plurals=lc_plurals):
250253
file.write(line)
251254
updated_locales.add(locale)
252-
for tx in lc_translations:
255+
for tx in lc_translations.values():
253256
if tx.approved and tx.entity in changed_entities and tx.user:
254257
translators[tx.user].add(locale.code)
255258
count += 1
256259
except Exception as error:
257-
log.error(f"{lc_scope} Update failed: {error}")
260+
log.error(
261+
f"[{project.slug}:{path}, {locale.code}] Update failed: {error}"
262+
)
258263
continue
259264
return count, updated_locales, translators
260265

@@ -324,60 +329,26 @@ def _entry_from_entity(format: Format, e: Entity) -> Entry[Message]:
324329

325330

326331
def build_translated_resource(
327-
locale: Locale, translations: list[Translation], res: Resource
328-
) -> Resource:
332+
locale: Locale, translations: dict[Id, Translation], res: Resource[Message]
333+
) -> Resource[Message]:
329334
res = deepcopy(res)
330-
if res.format == Format.fluent:
331-
trans_res = parse_resource(
332-
Format.fluent, "".join(tx.string for tx in translations)
333-
)
334-
trans_entries: dict[Id, Entry | None] = {
335-
entry.id: entry
336-
for section in trans_res.sections
337-
for entry in section.entries
338-
if isinstance(entry, Entry)
339-
}
340-
for section in res.sections:
341-
rm: list[Entry] = []
342-
for entry in section.entries:
343-
if isinstance(entry, Entry):
344-
te = trans_entries.get(entry.id, None)
345-
if te is None:
346-
rm.append(entry)
347-
else:
348-
entry.value = te.value
349-
entry.properties = (
350-
te.properties
351-
if entry.id[0].startswith("-")
352-
else {
353-
name: tp
354-
for name, tp in te.properties.items()
355-
if name in entry.properties
356-
}
357-
)
358-
if rm:
359-
section.entries = [e for e in section.entries if e not in rm]
360-
else:
361-
# The iOS locale remapping is a hacky workaround for Xcode projects only,
362-
# so don't apply it to other XLIFF projects.
363-
is_xcode = res.format == Format.xliff and xliff_is_xcode(res)
364-
for section in res.sections:
365-
if (
366-
res.format == Format.xliff
367-
and section.get_meta("@source-language") is not None
368-
):
369-
lc = str(locale.code)
370-
if is_xcode and lc in ios_locale_map:
371-
lc = ios_locale_map[lc]
372-
section.set_meta("@target-language", lc)
373-
374-
rm = []
375-
for entry in section.entries:
376-
if isinstance(entry, Entry):
377-
if not _set_translation(translations, res.format, section, entry):
335+
for section in res.sections:
336+
rm = []
337+
for entry in section.entries:
338+
assert isinstance(entry, Entry)
339+
tx = translations.get(section.id + entry.id, None)
340+
if tx is not None:
341+
_set_translation(res.format, entry, tx)
342+
else:
343+
match res.format:
344+
case Format.gettext if isinstance(entry.value, SelectMessage):
345+
entry.value.variants = {(CatchallKey(),): []}
346+
case Format.gettext | Format.xliff:
347+
entry.value = PatternMessage([])
348+
case _:
378349
rm.append(entry)
379-
if rm and res.format not in (Format.gettext, Format.xliff):
380-
section.entries = [e for e in section.entries if e not in rm]
350+
if rm:
351+
section.entries = [e for e in section.entries if e not in rm]
381352

382353
match res.format:
383354
case Format.gettext:
@@ -392,8 +363,15 @@ def build_translated_resource(
392363
for key, value in header.items()
393364
if key not in gettext_trim_headers
394365
]
366+
395367
case Format.xliff:
396-
pass
368+
lc = str(locale.code)
369+
if xliff_is_xcode(res):
370+
lc = ios_locale_map.get(lc, lc)
371+
for section in res.sections:
372+
if section.get_meta("@source-language") is not None:
373+
section.set_meta("@target-language", lc)
374+
397375
case _:
398376
res.sections = [
399377
section
@@ -403,27 +381,22 @@ def build_translated_resource(
403381
return res
404382

405383

406-
def _set_translation(
407-
translations: list[Translation],
408-
format: Format | None,
409-
section: Section,
410-
entry: Entry,
411-
) -> bool:
412-
key = list(section.id + entry.id)
413-
tx = next((tx for tx in translations if tx.entity.key == key), None)
414-
if tx is None:
415-
if format == Format.gettext:
416-
if isinstance(entry.value, SelectMessage):
417-
entry.value.variants = {(CatchallKey(),): []}
418-
else:
419-
entry.value = PatternMessage([])
420-
return True
421-
else:
422-
return False
423-
384+
def _set_translation(format: Format | None, entry: Entry, tx: Translation) -> None:
424385
match format:
386+
case Format.fluent:
387+
entry.value = message_from_json(tx.value)
388+
is_term = entry.id[0].startswith("-")
389+
entry.properties = (
390+
{
391+
name: message_from_json(pv)
392+
for name, pv in tx.properties.items()
393+
if is_term or name in entry.properties
394+
}
395+
if tx.properties
396+
else {}
397+
)
425398
case Format.android | Format.gettext | Format.webext | Format.xliff:
426-
msg = parse_message(Format.mf2, tx.string)
399+
msg = message_from_json(tx.value)
427400
if isinstance(entry.value, SelectMessage):
428401
entry.value.variants = (
429402
{(CatchallKey(),): msg.pattern}
@@ -443,6 +416,4 @@ def _set_translation(
443416
entry.meta = [m for m in entry.meta if m != fuzzy_flag]
444417

445418
case _:
446-
entry.value = tx.string
447-
448-
return True
419+
entry.value = message_from_json(tx.value)

‎pontoon/sync/tests/test_e2e.py‎

Lines changed: 49 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -78,13 +78,13 @@ def test_kitchen_sink():
7878
resource=res_c,
7979
section=section,
8080
key=[f"key-{i}"],
81-
string=f"key-{i} = Message {i}\n",
81+
value=[f"Message {i}"],
8282
)
8383
for locale in [locale_de, locale_fr]:
8484
TranslationFactory.create(
8585
entity=entity,
8686
locale=locale,
87-
string=f"key-{i} = New translation {locale.code[:2]} {i}\n",
87+
value=[f"New translation {locale.code[:2]} {i}"],
8888
active=True,
8989
approved=True,
9090
)
@@ -258,7 +258,7 @@ def test_add_resources():
258258
resource__project=project, resource__path="file.xliff"
259259
),
260260
locale=locale,
261-
string="xliff translation",
261+
value=["xliff translation"],
262262
active=True,
263263
approved=True,
264264
)
@@ -346,7 +346,7 @@ def test_xliff_html_translation():
346346
TranslationFactory.create(
347347
entity=Entity.objects.get(resource__project=project),
348348
locale=locale,
349-
string="translation: Hello <b>world</b>!",
349+
value=["translation: Hello <b>world</b>!"],
350350
active=True,
351351
approved=True,
352352
)
@@ -433,7 +433,7 @@ def test_xliff_target_language():
433433
resource__project=project, resource__path=path
434434
),
435435
locale=locale,
436-
string="translation",
436+
value=["translation"],
437437
active=True,
438438
approved=True,
439439
)
@@ -459,21 +459,21 @@ def test_translation_before_source():
459459
res_a = ResourceFactory.create(project=project, path="a.ftl", format="fluent")
460460
TranslationFactory.create(
461461
entity=EntityFactory.create(
462-
resource=res_a, key=["a0"], string="a0 = Message 0\n"
462+
resource=res_a, key=["a0"], value=["Message 0"]
463463
),
464464
locale=locale,
465-
string="a0 = Translation 0\n",
465+
value=["Translation 0"],
466466
active=True,
467467
approved=True,
468468
)
469469

470470
res_b = ResourceFactory.create(project=project, path="b.ftl", format="fluent")
471471
TranslationFactory.create(
472472
entity=EntityFactory.create(
473-
resource=res_b, key=["b0"], string="b0 = Message 0\n"
473+
resource=res_b, key=["b0"], value=["Message 0"]
474474
),
475475
locale=locale,
476-
string="b0 = Translation 0\n",
476+
value=["Translation 0"],
477477
active=True,
478478
approved=True,
479479
)
@@ -515,23 +515,23 @@ def test_android():
515515
)
516516

517517
entity = EntityFactory.create(
518-
resource=res, key=["quotes"], string="Prev quotes"
518+
resource=res, key=["quotes"], value=["Prev quotes"]
519519
)
520520
TranslationFactory.create(
521521
entity=entity,
522522
locale=locale,
523-
string="'Hello' \"translation\"",
523+
value=["'Hello' \"translation\""],
524524
active=True,
525525
approved=True,
526526
)
527527

528528
entity = EntityFactory.create(
529-
resource=res, key=["newline"], string="Prev newline"
529+
resource=res, key=["newline"], value=["Prev newline"]
530530
)
531531
TranslationFactory.create(
532532
entity=entity,
533533
locale=locale,
534-
string="translated escaped \n newlines",
534+
value=["translated escaped \n newlines"],
535535
active=True,
536536
approved=True,
537537
)
@@ -579,11 +579,13 @@ def test_gettext_fuzzy():
579579
for i in range(5):
580580
string = f"Message {i}\n"
581581
fuzzy = i < 3
582-
entity = EntityFactory.create(resource=res, key=[f"key-{i}"], string=string)
582+
entity = EntityFactory.create(
583+
resource=res, key=[f"key-{i}"], value=[string]
584+
)
583585
TranslationFactory.create(
584586
entity=entity,
585587
locale=locale,
586-
string=string.replace("Message", "Fuzzy" if fuzzy else "Translation"),
588+
value=[string.replace("Message", "Fuzzy" if fuzzy else "Translation")],
587589
active=True,
588590
approved=not fuzzy,
589591
fuzzy=fuzzy,
@@ -699,12 +701,14 @@ def test_plain_json(caplog):
699701
res = ResourceFactory.create(
700702
project=project, path="old-file.json", format="plain_json"
701703
)
702-
703-
entity = EntityFactory.create(resource=res, key=["o1"], string="Entity 1")
704+
section = SectionFactory.create(resource=res, key=[])
705+
entity = EntityFactory.create(
706+
resource=res, section=section, key=["o1"], value=["Entity 1"]
707+
)
704708
TranslationFactory.create(
705709
entity=entity,
706710
locale=locale,
707-
string="Translation 1",
711+
value=["Translation 1"],
708712
active=True,
709713
approved=True,
710714
)
@@ -794,37 +798,56 @@ def test_webext():
794798
project=project, path="messages.json", format="android"
795799
)
796800

797-
entity = EntityFactory.create(resource=res, key=["plain"], string="Entity")
801+
entity = EntityFactory.create(resource=res, key=["plain"], value=["Entity"])
798802
TranslationFactory.create(
799803
entity=entity,
800804
locale=locale,
801-
string="Translation",
805+
value=["Translation"],
802806
active=True,
803807
approved=True,
804808
)
805809

806810
entity = EntityFactory.create(
807-
resource=res, key=["number"], string="Entity for {$arg1 @source=|$1|}"
811+
resource=res,
812+
key=["number"],
813+
value=["Entity for ", {"$": "arg1", "attr": {"source": "$1"}}],
808814
)
809815
TranslationFactory.create(
810816
entity=entity,
811817
locale=locale,
812-
string="Translation for {$arg1 @source=|$1|}",
818+
value=["Translation for ", {"$": "arg1", "attr": {"source": "$1"}}],
813819
active=True,
814820
approved=True,
815821
)
816822

817823
entity = EntityFactory.create(
818824
resource=res,
819825
key=["name"],
820-
string=".local $ORIGIN = {$arg1 @source=|$1| @example=developer.mozilla.org}\n"
821-
+ "{{Entity for {$ORIGIN @source=|$ORIGIN$|}}}",
826+
value={
827+
"decl": {
828+
"ORIGIN": {
829+
"$": "arg1",
830+
"attr": {"source": "$1", "example": "developer.mozilla.org"},
831+
}
832+
},
833+
"msg": ["Entity for ", {"$": "ORIGIN", "attr": {"source": "ORIGIN"}}],
834+
},
822835
)
823836
TranslationFactory.create(
824837
entity=entity,
825838
locale=locale,
826-
string=".local $ORIGIN = {$arg1 @source=|$1| @example=developer.mozilla.org}\n"
827-
+ "{{Translation for {$ORIGIN @source=|$ORIGIN$|}}}",
839+
value={
840+
"decl": {
841+
"ORIGIN": {
842+
"$": "arg1",
843+
"attr": {"source": "$1", "example": "developer.mozilla.org"},
844+
}
845+
},
846+
"msg": [
847+
"Translation for ",
848+
{"$": "ORIGIN", "attr": {"source": "ORIGIN"}},
849+
],
850+
},
828851
active=True,
829852
approved=True,
830853
)

0 commit comments

Comments
 (0)