-
-
Notifications
You must be signed in to change notification settings - Fork 31
/
polib.py
1821 lines (1579 loc) · 60.5 KB
/
polib.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
# -* coding: utf-8 -*-
#
# License: MIT (see LICENSE file provided)
# vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4:
"""
**polib** allows you to manipulate, create, modify gettext files (pot, po and
mo files). You can load existing files, iterate through it's entries, add,
modify entries, comments or metadata, etc. or create new po files from scratch.
**polib** provides a simple and pythonic API via the :func:`~polib.pofile` and
:func:`~polib.mofile` convenience functions.
"""
import array
import codecs
import os
import re
import struct
import sys
import textwrap
import io
__author__ = 'David Jean Louis <[email protected]>'
__version__ = '1.2.0'
__all__ = ['pofile', 'POFile', 'POEntry', 'mofile', 'MOFile', 'MOEntry',
'default_encoding', 'escape', 'unescape', 'detect_encoding', ]
# the default encoding to use when encoding cannot be detected
default_encoding = 'utf-8'
# python 2/3 compatibility helpers {{{
if sys.version_info < (3,):
PY3 = False
text_type = unicode
def b(s):
return s
def u(s):
return unicode(s, "unicode_escape")
else:
PY3 = True
text_type = str
def b(s):
return s.encode("latin-1")
def u(s):
return s
# }}}
# _pofile_or_mofile {{{
def _pofile_or_mofile(f, type, **kwargs):
"""
Internal function used by :func:`polib.pofile` and :func:`polib.mofile` to
honor the DRY concept.
"""
# get the file encoding
enc = kwargs.get('encoding')
if enc is None:
enc = detect_encoding(f, type == 'mofile')
# parse the file
kls = type == 'pofile' and _POFileParser or _MOFileParser
parser = kls(
f,
encoding=enc,
check_for_duplicates=kwargs.get('check_for_duplicates', False),
klass=kwargs.get('klass')
)
instance = parser.parse()
instance.wrapwidth = kwargs.get('wrapwidth', 78)
return instance
# }}}
# _is_file {{{
def _is_file(filename_or_contents):
"""
Safely returns the value of os.path.exists(filename_or_contents).
Arguments:
``filename_or_contents``
either a filename, or a string holding the contents of some file.
In the latter case, this function will always return False.
"""
try:
return os.path.isfile(filename_or_contents)
except (TypeError, ValueError, UnicodeEncodeError):
return False
# }}}
# function pofile() {{{
def pofile(pofile, **kwargs):
"""
Convenience function that parses the po or pot file ``pofile`` and returns
a :class:`~polib.POFile` instance.
Arguments:
``pofile``
string, full or relative path to the po/pot file or its content (data).
``wrapwidth``
integer, the wrap width, only useful when the ``-w`` option was passed
to xgettext (optional, default: ``78``).
``encoding``
string, the encoding to use (e.g. "utf-8") (default: ``None``, the
encoding will be auto-detected).
``check_for_duplicates``
whether to check for duplicate entries when adding entries to the
file (optional, default: ``False``).
``klass``
class which is used to instantiate the return value (optional,
default: ``None``, the return value with be a :class:`~polib.POFile`
instance).
"""
return _pofile_or_mofile(pofile, 'pofile', **kwargs)
# }}}
# function mofile() {{{
def mofile(mofile, **kwargs):
"""
Convenience function that parses the mo file ``mofile`` and returns a
:class:`~polib.MOFile` instance.
Arguments:
``mofile``
string, full or relative path to the mo file or its content (string
or bytes).
``wrapwidth``
integer, the wrap width, only useful when the ``-w`` option was passed
to xgettext to generate the po file that was used to format the mo file
(optional, default: ``78``).
``encoding``
string, the encoding to use (e.g. "utf-8") (default: ``None``, the
encoding will be auto-detected).
``check_for_duplicates``
whether to check for duplicate entries when adding entries to the
file (optional, default: ``False``).
``klass``
class which is used to instantiate the return value (optional,
default: ``None``, the return value with be a :class:`~polib.POFile`
instance).
"""
return _pofile_or_mofile(mofile, 'mofile', **kwargs)
# }}}
# function detect_encoding() {{{
def detect_encoding(file, binary_mode=False):
"""
Try to detect the encoding used by the ``file``. The ``file`` argument can
be a PO or MO file path or a string containing the contents of the file.
If the encoding cannot be detected, the function will return the value of
``default_encoding``.
Arguments:
``file``
string, full or relative path to the po/mo file or its content.
``binary_mode``
boolean, set this to True if ``file`` is a mo file.
"""
PATTERN = r'"?Content-Type:.+? charset=([\w_\-:\.]+)'
rxt = re.compile(u(PATTERN))
rxb = re.compile(b(PATTERN))
def charset_exists(charset):
"""Check whether ``charset`` is valid or not."""
try:
codecs.lookup(charset)
except LookupError:
return False
return True
if not _is_file(file):
try:
match = rxt.search(file)
except TypeError:
match = rxb.search(file)
if match:
enc = match.group(1).strip()
if not isinstance(enc, text_type):
enc = enc.decode('utf-8')
if charset_exists(enc):
return enc
else:
# For PY3, always treat as binary
if binary_mode or PY3:
mode = 'rb'
rx = rxb
else:
mode = 'r'
rx = rxt
with open(file, mode) as f:
for line in f.readlines():
match = rx.search(line)
if match:
f.close()
enc = match.group(1).strip()
if not isinstance(enc, text_type):
enc = enc.decode('utf-8')
if charset_exists(enc):
return enc
return default_encoding
# }}}
# function escape() {{{
def escape(st):
"""
Escapes the characters ``\\\\``, ``\\t``, ``\\n``, ``\\r``, ``\\v``,
``\\b``, ``\\f`` and ``"`` in the given string ``st`` and returns it.
"""
return st.replace('\\', r'\\')\
.replace('\t', r'\t')\
.replace('\r', r'\r')\
.replace('\n', r'\n')\
.replace('\v', r'\v')\
.replace('\b', r'\b')\
.replace('\f', r'\f')\
.replace('\"', r'\"')
# }}}
# function unescape() {{{
def unescape(st):
"""
Unescapes the characters ``\\\\``, ``\\t``, ``\\n``, ``\\r``, ``\\v``,
``\\b``, ``\\f`` and ``"`` in the given string ``st`` and returns it.
"""
def unescape_repl(m):
m = m.group(1)
if m == 'n':
return '\n'
if m == 't':
return '\t'
if m == 'r':
return '\r'
if m == 'v':
return '\v'
if m == 'b':
return '\b'
if m == 'f':
return '\f'
if m == '\\':
return '\\'
return m # handles escaped double quote
return re.sub(r'\\(\\|n|t|r|v|b|f|")', unescape_repl, st)
# }}}
# function natural_sort() {{{
def natural_sort(lst):
"""
Sort naturally the given list.
Credits: http://stackoverflow.com/a/4836734
"""
def convert(text):
return int(text) if text.isdigit() else text.lower()
def alphanum_key(key):
return [convert(c) for c in re.split('([0-9]+)', key)]
return sorted(lst, key=alphanum_key)
# }}}
# class _BaseFile {{{
class _BaseFile(list):
"""
Common base class for the :class:`~polib.POFile` and :class:`~polib.MOFile`
classes. This class should **not** be instantiated directly.
"""
def __init__(self, *args, **kwargs):
"""
Constructor, accepts the following keyword arguments:
``pofile``
string, the path to the po or mo file, or its content as a string.
``wrapwidth``
integer, the wrap width, only useful when the ``-w`` option was
passed to xgettext (optional, default: ``78``).
``encoding``
string, the encoding to use, defaults to ``default_encoding``
global variable (optional).
``check_for_duplicates``
whether to check for duplicate entries when adding entries to the
file, (optional, default: ``False``).
"""
list.__init__(self)
# the opened file handle
pofile = kwargs.get('pofile', None)
if pofile and _is_file(pofile):
self.fpath = pofile
else:
self.fpath = kwargs.get('fpath')
# the width at which lines should be wrapped
self.wrapwidth = kwargs.get('wrapwidth', 78)
# the file encoding
self.encoding = kwargs.get('encoding', default_encoding)
# whether to check for duplicate entries or not
self.check_for_duplicates = kwargs.get('check_for_duplicates', False)
# header
self.header = ''
# both po and mo files have metadata
self.metadata = {}
self.metadata_is_fuzzy = 0
def __unicode__(self):
"""
Returns the unicode representation of the file.
"""
ret = []
entries = [self.metadata_as_entry()] + \
[e for e in self if not e.obsolete]
for entry in entries:
ret.append(entry.__unicode__(self.wrapwidth))
for entry in self.obsolete_entries():
ret.append(entry.__unicode__(self.wrapwidth))
ret = u('\n').join(ret)
return ret
if PY3:
def __str__(self):
return self.__unicode__()
else:
def __str__(self):
"""
Returns the string representation of the file.
"""
return unicode(self).encode(self.encoding)
def __contains__(self, entry):
"""
Overridden ``list`` method to implement the membership test (in and
not in).
The method considers that an entry is in the file if it finds an entry
that has the same msgid (the test is **case sensitive**) and the same
msgctxt (or none for both entries).
Argument:
``entry``
an instance of :class:`~polib._BaseEntry`.
"""
return self.find(entry.msgid, by='msgid', msgctxt=entry.msgctxt) \
is not None
def __eq__(self, other):
return str(self) == str(other)
def append(self, entry):
"""
Overridden method to check for duplicates entries, if a user tries to
add an entry that is already in the file, the method will raise a
``ValueError`` exception.
Argument:
``entry``
an instance of :class:`~polib._BaseEntry`.
"""
# check_for_duplicates may not be defined (yet) when unpickling.
# But if pickling, we never want to check for duplicates anyway.
if getattr(self, 'check_for_duplicates', False) and entry in self:
raise ValueError('Entry "%s" already exists' % entry.msgid)
super(_BaseFile, self).append(entry)
def insert(self, index, entry):
"""
Overridden method to check for duplicates entries, if a user tries to
add an entry that is already in the file, the method will raise a
``ValueError`` exception.
Arguments:
``index``
index at which the entry should be inserted.
``entry``
an instance of :class:`~polib._BaseEntry`.
"""
if self.check_for_duplicates and entry in self:
raise ValueError('Entry "%s" already exists' % entry.msgid)
super(_BaseFile, self).insert(index, entry)
def metadata_as_entry(self):
"""
Returns the file metadata as a :class:`~polib.POFile` instance.
"""
e = POEntry(msgid='')
mdata = self.ordered_metadata()
if mdata:
strs = []
for name, value in mdata:
# Strip whitespace off each line in a multi-line entry
strs.append('%s: %s' % (name, value))
e.msgstr = '\n'.join(strs) + '\n'
if self.metadata_is_fuzzy:
e.flags.append('fuzzy')
return e
def save(self, fpath=None, repr_method='__unicode__', newline=None):
"""
Saves the po file to ``fpath``.
If it is an existing file and no ``fpath`` is provided, then the
existing file is rewritten with the modified data.
Keyword arguments:
``fpath``
string, full or relative path to the file.
``repr_method``
string, the method to use for output.
``newline``
string, controls how universal newlines works
"""
if self.fpath is None and fpath is None:
raise IOError('You must provide a file path to save() method')
contents = getattr(self, repr_method)()
if fpath is None:
fpath = self.fpath
if repr_method == 'to_binary':
with open(fpath, 'wb') as fhandle:
fhandle.write(contents)
else:
with io.open(
fpath,
'w',
encoding=self.encoding,
newline=newline
) as fhandle:
if not isinstance(contents, text_type):
contents = contents.decode(self.encoding)
fhandle.write(contents)
# set the file path if not set
if self.fpath is None and fpath:
self.fpath = fpath
def find(self, st, by='msgid', include_obsolete_entries=False,
msgctxt=False):
"""
Find the entry which msgid (or property identified by the ``by``
argument) matches the string ``st``.
Keyword arguments:
``st``
string, the string to search for.
``by``
string, the property to use for comparison (default: ``msgid``).
``include_obsolete_entries``
boolean, whether to also search in entries that are obsolete.
``msgctxt``
string, allows specifying a specific message context for the
search.
"""
if include_obsolete_entries:
entries = self[:]
else:
entries = [e for e in self if not e.obsolete]
matches = []
for e in entries:
if getattr(e, by) == st:
if msgctxt is not False and e.msgctxt != msgctxt:
continue
matches.append(e)
if len(matches) == 1:
return matches[0]
elif len(matches) > 1:
if not msgctxt:
# find the entry with no msgctx
e = None
for m in matches:
if not m.msgctxt:
e = m
if e:
return e
# fallback to the first entry found
return matches[0]
return None
def ordered_metadata(self):
"""
Convenience method that returns an ordered version of the metadata
dictionary. The return value is list of tuples (metadata name,
metadata_value).
"""
# copy the dict first
metadata = self.metadata.copy()
data_order = [
'Project-Id-Version',
'Report-Msgid-Bugs-To',
'POT-Creation-Date',
'PO-Revision-Date',
'Last-Translator',
'Language-Team',
'Language',
'MIME-Version',
'Content-Type',
'Content-Transfer-Encoding',
'Plural-Forms'
]
ordered_data = []
for data in data_order:
try:
value = metadata.pop(data)
ordered_data.append((data, value))
except KeyError:
pass
# the rest of the metadata will be alphabetically ordered since there
# are no specs for this AFAIK
for data in natural_sort(metadata.keys()):
value = metadata[data]
ordered_data.append((data, value))
return ordered_data
def to_binary(self):
"""
Return the binary representation of the file.
"""
offsets = []
entries = self.translated_entries()
# the keys are sorted in the .mo file
def cmp(_self, other):
# msgfmt compares entries with msgctxt if it exists
self_msgid = _self.msgctxt and _self.msgctxt or _self.msgid
other_msgid = other.msgctxt and other.msgctxt or other.msgid
if self_msgid > other_msgid:
return 1
elif self_msgid < other_msgid:
return -1
else:
return 0
# add metadata entry
entries.sort(key=lambda o: o.msgid_with_context.encode('utf-8'))
mentry = self.metadata_as_entry()
entries = [mentry] + entries
entries_len = len(entries)
ids, strs = b(''), b('')
for e in entries:
# For each string, we need size and file offset. Each string is
# NUL terminated; the NUL does not count into the size.
msgid = b('')
if e.msgctxt:
# Contexts are stored by storing the concatenation of the
# context, a <EOT> byte, and the original string
msgid = self._encode(e.msgctxt + '\4')
if e.msgid_plural:
msgstr = []
for index in sorted(e.msgstr_plural.keys()):
msgstr.append(e.msgstr_plural[index])
msgid += self._encode(e.msgid + '\0' + e.msgid_plural)
msgstr = self._encode('\0'.join(msgstr))
else:
msgid += self._encode(e.msgid)
msgstr = self._encode(e.msgstr)
offsets.append((len(ids), len(msgid), len(strs), len(msgstr)))
ids += msgid + b('\0')
strs += msgstr + b('\0')
# The header is 7 32-bit unsigned integers.
keystart = 7 * 4 + 16 * entries_len
# and the values start after the keys
valuestart = keystart + len(ids)
koffsets = []
voffsets = []
# The string table first has the list of keys, then the list of values.
# Each entry has first the size of the string, then the file offset.
for o1, l1, o2, l2 in offsets:
koffsets += [l1, o1 + keystart]
voffsets += [l2, o2 + valuestart]
offsets = koffsets + voffsets
output = struct.pack(
"Iiiiiii",
# Magic number
MOFile.MAGIC,
# Version
0,
# number of entries
entries_len,
# start of key index
7 * 4,
# start of value index
7 * 4 + entries_len * 8,
# size and offset of hash table, we don't use hash tables
0, keystart
)
if PY3 and sys.version_info.minor > 1: # python 3.2 or superior
output += array.array("i", offsets).tobytes()
else:
output += array.array("i", offsets).tostring()
output += ids
output += strs
return output
def _encode(self, mixed):
"""
Encodes the given ``mixed`` argument with the file encoding if and
only if it's an unicode string and returns the encoded string.
"""
if isinstance(mixed, text_type):
mixed = mixed.encode(self.encoding)
return mixed
# }}}
# class POFile {{{
class POFile(_BaseFile):
"""
Po (or Pot) file reader/writer.
This class inherits the :class:`~polib._BaseFile` class and, by extension,
the python ``list`` type.
"""
def __unicode__(self):
"""
Returns the unicode representation of the po file.
"""
ret, headers = '', self.header.split('\n')
for header in headers:
if not len(header):
ret += "#\n"
elif header[:1] in [',', ':']:
ret += '#%s\n' % header
else:
ret += '# %s\n' % header
if not isinstance(ret, text_type):
ret = ret.decode(self.encoding)
return ret + _BaseFile.__unicode__(self)
def save_as_mofile(self, fpath):
"""
Saves the binary representation of the file to given ``fpath``.
Keyword argument:
``fpath``
string, full or relative path to the mo file.
"""
_BaseFile.save(self, fpath, 'to_binary')
def percent_translated(self):
"""
Convenience method that returns the percentage of translated
messages.
"""
total = len([e for e in self if not e.obsolete])
if total == 0:
return 100
translated = len(self.translated_entries())
return int(translated * 100 / float(total))
def translated_entries(self):
"""
Convenience method that returns the list of translated entries.
"""
return [e for e in self if e.translated()]
def untranslated_entries(self):
"""
Convenience method that returns the list of untranslated entries.
"""
return [e for e in self if not e.translated() and not e.obsolete
and not e.fuzzy]
def fuzzy_entries(self):
"""
Convenience method that returns the list of fuzzy entries.
"""
return [e for e in self if e.fuzzy and not e.obsolete]
def obsolete_entries(self):
"""
Convenience method that returns the list of obsolete entries.
"""
return [e for e in self if e.obsolete]
def merge(self, refpot):
"""
Convenience method that merges the current pofile with the pot file
provided. It behaves exactly as the gettext msgmerge utility:
* comments of this file will be preserved, but extracted comments and
occurrences will be discarded;
* any translations or comments in the file will be discarded, however,
dot comments and file positions will be preserved;
* the fuzzy flags are preserved.
Keyword argument:
``refpot``
object POFile, the reference catalog.
"""
# Store entries in dict/set for faster access
self_entries = dict(
(entry.msgid_with_context, entry) for entry in self
)
refpot_msgids = set(entry.msgid_with_context for entry in refpot)
# Merge entries that are in the refpot
for entry in refpot:
e = self_entries.get(entry.msgid_with_context)
if e is None:
e = POEntry()
self.append(e)
e.merge(entry)
# ok, now we must "obsolete" entries that are not in the refpot anymore
for entry in self:
if entry.msgid_with_context not in refpot_msgids:
entry.obsolete = True
# }}}
# class MOFile {{{
class MOFile(_BaseFile):
"""
Mo file reader/writer.
This class inherits the :class:`~polib._BaseFile` class and, by
extension, the python ``list`` type.
"""
MAGIC = 0x950412de
MAGIC_SWAPPED = 0xde120495
def __init__(self, *args, **kwargs):
"""
Constructor, accepts all keywords arguments accepted by
:class:`~polib._BaseFile` class.
"""
_BaseFile.__init__(self, *args, **kwargs)
self.magic_number = None
self.version = 0
def save_as_pofile(self, fpath):
"""
Saves the mofile as a pofile to ``fpath``.
Keyword argument:
``fpath``
string, full or relative path to the file.
"""
_BaseFile.save(self, fpath)
def save(self, fpath=None):
"""
Saves the mofile to ``fpath``.
Keyword argument:
``fpath``
string, full or relative path to the file.
"""
_BaseFile.save(self, fpath, 'to_binary')
def percent_translated(self):
"""
Convenience method to keep the same interface with POFile instances.
"""
return 100
def translated_entries(self):
"""
Convenience method to keep the same interface with POFile instances.
"""
return self
def untranslated_entries(self):
"""
Convenience method to keep the same interface with POFile instances.
"""
return []
def fuzzy_entries(self):
"""
Convenience method to keep the same interface with POFile instances.
"""
return []
def obsolete_entries(self):
"""
Convenience method to keep the same interface with POFile instances.
"""
return []
# }}}
# class _BaseEntry {{{
class _BaseEntry(object):
"""
Base class for :class:`~polib.POEntry` and :class:`~polib.MOEntry` classes.
This class should **not** be instantiated directly.
"""
def __init__(self, *args, **kwargs):
"""
Constructor, accepts the following keyword arguments:
``msgid``
string, the entry msgid.
``msgstr``
string, the entry msgstr.
``msgid_plural``
string, the entry msgid_plural.
``msgstr_plural``
dict, the entry msgstr_plural lines.
``msgctxt``
string, the entry context (msgctxt).
``obsolete``
bool, whether the entry is "obsolete" or not.
``encoding``
string, the encoding to use, defaults to ``default_encoding``
global variable (optional).
"""
self.msgid = kwargs.get('msgid', '')
self.msgstr = kwargs.get('msgstr', '')
self.msgid_plural = kwargs.get('msgid_plural', '')
self.msgstr_plural = kwargs.get('msgstr_plural', {})
self.msgctxt = kwargs.get('msgctxt', None)
self.obsolete = kwargs.get('obsolete', False)
self.encoding = kwargs.get('encoding', default_encoding)
def __unicode__(self, wrapwidth=78):
"""
Returns the unicode representation of the entry.
"""
if self.obsolete:
delflag = '#~ '
else:
delflag = ''
ret = []
# write the msgctxt if any
if self.msgctxt is not None:
ret += self._str_field("msgctxt", delflag, "", self.msgctxt,
wrapwidth)
# write the msgid
ret += self._str_field("msgid", delflag, "", self.msgid, wrapwidth)
# write the msgid_plural if any
if self.msgid_plural:
ret += self._str_field("msgid_plural", delflag, "",
self.msgid_plural, wrapwidth)
if self.msgstr_plural:
# write the msgstr_plural if any
msgstrs = self.msgstr_plural
keys = list(msgstrs)
keys.sort()
for index in keys:
msgstr = msgstrs[index]
plural_index = '[%s]' % index
ret += self._str_field("msgstr", delflag, plural_index, msgstr,
wrapwidth)
else:
# otherwise write the msgstr
ret += self._str_field("msgstr", delflag, "", self.msgstr,
wrapwidth)
ret.append('')
ret = u('\n').join(ret)
return ret
if PY3:
def __str__(self):
return self.__unicode__()
else:
def __str__(self):
"""
Returns the string representation of the entry.
"""
return unicode(self).encode(self.encoding)
def __eq__(self, other):
return str(self) == str(other)
def _str_field(self, fieldname, delflag, plural_index, field,
wrapwidth=78):
lines = field.splitlines(True)
if len(lines) > 1:
lines = [''] + lines # start with initial empty line
else:
escaped_field = escape(field)
specialchars_count = 0
for c in ['\\', '\n', '\r', '\t', '\v', '\b', '\f', '"']:
specialchars_count += field.count(c)
# comparison must take into account fieldname length + one space
# + 2 quotes (eg. msgid "<string>")
flength = len(fieldname) + 3
if plural_index:
flength += len(plural_index)
real_wrapwidth = wrapwidth - flength + specialchars_count
if wrapwidth > 0 and len(field) > real_wrapwidth:
# Wrap the line but take field name into account
lines = [''] + [unescape(item) for item in textwrap.wrap(
escaped_field,
wrapwidth - 2, # 2 for quotes ""
drop_whitespace=False,
break_long_words=False
)]
else:
lines = [field]
if fieldname.startswith('previous_'):
# quick and dirty trick to get the real field name
fieldname = fieldname[9:]
ret = ['%s%s%s "%s"' % (delflag, fieldname, plural_index,
escape(lines.pop(0)))]
for line in lines:
ret.append('%s"%s"' % (delflag, escape(line)))
return ret
@property
def msgid_with_context(self):
if self.msgctxt:
return '%s%s%s' % (self.msgctxt, "\x04", self.msgid)
return self.msgid
# }}}
# class POEntry {{{
class POEntry(_BaseEntry):
"""
Represents a po file entry.
"""
def __init__(self, *args, **kwargs):
"""
Constructor, accepts the following keyword arguments:
``comment``
string, the entry comment.
``tcomment``
string, the entry translator comment.
``occurrences``
list, the entry occurrences.
``flags``
list, the entry flags.
``previous_msgctxt``
string, the entry previous context.
``previous_msgid``
string, the entry previous msgid.
``previous_msgid_plural``
string, the entry previous msgid_plural.
``linenum``
integer, the line number of the entry
"""
_BaseEntry.__init__(self, *args, **kwargs)
self.comment = kwargs.get('comment', '')
self.tcomment = kwargs.get('tcomment', '')
self.occurrences = kwargs.get('occurrences', [])
self.flags = kwargs.get('flags', [])
self.previous_msgctxt = kwargs.get('previous_msgctxt', None)
self.previous_msgid = kwargs.get('previous_msgid', None)
self.previous_msgid_plural = kwargs.get('previous_msgid_plural', None)