-
-
Notifications
You must be signed in to change notification settings - Fork 957
/
ttkit.py
2167 lines (1792 loc) · 66.2 KB
/
ttkit.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright © Michal Čihař <michal@weblate.org>
# Copyright © WofWca <wofwca@protonmail.com>
#
# SPDX-License-Identifier: GPL-3.0-or-later
"""Translate Toolkit based file-format wrappers."""
from __future__ import annotations
import importlib
import inspect
import os
import re
import subprocess
from typing import TYPE_CHECKING, Any, BinaryIO
from django.core.exceptions import ValidationError
from django.utils.functional import cached_property
from django.utils.translation import gettext, gettext_lazy
from lxml import etree
from lxml.etree import XMLSyntaxError
from pyparsing import ParseException
from translate.misc import quote
from translate.misc.multistring import multistring
from translate.misc.xml_helpers import setXMLspace
from translate.storage.base import TranslationStore
from translate.storage.base import TranslationUnit as TranslateToolkitUnit
from translate.storage.csvl10n import csv, csvunit
from translate.storage.jsonl10n import BaseJsonUnit, JsonFile
from translate.storage.lisa import LISAfile
from translate.storage.po import pofile, pounit
from translate.storage.poxliff import PoXliffFile
from translate.storage.resx import RESXFile
from translate.storage.tbx import tbxfile, tbxunit
from translate.storage.ts2 import tsfile, tsunit
from translate.storage.xliff import ID_SEPARATOR, xlifffile, xliffunit
import weblate.utils.version
from weblate.checks.flags import Flags
from weblate.formats.base import (
BilingualUpdateMixin,
TranslationFormat,
TranslationUnit,
UpdateError,
)
from weblate.lang.data import FORMULA_WITH_ZERO, ZERO_PLURAL_TYPES
from weblate.lang.models import Plural
from weblate.trans.util import (
get_clean_env,
get_string,
rich_to_xliff_string,
xliff_string_to_rich,
)
from weblate.utils.errors import report_error
from weblate.utils.state import (
STATE_APPROVED,
STATE_EMPTY,
STATE_FUZZY,
STATE_TRANSLATED,
)
if TYPE_CHECKING:
from collections.abc import Callable
LOCATIONS_RE = re.compile(r"^([+-]|.*, [+-]|.*:[+-])")
PO_DOCSTRING_LOCATION = re.compile(r":docstring of [a-zA-Z0-9._]+:[0-9]+")
SUPPORTS_FUZZY = (pounit, tsunit, csvunit)
XLIFF_FUZZY_STATES = {"new", "needs-translation", "needs-adaptation", "needs-l10n"}
class TTKitUnit(TranslationUnit):
template: TranslateToolkitUnit | None
unit: TranslateToolkitUnit
mainunit: TranslateToolkitUnit
parent: TTKitFormat
@cached_property
def locations(self):
"""Return a comma-separated list of locations."""
return ", ".join(self.mainunit.getlocations())
@cached_property
def source(self):
"""Return source string from a Translate Toolkit unit."""
if self.template is not None:
return get_string(self.template.target)
return get_string(self.unit.source)
@cached_property
def target(self):
"""Return target string from a Translate Toolkit unit."""
if self.unit is None:
if self.parent.is_template and self.template is not None:
return get_string(self.template.target)
return ""
return get_string(self.unit.target)
@cached_property
def context(self):
"""
Return context of message.
In some cases we have to use ID here to make all the back-ends consistent.
"""
return self.mainunit.getcontext()
@cached_property
def notes(self):
"""Return notes or notes from units."""
comment = ""
if self.unit is not None:
comment = self.unit.getnotes()
if self.template is not None:
# Avoid duplication in case template has same notes
template_comment = self.template.getnotes()
if template_comment != comment:
comment = f"{template_comment}\n{comment}"
return comment
def is_translated(self):
"""Check whether unit is translated."""
if self.unit is None:
return False
return self.unit.istranslated()
def is_fuzzy(self, fallback=False):
"""Check whether unit needs editing."""
if self.unit is None:
return fallback
# Most of the formats do not support this, but they
# happily return False
if isinstance(self.unit, SUPPORTS_FUZZY):
return self.has_translation() and self.unit.isfuzzy()
return fallback
def has_content(self) -> bool:
"""Check whether unit has content."""
return (
not self.mainunit.isheader()
and not self.mainunit.isblank()
and not self.mainunit.isobsolete()
)
def is_readonly(self) -> bool:
return not self.mainunit.istranslatable()
def set_target(self, target: str | list[str]) -> None:
"""Set translation unit target."""
self._invalidate_target()
if isinstance(target, list):
target = multistring(target)
self.unit.target = target
def set_state(self, state) -> None:
"""Set fuzzy /approved flag on translated unit."""
if "flags" in self.__dict__:
del self.__dict__["flags"]
self.unit.markfuzzy(state == STATE_FUZZY)
if hasattr(self.unit, "markapproved"):
self.unit.markapproved(state == STATE_APPROVED)
@cached_property
def flags(self):
"""
Return flags from unit.
We currently extract maxwidth attribute.
"""
flags = Flags()
if hasattr(self.unit, "xmlelement"):
flags.merge(self.unit.xmlelement)
if self.template is not None and hasattr(self.template, "xmlelement"):
flags.merge(self.template.xmlelement)
return flags.format()
def untranslate(self, language) -> None:
target: str | list[str]
target = [""] * language.plural.number if self.mainunit.hasplural() else ""
self.set_target(target)
self.set_state(STATE_EMPTY)
class KeyValueUnit(TTKitUnit):
@cached_property
def source(self):
"""Return source string from a Translate Toolkit unit."""
if self.template is not None:
return get_string(self.template.source)
return get_string(self.unit.name)
@cached_property
def target(self):
"""Return target string from a Translate Toolkit unit."""
if self.unit is None:
return ""
return get_string(self.unit.source)
@cached_property
def context(self):
"""
Return context of message.
In some cases we have to use ID here to make all the back-ends consistent.
"""
context = super().context
if not context:
return self.mainunit.getid()
return context
def is_translated(self):
"""Check whether unit is translated."""
if self.unit is None:
return False
# The hasattr check here is needed for merged storages
# where template is different kind than translations
if hasattr(self.unit, "value"):
return not self.unit.isfuzzy() and self.unit.value
return self.unit.istranslated()
def set_target(self, target: str | list[str]) -> None:
"""Set translation unit target."""
super().set_target(target)
# Propagate to value so that searializing of empty values works correctly
if not target:
self.unit.value = self.unit.target
class TTKitFormat(TranslationFormat):
unit_class = TTKitUnit
loader = ("", "")
set_context_bilingual = True
# Use settarget/setsource to set language as well
use_settarget = False
force_encoding: None | str = None
plural_preference: tuple[int, ...] | None = (
Plural.SOURCE_CLDR,
Plural.SOURCE_DEFAULT,
)
units: list[TranslateToolkitUnit]
store: TranslationStore
def __init__(
self,
storefile,
template_store=None,
language_code: str | None = None,
source_language: str | None = None,
is_template: bool = False,
existing_units: list[Any] | None = None,
) -> None:
super().__init__(
storefile,
template_store=template_store,
language_code=language_code,
is_template=is_template,
source_language=source_language,
existing_units=existing_units,
)
@staticmethod
def serialize(store):
"""Serialize given Translate Toolkit store."""
return bytes(store)
def fixup(self, store) -> None:
"""Perform optional fixups on store."""
if self.force_encoding is not None:
store.encoding = self.force_encoding
# This gets already native language code, so no conversion is needed
if self.language_code is not None:
store.settargetlanguage(self.language_code)
if self.source_language is not None:
store.setsourcelanguage(self.source_language)
def load(
self, storefile: str | BinaryIO, template_store: TranslationStore | None
) -> TranslationStore:
"""Load file using defined loader."""
if isinstance(storefile, TranslationStore):
# Used by XLSX writer
return storefile
return self.parse_store(storefile)
@classmethod
def get_class(cls):
"""Return class for handling this module."""
# Direct class
if inspect.isclass(cls.loader):
return cls.loader
# Tuple style loader, import from translate toolkit
module_name, class_name = cls.loader
if "." not in module_name:
module_name = f"translate.storage.{module_name}"
module = importlib.import_module(module_name)
# Get the class
return getattr(module, class_name)
@staticmethod
def get_class_kwargs():
return {}
def get_store_instance(self, **kwargs):
kwargs.update(self.get_class_kwargs())
store = self.get_class()(**kwargs)
# Apply possible fixups
self.fixup(store)
return store
def parse_store(self, storefile):
"""Parse the store."""
store = self.get_store_instance()
# Read the content
if isinstance(storefile, str):
with open(storefile, "rb") as handle:
content = handle.read()
else:
content = storefile.read()
# Parse the content
store.parse(content)
return store
def add_unit(self, ttkit_unit) -> None:
"""Add new unit to underlying store."""
if isinstance(self.store, LISAfile):
# LISA based stores need to know this
self.store.addunit(ttkit_unit, new=True)
else:
self.store.addunit(ttkit_unit)
def save_content(self, handle) -> None:
"""Store content to file."""
self.store.serialize(handle)
def save(self) -> None:
"""Save underlying store to disk."""
self.save_atomic(self.storefile, self.save_content)
@classmethod
def mimetype(cls):
"""Return most common media type for format."""
return cls.get_class().Mimetypes[0]
@classmethod
def extension(cls):
"""Return most common file extension for format."""
return cls.get_class().Extensions[0]
def is_valid(self) -> bool:
"""
Check whether store seems to be valid.
In some cases Translate Toolkit happily "parses" the file, even though it really
did not do so (e.g. gettext parser on a random textfile).
"""
if not super().is_valid():
return False
return self.store is not None
def construct_unit(self, source: str):
if self.use_settarget and self.source_language:
# Setting source on LISAunit will make it use default language
unit = self.store.UnitClass(None)
unit.setsource(source, self.source_language)
elif hasattr(self.store, "wrapper"):
# gettext PO
unit = self.store.UnitClass(source, wrapper=self.store.wrapper)
else:
unit = self.store.UnitClass(source)
# Needed by some formats (Android) to set target
unit._store = self.store
return unit
def create_unit_key(
self, key: str, source: str | list[str] | multistring
) -> str | multistring:
return key
def create_unit(
self,
key: str,
source: str | list[str],
target: str | list[str] | None = None,
):
# Make sure target is a string
if target is None:
target = ""
# Process source
if isinstance(source, list):
context = source[0]
# Single string passed plain or multistring
source = context if len(source) == 1 else multistring(source)
else:
# This is string
context = source
# Process target
if isinstance(target, list):
target = target[0] if len(target) == 1 else multistring(target)
# Build the unit
unit = self.construct_unit(context)
# Monolingual translation
if self.is_template or self.template_store:
unit.setid(key)
target = source
source = self.create_unit_key(key, source)
# Bilingual translation
elif isinstance(unit, tbxunit | xliffunit) and key:
unit.setid(key)
elif self.set_context_bilingual and key:
unit.setcontext(key)
elif isinstance(unit, BaseJsonUnit):
unit.setid(context)
if self.use_settarget and self.source_language:
unit.setsource(source, self.source_language)
else:
unit.source = source
if self.use_settarget and self.language_code:
unit.settarget(target, self.language_code)
else:
unit.target = target
return unit
def untranslate_store(self, language) -> None:
"""Remove translations from Translate Toolkit store."""
self.store.settargetlanguage(self.get_language_code(language.code))
for unit in self.content_units:
if unit.is_translated():
unit.untranslate(language)
@classmethod
def get_new_file_content(cls):
result = cls.new_translation
if isinstance(result, str):
result = result.encode()
return result
@classmethod
def create_new_file(
cls,
filename: str,
language: str,
base: str,
callback: Callable | None = None,
) -> None:
"""Handle creation of new translation file."""
if base:
# Parse file
store = cls(base)
if callback:
callback(store)
store.untranslate_store(language)
store.store.savefile(filename)
elif cls.new_translation is not None:
with open(filename, "wb") as output:
output.write(cls.get_new_file_content())
else:
raise ValueError("Not supported")
@classmethod
def is_valid_base_for_new(
cls,
base: str,
monolingual: bool,
errors: list | None = None,
fast: bool = False,
) -> bool:
"""Check whether base is valid."""
if not base:
if cls.create_empty_bilingual:
return True
return monolingual and cls.new_translation is not None
try:
if not fast:
cls(base)
except Exception as exception:
if errors is not None:
errors.append(exception)
report_error(cause="File-parsing error")
return False
return os.path.exists(base)
@property
def all_store_units(self):
"""Wrapper for all store unit filtering out obsolete."""
return (
unit
for unit in self.store.units
if not unit.isobsolete() and not unit.isheader()
)
def delete_unit(self, ttkit_unit) -> str | None:
self.store.removeunit(ttkit_unit)
return None
class PropertiesUnit(KeyValueUnit):
"""Wrapper for properties-based units."""
@cached_property
def locations(self) -> str:
"""Return a comma-separated list of locations."""
return ""
@cached_property
def source(self):
"""Return source string from a Translate Toolkit unit."""
if self.template is not None:
return get_string(self.template.source)
# Need to decode property encoded string
return get_string(quote.propertiesdecode(self.unit.name))
@cached_property
def target(self):
"""Return target string from a Translate Toolkit unit."""
if self.unit is None:
return ""
return get_string(self.unit.target or self.unit.source)
class PoUnit(TTKitUnit):
"""Wrapper for gettext PO unit."""
def set_state(self, state) -> None:
"""Set fuzzy /approved flag on translated unit."""
super().set_state(state)
if state != STATE_FUZZY:
self.unit.prev_msgid = []
self.unit.prev_msgid_plural = []
self.unit.prev_msgctxt = []
@cached_property
def flags(self):
"""Return flags or typecomments from units."""
try:
flags = Flags(*self.mainunit.typecomments)
except ParseException as error:
raise ValueError(
f"Could not parse flags: {self.mainunit.typecomments!r}: {error}"
) from error
flags.remove({"fuzzy"})
return flags.format()
@cached_property
def previous_source(self):
"""Return previous message source if there was any."""
if not self.is_fuzzy():
return ""
return get_string(self.unit.prev_source)
@cached_property
def locations(self):
"""
Return comma separated list of locations.
Here we clean up Sphinx-generated "docstring of ..." part.
"""
locations = " ".join(self.mainunit.getlocations())
locations = PO_DOCSTRING_LOCATION.sub("", locations)
return ", ".join(locations.split())
class PoMonoUnit(PoUnit):
@cached_property
def context(self):
"""
Return context of message.
In some cases we have to use ID here to make all the backends consistent.
"""
# Monolingual PO files
if self.template is not None:
context = self.template.getcontext()
source = self.template.source
if source and context:
return f"{context}.{source}"
return source or context
return super().context
@cached_property
def notes(self):
result = []
notes = super().notes
if notes:
result.append(notes)
# Use unit context as note only in case source is present, otherwise
# it is used as a context (see above)
if self.template is not None and self.template.source:
context = self.template.getcontext()
if context:
result.append(context)
return "\n".join(result)
def set_target(self, target: str | list[str]) -> None:
"""Set translation unit target."""
# Add blank msgid_plural to store plural
if isinstance(target, list | multistring) and not self.unit.hasplural():
self.unit.msgid_plural = ['""']
super().set_target(target)
class XliffUnit(TTKitUnit):
"""
Wrapper unit for XLIFF.
XLIFF is special in Translate Toolkit — it uses locations for what
is context in other formats.
"""
@staticmethod
def get_unit_node(unit, element: str = "target"):
if unit is not None:
return unit.xmlelement.find(unit.namespaced(element))
return None
def get_xliff_units(self):
# Iterate over poxliff sub-units, or main unit
return getattr(self.unit, "units", [self.unit])
def get_xliff_nodes(self):
return (self.get_unit_node(unit) for unit in self.get_xliff_units())
def get_xliff_states(self) -> set[str]:
result = set()
for node in self.get_xliff_nodes():
if node is None:
continue
state = node.get("state", None)
if state is not None:
result.add(state)
return result
@cached_property
def context(self):
"""
Return context of message.
Use resname if available as it usually is more interesting for the translator
than ID.
"""
resname = self.mainunit.xmlelement.get("resname")
if resname:
return resname
return self.mainunit.getid().replace(ID_SEPARATOR, "///")
def is_translated(self):
"""
Check whether unit is translated.
We replace Translate Toolkit logic here as the isfuzzy is pretty much wrong
there, see is_fuzzy docs.
"""
return self.has_translation()
def is_fuzzy(self, fallback: bool = False) -> bool:
"""
Check whether unit needs edit.
The isfuzzy on XLIFF is really messing up the "approved" flag with "fuzzy"
flag, leading to various problems.
That's why we handle it on our own.
"""
return self.has_translation() and bool(
XLIFF_FUZZY_STATES.intersection(self.get_xliff_states())
)
def set_state(self, state) -> None:
"""Set fuzzy /approved flag on translated unit."""
self.unit.markapproved(state == STATE_APPROVED)
target_state = None
if state == STATE_FUZZY:
# Always set state for fuzzy
target_state = "needs-translation"
elif state == STATE_TRANSLATED:
# Always set state for translated
target_state = "translated"
elif state == STATE_APPROVED:
target_state = "final"
elif self.get_xliff_states():
# Only update state if it exists
target_state = "new"
if target_state:
for xliff_node in self.get_xliff_nodes():
xliff_node.set("state", target_state)
def is_approved(self, fallback=False):
"""Check whether unit is approved."""
if self.unit is None:
return fallback
if hasattr(self.unit, "isapproved"):
return self.unit.isapproved()
return fallback
def has_content(self):
"""
Check whether unit has content.
For some reason, blank string does not mean non-translatable unit in XLIFF, so
lets skip those as well.
"""
return (
not self.mainunit.isheader()
and bool(self.source)
and not self.mainunit.isobsolete()
)
def untranslate(self, language) -> None:
super().untranslate(language)
# Delete empty <target/> tag
for xmlnode in self.get_xliff_nodes():
if xmlnode is not None:
xmlnode.getparent().remove(xmlnode)
def set_target(self, target: str | list[str]) -> None:
"""Set translation unit target."""
if self.get_unit_node(self.unit, "source") is None:
# Make sure source element is present, otherwise it breaks
# translate-toolkit expectations.
self.unit.set_source_dom(
self.unit.createlanguageNode(self.parent.source_language, "", "source")
)
self._invalidate_target()
if isinstance(target, list):
target = multistring(target)
if self.template is not None:
if self.parent.is_template:
# Use source for monolingual files if editing template
self.unit.source = target
elif self.unit.source:
# Update source to match current source
self.unit.source = self.template.source
# Always set target, even in monolingual template
self.unit.target = target
@cached_property
def source(self):
"""Return source string from a Translate Toolkit unit."""
if self.template is not None:
# Use target if set, otherwise fall back to source
if self.template.target:
return get_string(self.template.target)
return get_string(self.template.source)
return get_string(self.unit.source)
@cached_property
def target(self):
"""Return target string from a Translate Toolkit unit."""
if self.unit is None:
return ""
# Use source for monolingual base if target is not set
if self.unit.target is None:
if self.parent.is_template:
return get_string(self.unit.source)
return ""
return get_string(self.unit.target)
class RichXliffUnit(XliffUnit):
"""Wrapper unit for XLIFF with XML elements."""
@cached_property
def source(self):
"""Return source string from a Translate Toolkit unit."""
if self.template is not None:
# Use target if set, otherwise fall back to source
if self.template.target:
return rich_to_xliff_string(self.template.rich_target)
return rich_to_xliff_string(self.template.rich_source)
return rich_to_xliff_string(self.unit.rich_source)
@cached_property
def target(self):
"""Return target string from a Translate Toolkit unit."""
if self.unit is None:
return ""
# Use source for monolingual base if target is not set
if self.unit.target is None:
if self.parent.is_template:
return rich_to_xliff_string(self.unit.rich_source)
return ""
return rich_to_xliff_string(self.unit.rich_target)
@cached_property
def flags(self):
flags = Flags(super().flags)
flags.merge("xml-text")
return flags.format()
def set_target(self, target: str | list[str]) -> None:
"""Set translation unit target."""
self._invalidate_target()
# Delete the empty target element
if not target:
for xmlnode in self.get_xliff_nodes():
if xmlnode is not None:
xmlnode.getparent().remove(xmlnode)
return
try:
converted = xliff_string_to_rich(target)
except (XMLSyntaxError, TypeError, KeyError):
# KeyError happens on missing attribute
converted = [target]
if self.template is not None:
if self.parent.is_template:
# Use source for monolingual files if editing template
self.unit.rich_source = converted
elif self.unit.source:
# Update source to match current source
self.unit.rich_source = self.template.rich_source
# Always set target, even in monolingual template
self.unit.rich_target = converted
class FlatXMLUnit(TTKitUnit):
@cached_property
def context(self):
if self.template is not None:
return self.template.source
return self.mainunit.source
@cached_property
def source(self):
return get_string(self.mainunit.target)
def has_content(self):
"""
Check whether unit has content.
The attribute-less units will have context None.
"""
if self.context is None:
return False
return super().has_content()
class MonolingualIDUnit(TTKitUnit):
@cached_property
def context(self):
if self.template is not None:
return self.template.getid()
return self.mainunit.getcontext()
class TSUnit(MonolingualIDUnit):
@cached_property
def source(self):
if self.template is None and self.mainunit.hasplural():
# Need to apply special magic for plurals here
# as there is no singular/plural in the source string
source = self.unit.source
return get_string([source.replace("(s)", ""), source.replace("(s)", "s")])
return super().source
@cached_property
def locations(self):
"""Return a comma-separated list of locations."""
result = super().locations
# Do not try to handle relative locations in Qt TS, see
# http://doc.qt.io/qt-5/linguist-ts-file-format.html
if LOCATIONS_RE.match(result):
return ""
return result
@cached_property
def target(self):
"""Return target string from a Translate Toolkit unit."""
if self.unit is None:
return ""
if not self.unit.isreview() and not self.unit.istranslated():
# For Qt ts, empty translated string means source should be used
return self.source
return super().target
def is_translated(self):
"""Check whether unit is translated."""
if self.unit is None:
return False
# For Qt ts, empty translated string means source should be used
return not self.unit.isreview() or self.unit.istranslated()
def set_state(self, state) -> None:
"""Set fuzzy /approved flag on translated unit."""
super().set_state(state)
if state == STATE_EMPTY:
# We need to mark all units as fuzzy to get
# type="unfinished" on empty strings, which are otherwise
# treated as translated same as source
self.unit.markfuzzy(True)
class MonolingualSimpleUnit(MonolingualIDUnit):
@cached_property
def locations(self) -> str:
return ""
@cached_property
def source(self):
if self.template is None:
return self.mainunit.getid().lstrip(".")
return get_string(self.template.target)
def has_content(self) -> bool:
return not self.mainunit.isheader()
def is_readonly(self) -> bool:
return False
class JSONUnit(MonolingualSimpleUnit):
@cached_property
def context(self):
context = super().context
if context.startswith("."):
return context[1:]
return context
class PlaceholdersJSONUnit(JSONUnit):
@cached_property
def flags(self):
placeholders = self.mainunit.placeholders
if not placeholders:
return ""
flags = ""
if isinstance(placeholders, list):
# golang placeholders
placeholder_ids = [f"{{{p['id']}}}" for p in placeholders]
else:
# WebExtension placeholders
placeholder_ids = [f"${key.upper()}$" for key in placeholders]
flags = ",case-insensitive"
return "placeholders:{}{}".format(
":".join(Flags.format_value(key) for key in placeholder_ids), flags
)
class CSVUnit(MonolingualSimpleUnit):
@staticmethod
def unescape_csv(string):
r"""
Remove Excel-specific escaping from CSV.
See weblate.formats.exporters.CSVExporter.string_filter
Note: | is replaced by \ in the condition as it is escaped
"""
if (
len(string) > 2
and string[0] == "'"
and string[-1] == "'"
and string[1] in {"=", "+", "-", "@", "\\", "%"}
):
return get_string(string[1:-1].replace("\\|", "|"))
return get_string(string)
@cached_property
def context(self):
def get_context(unit):
if unit.id:
return unit.id
if unit.context:
return unit.context
return unit.getid()
# Needed to avoid Translate Toolkit construct ID
# as context\04source
if self.template is not None:
return get_context(self.template)
if self.parent.is_template:
return get_context(self.unit)
return self.unescape_csv(self.mainunit.getcontext())
@cached_property
def locations(self):
return self.mainunit.location
@cached_property