Debian Codegraph @

third_party/python/polib/polib.py

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