Debian Codegraph @

i18n/polib.py

raw
1 # no-check-code
2 #
3 # License: MIT (see LICENSE file provided)
4 # vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4:
5
6 """
7 **polib** allows you to manipulate, create, modify gettext files (pot, po and
8 mo files). You can load existing files, iterate through it's entries, add,
9 modify entries, comments or metadata, etc. or create new po files from scratch.
10
11 **polib** provides a simple and pythonic API via the :func:`~polib.pofile` and
12 :func:`~polib.mofile` convenience functions.
13 """
14
15 from __future__ import annotations
16
17 __author__ = 'David Jean Louis <[email protected]>'
18 __version__ = '1.0.7'
19 __all__ = [
20 'pofile',
21 'POFile',
22 'POEntry',
23 'mofile',
24 'MOFile',
25 'MOEntry',
26 'default_encoding',
27 'escape',
28 'unescape',
29 'detect_encoding',
30 ]
31
32 import array
33 import codecs
34 import os
35 import re
36 import struct
37 import sys
38 import textwrap
39
40 try:
41 import io
42 except ImportError:
43 # replacement of io.open() for python < 2.6
44 # we use codecs instead
45 class io:
46 @staticmethod
47 def open(fpath, mode='r', encoding=None):
48 return codecs.open(fpath, mode, encoding)
49
50
51 # the default encoding to use when encoding cannot be detected
52 default_encoding = 'utf-8'
53
54 # python 2/3 compatibility helpers {{{
55
56
57 if sys.version_info[:2] < (3, 0):
58 PY3 = False
59 text_type = unicode
60
61 def b(s):
62 return s
63
64 def u(s):
65 return unicode(s, "unicode_escape")
66
67 else:
68 PY3 = True
69 text_type = str
70
71 def b(s):
72 return s.encode("latin-1")
73
74 def u(s):
75 return s
76
77
78 # }}}
79 # _pofile_or_mofile {{{
80
81
82 def _pofile_or_mofile(f, type, **kwargs):
83 """
84 Internal function used by :func:`polib.pofile` and :func:`polib.mofile` to
85 honor the DRY concept.
86 """
87 # get the file encoding
88 enc = kwargs.get('encoding')
89 if enc is None:
90 enc = detect_encoding(f, type == 'mofile')
91
92 # parse the file
93 kls = type == 'pofile' and _POFileParser or _MOFileParser
94 parser = kls(
95 f,
96 encoding=enc,
97 check_for_duplicates=kwargs.get('check_for_duplicates', False),
98 klass=kwargs.get('klass'),
99 )
100 instance = parser.parse()
101 instance.wrapwidth = kwargs.get('wrapwidth', 78)
102 return instance
103
104
105 # }}}
106 # _is_file {{{
107
108
109 def _is_file(filename_or_contents):
110 """
111 Safely returns the value of os.path.exists(filename_or_contents).
112
113 Arguments:
114
115 ``filename_or_contents``
116 either a filename, or a string holding the contents of some file.
117 In the latter case, this function will always return False.
118 """
119 try:
120 return os.path.exists(filename_or_contents)
121 except (ValueError, UnicodeEncodeError):
122 return False
123
124
125 # }}}
126 # function pofile() {{{
127
128
129 def pofile(pofile, **kwargs):
130 """
131 Convenience function that parses the po or pot file ``pofile`` and returns
132 a :class:`~polib.POFile` instance.
133
134 Arguments:
135
136 ``pofile``
137 string, full or relative path to the po/pot file or its content (data).
138
139 ``wrapwidth``
140 integer, the wrap width, only useful when the ``-w`` option was passed
141 to xgettext (optional, default: ``78``).
142
143 ``encoding``
144 string, the encoding to use (e.g. "utf-8") (default: ``None``, the
145 encoding will be auto-detected).
146
147 ``check_for_duplicates``
148 whether to check for duplicate entries when adding entries to the
149 file (optional, default: ``False``).
150
151 ``klass``
152 class which is used to instantiate the return value (optional,
153 default: ``None``, the return value with be a :class:`~polib.POFile`
154 instance).
155 """
156 return _pofile_or_mofile(pofile, 'pofile', **kwargs)
157
158
159 # }}}
160 # function mofile() {{{
161
162
163 def mofile(mofile, **kwargs):
164 """
165 Convenience function that parses the mo file ``mofile`` and returns a
166 :class:`~polib.MOFile` instance.
167
168 Arguments:
169
170 ``mofile``
171 string, full or relative path to the mo file or its content (data).
172
173 ``wrapwidth``
174 integer, the wrap width, only useful when the ``-w`` option was passed
175 to xgettext to generate the po file that was used to format the mo file
176 (optional, default: ``78``).
177
178 ``encoding``
179 string, the encoding to use (e.g. "utf-8") (default: ``None``, the
180 encoding will be auto-detected).
181
182 ``check_for_duplicates``
183 whether to check for duplicate entries when adding entries to the
184 file (optional, default: ``False``).
185
186 ``klass``
187 class which is used to instantiate the return value (optional,
188 default: ``None``, the return value with be a :class:`~polib.POFile`
189 instance).
190 """
191 return _pofile_or_mofile(mofile, 'mofile', **kwargs)
192
193
194 # }}}
195 # function detect_encoding() {{{
196
197
198 def detect_encoding(file, binary_mode=False):
199 """
200 Try to detect the encoding used by the ``file``. The ``file`` argument can
201 be a PO or MO file path or a string containing the contents of the file.
202 If the encoding cannot be detected, the function will return the value of
203 ``default_encoding``.
204
205 Arguments:
206
207 ``file``
208 string, full or relative path to the po/mo file or its content.
209
210 ``binary_mode``
211 boolean, set this to True if ``file`` is a mo file.
212 """
213 PATTERN = r'"?Content-Type:.+? charset=([\w_\-:\.]+)'
214 rxt = re.compile(u(PATTERN))
215 rxb = re.compile(b(PATTERN))
216
217 def charset_exists(charset):
218 """Check whether ``charset`` is valid or not."""
219 try:
220 codecs.lookup(charset)
221 except LookupError:
222 return False
223 return True
224
225 if not _is_file(file):
226 match = rxt.search(file)
227 if match:
228 enc = match.group(1).strip()
229 if charset_exists(enc):
230 return enc
231 else:
232 # For PY3, always treat as binary
233 if binary_mode or PY3:
234 mode = 'rb'
235 rx = rxb
236 else:
237 mode = 'r'
238 rx = rxt
239 f = open(file, mode)
240 for l in f.readlines():
241 match = rx.search(l)
242 if match:
243 f.close()
244 enc = match.group(1).strip()
245 if not isinstance(enc, text_type):
246 enc = enc.decode('utf-8')
247 if charset_exists(enc):
248 return enc
249 f.close()
250 return default_encoding
251
252
253 # }}}
254 # function escape() {{{
255
256
257 def escape(st):
258 """
259 Escapes the characters ``\\\\``, ``\\t``, ``\\n``, ``\\r`` and ``"`` in
260 the given string ``st`` and returns it.
261 """
262 return (
263 st.replace('\\', r'\\')
264 .replace('\t', r'\t')
265 .replace('\r', r'\r')
266 .replace('\n', r'\n')
267 .replace('\"', r'\"')
268 )
269
270
271 # }}}
272 # function unescape() {{{
273
274
275 def unescape(st):
276 """
277 Unescapes the characters ``\\\\``, ``\\t``, ``\\n``, ``\\r`` and ``"`` in
278 the given string ``st`` and returns it.
279 """
280
281 def unescape_repl(m):
282 m = m.group(1)
283 if m == 'n':
284 return '\n'
285 if m == 't':
286 return '\t'
287 if m == 'r':
288 return '\r'
289 if m == '\\':
290 return '\\'
291 return m # handles escaped double quote
292
293 return re.sub(r'\\(\\|n|t|r|")', unescape_repl, st)
294
295
296 # }}}
297 # class _BaseFile {{{
298
299
300 class _BaseFile(list):
301 """
302 Common base class for the :class:`~polib.POFile` and :class:`~polib.MOFile`
303 classes. This class should **not** be instanciated directly.
304 """
305
306 def __init__(self, *args, **kwargs):
307 """
308 Constructor, accepts the following keyword arguments:
309
310 ``pofile``
311 string, the path to the po or mo file, or its content as a string.
312
313 ``wrapwidth``
314 integer, the wrap width, only useful when the ``-w`` option was
315 passed to xgettext (optional, default: ``78``).
316
317 ``encoding``
318 string, the encoding to use, defaults to ``default_encoding``
319 global variable (optional).
320
321 ``check_for_duplicates``
322 whether to check for duplicate entries when adding entries to the
323 file, (optional, default: ``False``).
324 """
325 list.__init__(self)
326 # the opened file handle
327 pofile = kwargs.get('pofile', None)
328 if pofile and _is_file(pofile):
329 self.fpath = pofile
330 else:
331 self.fpath = kwargs.get('fpath')
332 # the width at which lines should be wrapped
333 self.wrapwidth = kwargs.get('wrapwidth', 78)
334 # the file encoding
335 self.encoding = kwargs.get('encoding', default_encoding)
336 # whether to check for duplicate entries or not
337 self.check_for_duplicates = kwargs.get('check_for_duplicates', False)
338 # header
339 self.header = ''
340 # both po and mo files have metadata
341 self.metadata = {}
342 self.metadata_is_fuzzy = 0
343
344 def __unicode__(self):
345 """
346 Returns the unicode representation of the file.
347 """
348 ret = []
349 entries = [self.metadata_as_entry()] + [
350 e for e in self if not e.obsolete
351 ]
352 for entry in entries:
353 ret.append(entry.__unicode__(self.wrapwidth))
354 for entry in self.obsolete_entries():
355 ret.append(entry.__unicode__(self.wrapwidth))
356 ret = u('\n').join(ret)
357
358 assert isinstance(ret, text_type)
359 # if type(ret) != text_type:
360 # return unicode(ret, self.encoding)
361 return ret
362
363 if PY3:
364
365 def __str__(self):
366 return self.__unicode__()
367
368 else:
369
370 def __str__(self):
371 """
372 Returns the string representation of the file.
373 """
374 return unicode(self).encode(self.encoding)
375
376 def __contains__(self, entry):
377 """
378 Overridden ``list`` method to implement the membership test (in and
379 not in).
380 The method considers that an entry is in the file if it finds an entry
381 that has the same msgid (the test is **case sensitive**) and the same
382 msgctxt (or none for both entries).
383
384 Argument:
385
386 ``entry``
387 an instance of :class:`~polib._BaseEntry`.
388 """
389 return (
390 self.find(entry.msgid, by='msgid', msgctxt=entry.msgctxt)
391 is not None
392 )
393
394 def __eq__(self, other):
395 return str(self) == str(other)
396
397 def append(self, entry):
398 """
399 Overridden method to check for duplicates entries, if a user tries to
400 add an entry that is already in the file, the method will raise a
401 ``ValueError`` exception.
402
403 Argument:
404
405 ``entry``
406 an instance of :class:`~polib._BaseEntry`.
407 """
408 if self.check_for_duplicates and entry in self:
409 raise ValueError('Entry "%s" already exists' % entry.msgid)
410 super().append(entry)
411
412 def insert(self, index, entry):
413 """
414 Overridden method to check for duplicates entries, if a user tries to
415 add an entry that is already in the file, the method will raise a
416 ``ValueError`` exception.
417
418 Arguments:
419
420 ``index``
421 index at which the entry should be inserted.
422
423 ``entry``
424 an instance of :class:`~polib._BaseEntry`.
425 """
426 if self.check_for_duplicates and entry in self:
427 raise ValueError('Entry "%s" already exists' % entry.msgid)
428 super().insert(index, entry)
429
430 def metadata_as_entry(self):
431 """
432 Returns the file metadata as a :class:`~polib.POFile` instance.
433 """
434 e = POEntry(msgid='')
435 mdata = self.ordered_metadata()
436 if mdata:
437 strs = []
438 for name, value in mdata:
439 # Strip whitespace off each line in a multi-line entry
440 strs.append('%s: %s' % (name, value))
441 e.msgstr = '\n'.join(strs) + '\n'
442 if self.metadata_is_fuzzy:
443 e.flags.append('fuzzy')
444 return e
445
446 def save(self, fpath=None, repr_method='__unicode__'):
447 """
448 Saves the po file to ``fpath``.
449 If it is an existing file and no ``fpath`` is provided, then the
450 existing file is rewritten with the modified data.
451
452 Keyword arguments:
453
454 ``fpath``
455 string, full or relative path to the file.
456
457 ``repr_method``
458 string, the method to use for output.
459 """
460 if self.fpath is None and fpath is None:
461 raise OSError('You must provide a file path to save() method')
462 contents = getattr(self, repr_method)()
463 if fpath is None:
464 fpath = self.fpath
465 if repr_method == 'to_binary':
466 fhandle = open(fpath, 'wb')
467 else:
468 fhandle = open(fpath, 'w', encoding=self.encoding)
469 if not isinstance(contents, text_type):
470 contents = contents.decode(self.encoding)
471 fhandle.write(contents)
472 fhandle.close()
473 # set the file path if not set
474 if self.fpath is None and fpath:
475 self.fpath = fpath
476
477 def find(
478 self, st, by='msgid', include_obsolete_entries=False, msgctxt=False
479 ):
480 """
481 Find the entry which msgid (or property identified by the ``by``
482 argument) matches the string ``st``.
483
484 Keyword arguments:
485
486 ``st``
487 string, the string to search for.
488
489 ``by``
490 string, the property to use for comparison (default: ``msgid``).
491
492 ``include_obsolete_entries``
493 boolean, whether to also search in entries that are obsolete.
494
495 ``msgctxt``
496 string, allows specifying a specific message context for the
497 search.
498 """
499 if include_obsolete_entries:
500 entries = self[:]
501 else:
502 entries = [e for e in self if not e.obsolete]
503 for e in entries:
504 if getattr(e, by) == st:
505 if msgctxt is not False and e.msgctxt != msgctxt:
506 continue
507 return e
508 return None
509
510 def ordered_metadata(self):
511 """
512 Convenience method that returns an ordered version of the metadata
513 dictionary. The return value is list of tuples (metadata name,
514 metadata_value).
515 """
516 # copy the dict first
517 metadata = self.metadata.copy()
518 data_order = [
519 'Project-Id-Version',
520 'Report-Msgid-Bugs-To',
521 'POT-Creation-Date',
522 'PO-Revision-Date',
523 'Last-Translator',
524 'Language-Team',
525 'MIME-Version',
526 'Content-Type',
527 'Content-Transfer-Encoding',
528 'Language',
529 'Plural-Forms',
530 ]
531 ordered_data = []
532 for data in data_order:
533 try:
534 value = metadata.pop(data)
535 ordered_data.append((data, value))
536 except KeyError:
537 pass
538 # the rest of the metadata will be alphabetically ordered since there
539 # are no specs for this AFAIK
540 for data in sorted(metadata.keys()):
541 value = metadata[data]
542 ordered_data.append((data, value))
543 return ordered_data
544
545 def to_binary(self):
546 """
547 Return the binary representation of the file.
548 """
549 offsets = []
550 entries = self.translated_entries()
551
552 # add metadata entry
553 entries.sort(key=lambda o: o.msgctxt or o.msgid)
554 mentry = self.metadata_as_entry()
555 # mentry.msgstr = mentry.msgstr.replace('\\n', '').lstrip()
556 entries = [mentry] + entries
557 entries_len = len(entries)
558 ids, strs = b(''), b('')
559 for e in entries:
560 # For each string, we need size and file offset. Each string is
561 # NUL terminated; the NUL does not count into the size.
562 msgid = b('')
563 if e.msgctxt:
564 # Contexts are stored by storing the concatenation of the
565 # context, a <EOT> byte, and the original string
566 msgid = self._encode(e.msgctxt + '\4')
567 if e.msgid_plural:
568 msgstr = []
569 for index in sorted(e.msgstr_plural.keys()):
570 msgstr.append(e.msgstr_plural[index])
571 msgid += self._encode(e.msgid + '\0' + e.msgid_plural)
572 msgstr = self._encode('\0'.join(msgstr))
573 else:
574 msgid += self._encode(e.msgid)
575 msgstr = self._encode(e.msgstr)
576 offsets.append((len(ids), len(msgid), len(strs), len(msgstr)))
577 ids += msgid + b('\0')
578 strs += msgstr + b('\0')
579
580 # The header is 7 32-bit unsigned integers.
581 keystart = 7 * 4 + 16 * entries_len
582 # and the values start after the keys
583 valuestart = keystart + len(ids)
584 koffsets = []
585 voffsets = []
586 # The string table first has the list of keys, then the list of values.
587 # Each entry has first the size of the string, then the file offset.
588 for o1, l1, o2, l2 in offsets:
589 koffsets += [l1, o1 + keystart]
590 voffsets += [l2, o2 + valuestart]
591 offsets = koffsets + voffsets
592
593 output = struct.pack(
594 "Iiiiiii",
595 # Magic number
596 MOFile.MAGIC,
597 # Version
598 0,
599 # number of entries
600 entries_len,
601 # start of key index
602 7 * 4,
603 # start of value index
604 7 * 4 + entries_len * 8,
605 # size and offset of hash table, we don't use hash tables
606 0,
607 keystart,
608 )
609 if PY3 and sys.version_info.minor > 1: # python 3.2 or superior
610 output += array.array("i", offsets).tobytes()
611 else:
612 output += array.array("i", offsets).tostring()
613 output += ids
614 output += strs
615 return output
616
617 def _encode(self, mixed):
618 """
619 Encodes the given ``mixed`` argument with the file encoding if and
620 only if it's an unicode string and returns the encoded string.
621 """
622 if isinstance(mixed, text_type):
623 mixed = mixed.encode(self.encoding)
624 return mixed
625
626
627 # }}}
628 # class POFile {{{
629
630
631 class POFile(_BaseFile):
632 """
633 Po (or Pot) file reader/writer.
634 This class inherits the :class:`~polib._BaseFile` class and, by extension,
635 the python ``list`` type.
636 """
637
638 def __unicode__(self):
639 """
640 Returns the unicode representation of the po file.
641 """
642 ret, headers = '', self.header.split('\n')
643 for header in headers:
644 if not len(header):
645 ret += "#\n"
646 elif header[:1] in [',', ':']:
647 ret += '#%s\n' % header
648 else:
649 ret += '# %s\n' % header
650
651 if not isinstance(ret, text_type):
652 ret = ret.decode(self.encoding)
653
654 return ret + _BaseFile.__unicode__(self)
655
656 def save_as_mofile(self, fpath):
657 """
658 Saves the binary representation of the file to given ``fpath``.
659
660 Keyword argument:
661
662 ``fpath``
663 string, full or relative path to the mo file.
664 """
665 _BaseFile.save(self, fpath, 'to_binary')
666
667 def percent_translated(self):
668 """
669 Convenience method that returns the percentage of translated
670 messages.
671 """
672 total = len([e for e in self if not e.obsolete])
673 if total == 0:
674 return 100
675 translated = len(self.translated_entries())
676 return int(translated * 100 / float(total))
677
678 def translated_entries(self):
679 """
680 Convenience method that returns the list of translated entries.
681 """
682 return [e for e in self if e.translated()]
683
684 def untranslated_entries(self):
685 """
686 Convenience method that returns the list of untranslated entries.
687 """
688 return [
689 e
690 for e in self
691 if not e.translated() and not e.obsolete and not 'fuzzy' in e.flags
692 ]
693
694 def fuzzy_entries(self):
695 """
696 Convenience method that returns the list of fuzzy entries.
697 """
698 return [e for e in self if 'fuzzy' in e.flags]
699
700 def obsolete_entries(self):
701 """
702 Convenience method that returns the list of obsolete entries.
703 """
704 return [e for e in self if e.obsolete]
705
706 def merge(self, refpot):
707 """
708 Convenience method that merges the current pofile with the pot file
709 provided. It behaves exactly as the gettext msgmerge utility:
710
711 * comments of this file will be preserved, but extracted comments and
712 occurrences will be discarded;
713 * any translations or comments in the file will be discarded, however,
714 dot comments and file positions will be preserved;
715 * the fuzzy flags are preserved.
716
717 Keyword argument:
718
719 ``refpot``
720 object POFile, the reference catalog.
721 """
722 # Store entries in dict/set for faster access
723 self_entries = {entry.msgid: entry for entry in self}
724 refpot_msgids = {entry.msgid for entry in refpot}
725 # Merge entries that are in the refpot
726 for entry in refpot:
727 e = self_entries.get(entry.msgid)
728 if e is None:
729 e = POEntry()
730 self.append(e)
731 e.merge(entry)
732 # ok, now we must "obsolete" entries that are not in the refpot anymore
733 for entry in self:
734 if entry.msgid not in refpot_msgids:
735 entry.obsolete = True
736
737
738 # }}}
739 # class MOFile {{{
740
741
742 class MOFile(_BaseFile):
743 """
744 Mo file reader/writer.
745 This class inherits the :class:`~polib._BaseFile` class and, by
746 extension, the python ``list`` type.
747 """
748
749 MAGIC = 0x950412DE
750 MAGIC_SWAPPED = 0xDE120495
751
752 def __init__(self, *args, **kwargs):
753 """
754 Constructor, accepts all keywords arguments accepted by
755 :class:`~polib._BaseFile` class.
756 """
757 _BaseFile.__init__(self, *args, **kwargs)
758 self.magic_number = None
759 self.version = 0
760
761 def save_as_pofile(self, fpath):
762 """
763 Saves the mofile as a pofile to ``fpath``.
764
765 Keyword argument:
766
767 ``fpath``
768 string, full or relative path to the file.
769 """
770 _BaseFile.save(self, fpath)
771
772 def save(self, fpath=None):
773 """
774 Saves the mofile to ``fpath``.
775
776 Keyword argument:
777
778 ``fpath``
779 string, full or relative path to the file.
780 """
781 _BaseFile.save(self, fpath, 'to_binary')
782
783 def percent_translated(self):
784 """
785 Convenience method to keep the same interface with POFile instances.
786 """
787 return 100
788
789 def translated_entries(self):
790 """
791 Convenience method to keep the same interface with POFile instances.
792 """
793 return self
794
795 def untranslated_entries(self):
796 """
797 Convenience method to keep the same interface with POFile instances.
798 """
799 return []
800
801 def fuzzy_entries(self):
802 """
803 Convenience method to keep the same interface with POFile instances.
804 """
805 return []
806
807 def obsolete_entries(self):
808 """
809 Convenience method to keep the same interface with POFile instances.
810 """
811 return []
812
813
814 # }}}
815 # class _BaseEntry {{{
816
817
818 class _BaseEntry:
819 """
820 Base class for :class:`~polib.POEntry` and :class:`~polib.MOEntry` classes.
821 This class should **not** be instanciated directly.
822 """
823
824 def __init__(self, *args, **kwargs):
825 """
826 Constructor, accepts the following keyword arguments:
827
828 ``msgid``
829 string, the entry msgid.
830
831 ``msgstr``
832 string, the entry msgstr.
833
834 ``msgid_plural``
835 string, the entry msgid_plural.
836
837 ``msgstr_plural``
838 list, the entry msgstr_plural lines.
839
840 ``msgctxt``
841 string, the entry context (msgctxt).
842
843 ``obsolete``
844 bool, whether the entry is "obsolete" or not.
845
846 ``encoding``
847 string, the encoding to use, defaults to ``default_encoding``
848 global variable (optional).
849 """
850 self.msgid = kwargs.get('msgid', '')
851 self.msgstr = kwargs.get('msgstr', '')
852 self.msgid_plural = kwargs.get('msgid_plural', '')
853 self.msgstr_plural = kwargs.get('msgstr_plural', {})
854 self.msgctxt = kwargs.get('msgctxt', None)
855 self.obsolete = kwargs.get('obsolete', False)
856 self.encoding = kwargs.get('encoding', default_encoding)
857
858 def __unicode__(self, wrapwidth=78):
859 """
860 Returns the unicode representation of the entry.
861 """
862 if self.obsolete:
863 delflag = '#~ '
864 else:
865 delflag = ''
866 ret = []
867 # write the msgctxt if any
868 if self.msgctxt is not None:
869 ret += self._str_field(
870 "msgctxt", delflag, "", self.msgctxt, wrapwidth
871 )
872 # write the msgid
873 ret += self._str_field("msgid", delflag, "", self.msgid, wrapwidth)
874 # write the msgid_plural if any
875 if self.msgid_plural:
876 ret += self._str_field(
877 "msgid_plural", delflag, "", self.msgid_plural, wrapwidth
878 )
879 if self.msgstr_plural:
880 # write the msgstr_plural if any
881 msgstrs = self.msgstr_plural
882 keys = list(msgstrs)
883 keys.sort()
884 for index in keys:
885 msgstr = msgstrs[index]
886 plural_index = '[%s]' % index
887 ret += self._str_field(
888 "msgstr", delflag, plural_index, msgstr, wrapwidth
889 )
890 else:
891 # otherwise write the msgstr
892 ret += self._str_field(
893 "msgstr", delflag, "", self.msgstr, wrapwidth
894 )
895 ret.append('')
896 ret = u('\n').join(ret)
897 return ret
898
899 if PY3:
900
901 def __str__(self):
902 return self.__unicode__()
903
904 else:
905
906 def __str__(self):
907 """
908 Returns the string representation of the entry.
909 """
910 return unicode(self).encode(self.encoding)
911
912 def __eq__(self, other):
913 return str(self) == str(other)
914
915 def _str_field(self, fieldname, delflag, plural_index, field, wrapwidth=78):
916 lines = field.splitlines(True)
917 if len(lines) > 1:
918 lines = [''] + lines # start with initial empty line
919 else:
920 escaped_field = escape(field)
921 specialchars_count = 0
922 for c in ['\\', '\n', '\r', '\t', '"']:
923 specialchars_count += field.count(c)
924 # comparison must take into account fieldname length + one space
925 # + 2 quotes (eg. msgid "<string>")
926 flength = len(fieldname) + 3
927 if plural_index:
928 flength += len(plural_index)
929 real_wrapwidth = wrapwidth - flength + specialchars_count
930 if wrapwidth > 0 and len(field) > real_wrapwidth:
931 # Wrap the line but take field name into account
932 lines = [''] + [
933 unescape(item)
934 for item in wrap(
935 escaped_field,
936 wrapwidth - 2, # 2 for quotes ""
937 drop_whitespace=False,
938 break_long_words=False,
939 )
940 ]
941 else:
942 lines = [field]
943 if fieldname.startswith('previous_'):
944 # quick and dirty trick to get the real field name
945 fieldname = fieldname[9:]
946
947 ret = [
948 '%s%s%s "%s"'
949 % (delflag, fieldname, plural_index, escape(lines.pop(0)))
950 ]
951 for line in lines:
952 ret.append('%s"%s"' % (delflag, escape(line)))
953 return ret
954
955
956 # }}}
957 # class POEntry {{{
958
959
960 class POEntry(_BaseEntry):
961 """
962 Represents a po file entry.
963 """
964
965 def __init__(self, *args, **kwargs):
966 """
967 Constructor, accepts the following keyword arguments:
968
969 ``comment``
970 string, the entry comment.
971
972 ``tcomment``
973 string, the entry translator comment.
974
975 ``occurrences``
976 list, the entry occurrences.
977
978 ``flags``
979 list, the entry flags.
980
981 ``previous_msgctxt``
982 string, the entry previous context.
983
984 ``previous_msgid``
985 string, the entry previous msgid.
986
987 ``previous_msgid_plural``
988 string, the entry previous msgid_plural.
989
990 ``linenum``
991 integer, the line number of the entry
992 """
993 _BaseEntry.__init__(self, *args, **kwargs)
994 self.comment = kwargs.get('comment', '')
995 self.tcomment = kwargs.get('tcomment', '')
996 self.occurrences = kwargs.get('occurrences', [])
997 self.flags = kwargs.get('flags', [])
998 self.previous_msgctxt = kwargs.get('previous_msgctxt', None)
999 self.previous_msgid = kwargs.get('previous_msgid', None)
1000 self.previous_msgid_plural = kwargs.get('previous_msgid_plural', None)
1001 self.linenum = kwargs.get('linenum', None)
1002
1003 def __unicode__(self, wrapwidth=78):
1004 """
1005 Returns the unicode representation of the entry.
1006 """
1007 if self.obsolete:
1008 return _BaseEntry.__unicode__(self, wrapwidth)
1009
1010 ret = []
1011 # comments first, if any (with text wrapping as xgettext does)
1012 comments = [('comment', '#. '), ('tcomment', '# ')]
1013 for c in comments:
1014 val = getattr(self, c[0])
1015 if val:
1016 for comment in val.split('\n'):
1017 if wrapwidth > 0 and len(comment) + len(c[1]) > wrapwidth:
1018 ret += wrap(
1019 comment,
1020 wrapwidth,
1021 initial_indent=c[1],
1022 subsequent_indent=c[1],
1023 break_long_words=False,
1024 )
1025 else:
1026 ret.append('%s%s' % (c[1], comment))
1027
1028 # occurrences (with text wrapping as xgettext does)
1029 if self.occurrences:
1030 filelist = []
1031 for fpath, lineno in self.occurrences:
1032 if lineno:
1033 filelist.append('%s:%s' % (fpath, lineno))
1034 else:
1035 filelist.append(fpath)
1036 filestr = ' '.join(filelist)
1037 if wrapwidth > 0 and len(filestr) + 3 > wrapwidth:
1038 # textwrap split words that contain hyphen, this is not
1039 # what we want for filenames, so the dirty hack is to
1040 # temporally replace hyphens with a char that a file cannot
1041 # contain, like "*"
1042 ret += [
1043 l.replace('*', '-')
1044 for l in wrap(
1045 filestr.replace('-', '*'),
1046 wrapwidth,
1047 initial_indent='#: ',
1048 subsequent_indent='#: ',
1049 break_long_words=False,
1050 )
1051 ]
1052 else:
1053 ret.append('#: ' + filestr)
1054
1055 # flags (TODO: wrapping ?)
1056 if self.flags:
1057 ret.append('#, %s' % ', '.join(self.flags))
1058
1059 # previous context and previous msgid/msgid_plural
1060 fields = ['previous_msgctxt', 'previous_msgid', 'previous_msgid_plural']
1061 for f in fields:
1062 val = getattr(self, f)
1063 if val:
1064 ret += self._str_field(f, "#| ", "", val, wrapwidth)
1065
1066 ret.append(_BaseEntry.__unicode__(self, wrapwidth))
1067 ret = u('\n').join(ret)
1068
1069 assert isinstance(ret, text_type)
1070 # if type(ret) != types.UnicodeType:
1071 # return unicode(ret, self.encoding)
1072 return ret
1073
1074 def __cmp__(self, other):
1075 """
1076 Called by comparison operations if rich comparison is not defined.
1077 """
1078
1079 # First: Obsolete test
1080 if self.obsolete != other.obsolete:
1081 if self.obsolete:
1082 return -1
1083 else:
1084 return 1
1085 # Work on a copy to protect original
1086 occ1 = sorted(self.occurrences[:])
1087 occ2 = sorted(other.occurrences[:])
1088 pos = 0
1089 for entry1 in occ1:
1090 try:
1091 entry2 = occ2[pos]
1092 except IndexError:
1093 return 1
1094 pos = pos + 1
1095 if entry1[0] != entry2[0]:
1096 if entry1[0] > entry2[0]:
1097 return 1
1098 else:
1099 return -1
1100 if entry1[1] != entry2[1]:
1101 if entry1[1] > entry2[1]:
1102 return 1
1103 else:
1104 return -1
1105 # Compare msgid_plural if set
1106 if self.msgid_plural:
1107 if not other.msgid_plural:
1108 return 1
1109 for pos in self.msgid_plural:
1110 if pos not in other.msgid_plural:
1111 return 1
1112 if self.msgid_plural[pos] > other.msgid_plural[pos]:
1113 return 1
1114 if self.msgid_plural[pos] < other.msgid_plural[pos]:
1115 return -1
1116 # Finally: Compare message ID
1117 if self.msgid > other.msgid:
1118 return 1
1119 elif self.msgid < other.msgid:
1120 return -1
1121 return 0
1122
1123 def __gt__(self, other):
1124 return self.__cmp__(other) > 0
1125
1126 def __lt__(self, other):
1127 return self.__cmp__(other) < 0
1128
1129 def __ge__(self, other):
1130 return self.__cmp__(other) >= 0
1131
1132 def __le__(self, other):
1133 return self.__cmp__(other) <= 0
1134
1135 def __eq__(self, other):
1136 return self.__cmp__(other) == 0
1137
1138 def __ne__(self, other):
1139 return self.__cmp__(other) != 0
1140
1141 def translated(self):
1142 """
1143 Returns ``True`` if the entry has been translated or ``False``
1144 otherwise.
1145 """
1146 if self.obsolete or 'fuzzy' in self.flags:
1147 return False
1148 if self.msgstr != '':
1149 return True
1150 if self.msgstr_plural:
1151 for pos in self.msgstr_plural:
1152 if self.msgstr_plural[pos] == '':
1153 return False
1154 return True
1155 return False
1156
1157 def merge(self, other):
1158 """
1159 Merge the current entry with the given pot entry.
1160 """
1161 self.msgid = other.msgid
1162 self.msgctxt = other.msgctxt
1163 self.occurrences = other.occurrences
1164 self.comment = other.comment
1165 fuzzy = 'fuzzy' in self.flags
1166 self.flags = other.flags[:] # clone flags
1167 if fuzzy:
1168 self.flags.append('fuzzy')
1169 self.msgid_plural = other.msgid_plural
1170 self.obsolete = other.obsolete
1171 self.previous_msgctxt = other.previous_msgctxt
1172 self.previous_msgid = other.previous_msgid
1173 self.previous_msgid_plural = other.previous_msgid_plural
1174 if other.msgstr_plural:
1175 for pos in other.msgstr_plural:
1176 try:
1177 # keep existing translation at pos if any
1178 self.msgstr_plural[pos]
1179 except KeyError:
1180 self.msgstr_plural[pos] = ''
1181
1182 def __hash__(self):
1183 return hash((self.msgid, self.msgstr))
1184
1185
1186 # }}}
1187 # class MOEntry {{{
1188
1189
1190 class MOEntry(_BaseEntry):
1191 """
1192 Represents a mo file entry.
1193 """
1194
1195 def __init__(self, *args, **kwargs):
1196 """
1197 Constructor, accepts the following keyword arguments,
1198 for consistency with :class:`~polib.POEntry`:
1199
1200 ``comment``
1201 ``tcomment``
1202 ``occurrences``
1203 ``flags``
1204 ``previous_msgctxt``
1205 ``previous_msgid``
1206 ``previous_msgid_plural``
1207
1208 Note: even though these keyword arguments are accepted,
1209 they hold no real meaning in the context of MO files
1210 and are simply ignored.
1211 """
1212 _BaseEntry.__init__(self, *args, **kwargs)
1213 self.comment = ''
1214 self.tcomment = ''
1215 self.occurrences = []
1216 self.flags = []
1217 self.previous_msgctxt = None
1218 self.previous_msgid = None
1219 self.previous_msgid_plural = None
1220
1221 def __hash__(self):
1222 return hash((self.msgid, self.msgstr))
1223
1224
1225 # }}}
1226 # class _POFileParser {{{
1227
1228
1229 class _POFileParser:
1230 """
1231 A finite state machine to parse efficiently and correctly po
1232 file format.
1233 """
1234
1235 def __init__(self, pofile, *args, **kwargs):
1236 """
1237 Constructor.
1238
1239 Keyword arguments:
1240
1241 ``pofile``
1242 string, path to the po file or its content
1243
1244 ``encoding``
1245 string, the encoding to use, defaults to ``default_encoding``
1246 global variable (optional).
1247
1248 ``check_for_duplicates``
1249 whether to check for duplicate entries when adding entries to the
1250 file (optional, default: ``False``).
1251 """
1252 enc = kwargs.get('encoding', default_encoding)
1253 if _is_file(pofile):
1254 try:
1255 self.fhandle = open(pofile, encoding=enc)
1256 except LookupError:
1257 enc = default_encoding
1258 self.fhandle = open(pofile, encoding=enc)
1259 else:
1260 self.fhandle = pofile.splitlines()
1261
1262 klass = kwargs.get('klass')
1263 if klass is None:
1264 klass = POFile
1265 self.instance = klass(
1266 pofile=pofile,
1267 encoding=enc,
1268 check_for_duplicates=kwargs.get('check_for_duplicates', False),
1269 )
1270 self.transitions = {}
1271 self.current_line = 0
1272 self.current_entry = POEntry(linenum=self.current_line)
1273 self.current_state = 'st'
1274 self.current_token = None
1275 # two memo flags used in handlers
1276 self.msgstr_index = 0
1277 self.entry_obsolete = 0
1278 # Configure the state machine, by adding transitions.
1279 # Signification of symbols:
1280 # * ST: Beginning of the file (start)
1281 # * HE: Header
1282 # * TC: a translation comment
1283 # * GC: a generated comment
1284 # * OC: a file/line occurrence
1285 # * FL: a flags line
1286 # * CT: a message context
1287 # * PC: a previous msgctxt
1288 # * PM: a previous msgid
1289 # * PP: a previous msgid_plural
1290 # * MI: a msgid
1291 # * MP: a msgid plural
1292 # * MS: a msgstr
1293 # * MX: a msgstr plural
1294 # * MC: a msgid or msgstr continuation line
1295 all = [
1296 'st',
1297 'he',
1298 'gc',
1299 'oc',
1300 'fl',
1301 'ct',
1302 'pc',
1303 'pm',
1304 'pp',
1305 'tc',
1306 'ms',
1307 'mp',
1308 'mx',
1309 'mi',
1310 ]
1311
1312 self.add('tc', ['st', 'he'], 'he')
1313 self.add(
1314 'tc',
1315 ['gc', 'oc', 'fl', 'tc', 'pc', 'pm', 'pp', 'ms', 'mp', 'mx', 'mi'],
1316 'tc',
1317 )
1318 self.add('gc', all, 'gc')
1319 self.add('oc', all, 'oc')
1320 self.add('fl', all, 'fl')
1321 self.add('pc', all, 'pc')
1322 self.add('pm', all, 'pm')
1323 self.add('pp', all, 'pp')
1324 self.add(
1325 'ct',
1326 ['st', 'he', 'gc', 'oc', 'fl', 'tc', 'pc', 'pm', 'pp', 'ms', 'mx'],
1327 'ct',
1328 )
1329 self.add(
1330 'mi',
1331 [
1332 'st',
1333 'he',
1334 'gc',
1335 'oc',
1336 'fl',
1337 'ct',
1338 'tc',
1339 'pc',
1340 'pm',
1341 'pp',
1342 'ms',
1343 'mx',
1344 ],
1345 'mi',
1346 )
1347 self.add('mp', ['tc', 'gc', 'pc', 'pm', 'pp', 'mi'], 'mp')
1348 self.add('ms', ['mi', 'mp', 'tc'], 'ms')
1349 self.add('mx', ['mi', 'mx', 'mp', 'tc'], 'mx')
1350 self.add('mc', ['ct', 'mi', 'mp', 'ms', 'mx', 'pm', 'pp', 'pc'], 'mc')
1351
1352 def parse(self):
1353 """
1354 Run the state machine, parse the file line by line and call process()
1355 with the current matched symbol.
1356 """
1357
1358 keywords = {
1359 'msgctxt': 'ct',
1360 'msgid': 'mi',
1361 'msgstr': 'ms',
1362 'msgid_plural': 'mp',
1363 }
1364 prev_keywords = {
1365 'msgid_plural': 'pp',
1366 'msgid': 'pm',
1367 'msgctxt': 'pc',
1368 }
1369 tokens = []
1370 for line in self.fhandle:
1371 self.current_line += 1
1372 line = line.strip()
1373 if line == '':
1374 continue
1375
1376 tokens = line.split(None, 2)
1377 nb_tokens = len(tokens)
1378
1379 if tokens[0] == '#~|':
1380 continue
1381
1382 if tokens[0] == '#~' and nb_tokens > 1:
1383 line = line[3:].strip()
1384 tokens = tokens[1:]
1385 nb_tokens -= 1
1386 self.entry_obsolete = 1
1387 else:
1388 self.entry_obsolete = 0
1389
1390 # Take care of keywords like
1391 # msgid, msgid_plural, msgctxt & msgstr.
1392 if tokens[0] in keywords and nb_tokens > 1:
1393 line = line[len(tokens[0]) :].lstrip()
1394 if re.search(r'([^\\]|^)"', line[1:-1]):
1395 raise OSError(
1396 'Syntax error in po file %s (line %s): '
1397 'unescaped double quote found'
1398 % (self.instance.fpath, self.current_line)
1399 )
1400 self.current_token = line
1401 self.process(keywords[tokens[0]])
1402 continue
1403
1404 self.current_token = line
1405
1406 if tokens[0] == '#:':
1407 if nb_tokens <= 1:
1408 continue
1409 # we are on a occurrences line
1410 self.process('oc')
1411
1412 elif line[:1] == '"':
1413 # we are on a continuation line
1414 if re.search(r'([^\\]|^)"', line[1:-1]):
1415 raise OSError(
1416 'Syntax error in po file %s (line %s): '
1417 'unescaped double quote found'
1418 % (self.instance.fpath, self.current_line)
1419 )
1420 self.process('mc')
1421
1422 elif line[:7] == 'msgstr[':
1423 # we are on a msgstr plural
1424 self.process('mx')
1425
1426 elif tokens[0] == '#,':
1427 if nb_tokens <= 1:
1428 continue
1429 # we are on a flags line
1430 self.process('fl')
1431
1432 elif tokens[0] == '#' or tokens[0].startswith('##'):
1433 if line == '#':
1434 line += ' '
1435 # we are on a translator comment line
1436 self.process('tc')
1437
1438 elif tokens[0] == '#.':
1439 if nb_tokens <= 1:
1440 continue
1441 # we are on a generated comment line
1442 self.process('gc')
1443
1444 elif tokens[0] == '#|':
1445 if nb_tokens <= 1:
1446 raise OSError(
1447 'Syntax error in po file %s (line %s)'
1448 % (self.instance.fpath, self.current_line)
1449 )
1450
1451 # Remove the marker and any whitespace right after that.
1452 line = line[2:].lstrip()
1453 self.current_token = line
1454
1455 if tokens[1].startswith('"'):
1456 # Continuation of previous metadata.
1457 self.process('mc')
1458 continue
1459
1460 if nb_tokens == 2:
1461 # Invalid continuation line.
1462 raise OSError(
1463 'Syntax error in po file %s (line %s): '
1464 'invalid continuation line'
1465 % (self.instance.fpath, self.current_line)
1466 )
1467
1468 # we are on a "previous translation" comment line,
1469 if tokens[1] not in prev_keywords:
1470 # Unknown keyword in previous translation comment.
1471 raise OSError(
1472 'Syntax error in po file %s (line %s): '
1473 'unknown keyword %s'
1474 % (self.instance.fpath, self.current_line, tokens[1])
1475 )
1476
1477 # Remove the keyword and any whitespace
1478 # between it and the starting quote.
1479 line = line[len(tokens[1]) :].lstrip()
1480 self.current_token = line
1481 self.process(prev_keywords[tokens[1]])
1482
1483 else:
1484 raise OSError(
1485 'Syntax error in po file %s (line %s)'
1486 % (self.instance.fpath, self.current_line)
1487 )
1488
1489 if (
1490 self.current_entry
1491 and len(tokens) > 0
1492 and not tokens[0].startswith('#')
1493 ):
1494 # since entries are added when another entry is found, we must add
1495 # the last entry here (only if there are lines). Trailing comments
1496 # are ignored
1497 self.instance.append(self.current_entry)
1498
1499 # before returning the instance, check if there's metadata and if
1500 # so extract it in a dict
1501 metadataentry = self.instance.find('')
1502 if metadataentry: # metadata found
1503 # remove the entry
1504 self.instance.remove(metadataentry)
1505 self.instance.metadata_is_fuzzy = metadataentry.flags
1506 key = None
1507 for msg in metadataentry.msgstr.splitlines():
1508 try:
1509 key, val = msg.split(':', 1)
1510 self.instance.metadata[key] = val.strip()
1511 except (ValueError, KeyError):
1512 if key is not None:
1513 self.instance.metadata[key] += '\n' + msg.strip()
1514 # close opened file
1515 if not isinstance(self.fhandle, list): # must be file
1516 self.fhandle.close()
1517 return self.instance
1518
1519 def add(self, symbol, states, next_state):
1520 """
1521 Add a transition to the state machine.
1522
1523 Keywords arguments:
1524
1525 ``symbol``
1526 string, the matched token (two chars symbol).
1527
1528 ``states``
1529 list, a list of states (two chars symbols).
1530
1531 ``next_state``
1532 the next state the fsm will have after the action.
1533 """
1534 for state in states:
1535 action = getattr(self, 'handle_%s' % next_state)
1536 self.transitions[(symbol, state)] = (action, next_state)
1537
1538 def process(self, symbol):
1539 """
1540 Process the transition corresponding to the current state and the
1541 symbol provided.
1542
1543 Keywords arguments:
1544
1545 ``symbol``
1546 string, the matched token (two chars symbol).
1547
1548 ``linenum``
1549 integer, the current line number of the parsed file.
1550 """
1551 try:
1552 (action, state) = self.transitions[(symbol, self.current_state)]
1553 if action():
1554 self.current_state = state
1555 except Exception:
1556 raise OSError(
1557 'Syntax error in po file (line %s)' % self.current_line
1558 )
1559
1560 # state handlers
1561
1562 def handle_he(self):
1563 """Handle a header comment."""
1564 if self.instance.header != '':
1565 self.instance.header += '\n'
1566 self.instance.header += self.current_token[2:]
1567 return 1
1568
1569 def handle_tc(self):
1570 """Handle a translator comment."""
1571 if self.current_state in ['mc', 'ms', 'mx']:
1572 self.instance.append(self.current_entry)
1573 self.current_entry = POEntry(linenum=self.current_line)
1574 if self.current_entry.tcomment != '':
1575 self.current_entry.tcomment += '\n'
1576 tcomment = self.current_token.lstrip('#')
1577 if tcomment.startswith(' '):
1578 tcomment = tcomment[1:]
1579 self.current_entry.tcomment += tcomment
1580 return True
1581
1582 def handle_gc(self):
1583 """Handle a generated comment."""
1584 if self.current_state in ['mc', 'ms', 'mx']:
1585 self.instance.append(self.current_entry)
1586 self.current_entry = POEntry(linenum=self.current_line)
1587 if self.current_entry.comment != '':
1588 self.current_entry.comment += '\n'
1589 self.current_entry.comment += self.current_token[3:]
1590 return True
1591
1592 def handle_oc(self):
1593 """Handle a file:num occurrence."""
1594 if self.current_state in ['mc', 'ms', 'mx']:
1595 self.instance.append(self.current_entry)
1596 self.current_entry = POEntry(linenum=self.current_line)
1597 occurrences = self.current_token[3:].split()
1598 for occurrence in occurrences:
1599 if occurrence != '':
1600 try:
1601 fil, line = occurrence.split(':')
1602 if not line.isdigit():
1603 fil = fil + line
1604 line = ''
1605 self.current_entry.occurrences.append((fil, line))
1606 except (ValueError, AttributeError):
1607 self.current_entry.occurrences.append((occurrence, ''))
1608 return True
1609
1610 def handle_fl(self):
1611 """Handle a flags line."""
1612 if self.current_state in ['mc', 'ms', 'mx']:
1613 self.instance.append(self.current_entry)
1614 self.current_entry = POEntry(linenum=self.current_line)
1615 self.current_entry.flags += [
1616 c.strip() for c in self.current_token[3:].split(',')
1617 ]
1618 return True
1619
1620 def handle_pp(self):
1621 """Handle a previous msgid_plural line."""
1622 if self.current_state in ['mc', 'ms', 'mx']:
1623 self.instance.append(self.current_entry)
1624 self.current_entry = POEntry(linenum=self.current_line)
1625 self.current_entry.previous_msgid_plural = unescape(
1626 self.current_token[1:-1]
1627 )
1628 return True
1629
1630 def handle_pm(self):
1631 """Handle a previous msgid line."""
1632 if self.current_state in ['mc', 'ms', 'mx']:
1633 self.instance.append(self.current_entry)
1634 self.current_entry = POEntry(linenum=self.current_line)
1635 self.current_entry.previous_msgid = unescape(self.current_token[1:-1])
1636 return True
1637
1638 def handle_pc(self):
1639 """Handle a previous msgctxt line."""
1640 if self.current_state in ['mc', 'ms', 'mx']:
1641 self.instance.append(self.current_entry)
1642 self.current_entry = POEntry(linenum=self.current_line)
1643 self.current_entry.previous_msgctxt = unescape(self.current_token[1:-1])
1644 return True
1645
1646 def handle_ct(self):
1647 """Handle a msgctxt."""
1648 if self.current_state in ['mc', 'ms', 'mx']:
1649 self.instance.append(self.current_entry)
1650 self.current_entry = POEntry(linenum=self.current_line)
1651 self.current_entry.msgctxt = unescape(self.current_token[1:-1])
1652 return True
1653
1654 def handle_mi(self):
1655 """Handle a msgid."""
1656 if self.current_state in ['mc', 'ms', 'mx']:
1657 self.instance.append(self.current_entry)
1658 self.current_entry = POEntry(linenum=self.current_line)
1659 self.current_entry.obsolete = self.entry_obsolete
1660 self.current_entry.msgid = unescape(self.current_token[1:-1])
1661 return True
1662
1663 def handle_mp(self):
1664 """Handle a msgid plural."""
1665 self.current_entry.msgid_plural = unescape(self.current_token[1:-1])
1666 return True
1667
1668 def handle_ms(self):
1669 """Handle a msgstr."""
1670 self.current_entry.msgstr = unescape(self.current_token[1:-1])
1671 return True
1672
1673 def handle_mx(self):
1674 """Handle a msgstr plural."""
1675 index = self.current_token[7]
1676 value = self.current_token[self.current_token.find('"') + 1 : -1]
1677 self.current_entry.msgstr_plural[int(index)] = unescape(value)
1678 self.msgstr_index = int(index)
1679 return True
1680
1681 def handle_mc(self):
1682 """Handle a msgid or msgstr continuation line."""
1683 token = unescape(self.current_token[1:-1])
1684 if self.current_state == 'ct':
1685 self.current_entry.msgctxt += token
1686 elif self.current_state == 'mi':
1687 self.current_entry.msgid += token
1688 elif self.current_state == 'mp':
1689 self.current_entry.msgid_plural += token
1690 elif self.current_state == 'ms':
1691 self.current_entry.msgstr += token
1692 elif self.current_state == 'mx':
1693 self.current_entry.msgstr_plural[self.msgstr_index] += token
1694 elif self.current_state == 'pp':
1695 self.current_entry.previous_msgid_plural += token
1696 elif self.current_state == 'pm':
1697 self.current_entry.previous_msgid += token
1698 elif self.current_state == 'pc':
1699 self.current_entry.previous_msgctxt += token
1700 # don't change the current state
1701 return False
1702
1703
1704 # }}}
1705 # class _MOFileParser {{{
1706
1707
1708 class _MOFileParser:
1709 """
1710 A class to parse binary mo files.
1711 """
1712
1713 def __init__(self, mofile, *args, **kwargs):
1714 """
1715 Constructor.
1716
1717 Keyword arguments:
1718
1719 ``mofile``
1720 string, path to the mo file or its content
1721
1722 ``encoding``
1723 string, the encoding to use, defaults to ``default_encoding``
1724 global variable (optional).
1725
1726 ``check_for_duplicates``
1727 whether to check for duplicate entries when adding entries to the
1728 file (optional, default: ``False``).
1729 """
1730 self.fhandle = open(mofile, 'rb')
1731
1732 klass = kwargs.get('klass')
1733 if klass is None:
1734 klass = MOFile
1735 self.instance = klass(
1736 fpath=mofile,
1737 encoding=kwargs.get('encoding', default_encoding),
1738 check_for_duplicates=kwargs.get('check_for_duplicates', False),
1739 )
1740
1741 def __del__(self):
1742 """
1743 Make sure the file is closed, this prevents warnings on unclosed file
1744 when running tests with python >= 3.2.
1745 """
1746 if self.fhandle:
1747 self.fhandle.close()
1748
1749 def parse(self):
1750 """
1751 Build the instance with the file handle provided in the
1752 constructor.
1753 """
1754 # parse magic number
1755 magic_number = self._readbinary('<I', 4)
1756 if magic_number == MOFile.MAGIC:
1757 ii = '<II'
1758 elif magic_number == MOFile.MAGIC_SWAPPED:
1759 ii = '>II'
1760 else:
1761 raise OSError('Invalid mo file, magic number is incorrect !')
1762 self.instance.magic_number = magic_number
1763 # parse the version number and the number of strings
1764 version, numofstrings = self._readbinary(ii, 8)
1765 # from MO file format specs: "A program seeing an unexpected major
1766 # revision number should stop reading the MO file entirely"
1767 if version not in (0, 1):
1768 raise OSError('Invalid mo file, unexpected major revision number')
1769 self.instance.version = version
1770 # original strings and translation strings hash table offset
1771 msgids_hash_offset, msgstrs_hash_offset = self._readbinary(ii, 8)
1772 # move to msgid hash table and read length and offset of msgids
1773 self.fhandle.seek(msgids_hash_offset)
1774 msgids_index = []
1775 for i in range(numofstrings):
1776 msgids_index.append(self._readbinary(ii, 8))
1777 # move to msgstr hash table and read length and offset of msgstrs
1778 self.fhandle.seek(msgstrs_hash_offset)
1779 msgstrs_index = []
1780 for i in range(numofstrings):
1781 msgstrs_index.append(self._readbinary(ii, 8))
1782 # build entries
1783 encoding = self.instance.encoding
1784 for i in range(numofstrings):
1785 self.fhandle.seek(msgids_index[i][1])
1786 msgid = self.fhandle.read(msgids_index[i][0])
1787
1788 self.fhandle.seek(msgstrs_index[i][1])
1789 msgstr = self.fhandle.read(msgstrs_index[i][0])
1790 if i == 0 and not msgid: # metadata
1791 raw_metadata, metadata = msgstr.split(b('\n')), {}
1792 for line in raw_metadata:
1793 tokens = line.split(b(':'), 1)
1794 if tokens[0] != b(''):
1795 try:
1796 k = tokens[0].decode(encoding)
1797 v = tokens[1].decode(encoding)
1798 metadata[k] = v.strip()
1799 except IndexError:
1800 metadata[k] = u('')
1801 self.instance.metadata = metadata
1802 continue
1803 # test if we have a plural entry
1804 msgid_tokens = msgid.split(b('\0'))
1805 if len(msgid_tokens) > 1:
1806 entry = self._build_entry(
1807 msgid=msgid_tokens[0],
1808 msgid_plural=msgid_tokens[1],
1809 msgstr_plural={
1810 k: v for k, v in enumerate(msgstr.split(b('\0')))
1811 },
1812 )
1813 else:
1814 entry = self._build_entry(msgid=msgid, msgstr=msgstr)
1815 self.instance.append(entry)
1816 # close opened file
1817 self.fhandle.close()
1818 return self.instance
1819
1820 def _build_entry(
1821 self, msgid, msgstr=None, msgid_plural=None, msgstr_plural=None
1822 ):
1823 msgctxt_msgid = msgid.split(b('\x04'))
1824 encoding = self.instance.encoding
1825 if len(msgctxt_msgid) > 1:
1826 kwargs = {
1827 'msgctxt': msgctxt_msgid[0].decode(encoding),
1828 'msgid': msgctxt_msgid[1].decode(encoding),
1829 }
1830 else:
1831 kwargs = {'msgid': msgid.decode(encoding)}
1832 if msgstr:
1833 kwargs['msgstr'] = msgstr.decode(encoding)
1834 if msgid_plural:
1835 kwargs['msgid_plural'] = msgid_plural.decode(encoding)
1836 if msgstr_plural:
1837 for k in msgstr_plural:
1838 msgstr_plural[k] = msgstr_plural[k].decode(encoding)
1839 kwargs['msgstr_plural'] = msgstr_plural
1840 return MOEntry(**kwargs)
1841
1842 def _readbinary(self, fmt, numbytes):
1843 """
1844 Private method that unpack n bytes of data using format <fmt>.
1845 It returns a tuple or a mixed value if the tuple length is 1.
1846 """
1847 bytes = self.fhandle.read(numbytes)
1848 tup = struct.unpack(fmt, bytes)
1849 if len(tup) == 1:
1850 return tup[0]
1851 return tup
1852
1853
1854 # }}}
1855 # class TextWrapper {{{
1856
1857
1858 class TextWrapper(textwrap.TextWrapper):
1859 """
1860 Subclass of textwrap.TextWrapper that backport the
1861 drop_whitespace option.
1862 """
1863
1864 def __init__(self, *args, **kwargs):
1865 drop_whitespace = kwargs.pop('drop_whitespace', True)
1866 textwrap.TextWrapper.__init__(self, *args, **kwargs)
1867 self.drop_whitespace = drop_whitespace
1868
1869 def _wrap_chunks(self, chunks):
1870 """_wrap_chunks(chunks : [string]) -> [string]
1871
1872 Wrap a sequence of text chunks and return a list of lines of
1873 length 'self.width' or less. (If 'break_long_words' is false,
1874 some lines may be longer than this.) Chunks correspond roughly
1875 to words and the whitespace between them: each chunk is
1876 indivisible (modulo 'break_long_words'), but a line break can
1877 come between any two chunks. Chunks should not have internal
1878 whitespace; ie. a chunk is either all whitespace or a "word".
1879 Whitespace chunks will be removed from the beginning and end of
1880 lines, but apart from that whitespace is preserved.
1881 """
1882 lines = []
1883 if self.width <= 0:
1884 raise ValueError("invalid width %r (must be > 0)" % self.width)
1885
1886 # Arrange in reverse order so items can be efficiently popped
1887 # from a stack of chucks.
1888 chunks.reverse()
1889
1890 while chunks:
1891 # Start the list of chunks that will make up the current line.
1892 # cur_len is just the length of all the chunks in cur_line.
1893 cur_line = []
1894 cur_len = 0
1895
1896 # Figure out which static string will prefix this line.
1897 if lines:
1898 indent = self.subsequent_indent
1899 else:
1900 indent = self.initial_indent
1901
1902 # Maximum width for this line.
1903 width = self.width - len(indent)
1904
1905 # First chunk on line is whitespace -- drop it, unless this
1906 # is the very beginning of the text (ie. no lines started yet).
1907 if self.drop_whitespace and chunks[-1].strip() == '' and lines:
1908 del chunks[-1]
1909
1910 while chunks:
1911 l = len(chunks[-1])
1912
1913 # Can at least squeeze this chunk onto the current line.
1914 if cur_len + l <= width:
1915 cur_line.append(chunks.pop())
1916 cur_len += l
1917
1918 # Nope, this line is full.
1919 else:
1920 break
1921
1922 # The current line is full, and the next chunk is too big to
1923 # fit on *any* line (not just this one).
1924 if chunks and len(chunks[-1]) > width:
1925 self._handle_long_word(chunks, cur_line, cur_len, width)
1926
1927 # If the last chunk on this line is all whitespace, drop it.
1928 if self.drop_whitespace and cur_line and not cur_line[-1].strip():
1929 del cur_line[-1]
1930
1931 # Convert current line back to a string and store it in list
1932 # of all lines (return value).
1933 if cur_line:
1934 lines.append(indent + ''.join(cur_line))
1935
1936 return lines
1937
1938
1939 # }}}
1940 # function wrap() {{{
1941
1942
1943 def wrap(text, width=70, **kwargs):
1944 """
1945 Wrap a single paragraph of text, returning a list of wrapped lines.
1946 """
1947 if sys.version_info < (2, 6):
1948 return TextWrapper(width=width, **kwargs).wrap(text)
1949 return textwrap.wrap(text, width=width, **kwargs)
1950
1951
1952 # }}}