Skip to content
Snippets Groups Projects
polib.py 57.8 KiB
Newer Older
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# License: MIT (see LICENSE file provided)
# vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4:

"""
**polib** allows you to manipulate, create, modify gettext files (pot, po
and mo files).  You can load existing files, iterate through it's entries,
add, modify entries, comments or metadata, etc... or create new po files
from scratch.

**polib** provides a simple and pythonic API, exporting only three
convenience functions (*pofile*, *mofile* and *detect_encoding*), and the
four core classes, *POFile*, *MOFile*, *POEntry* and *MOEntry* for creating
new files/entries.

**Basic example**:

>>> import polib
>>> # load an existing po file
>>> po = polib.pofile('tests/test_utf8.po')
>>> for entry in po:
...     # do something with entry...
...     pass
>>> # add an entry
>>> entry = polib.POEntry(msgid='Welcome', msgstr='Bienvenue')
>>> entry.occurrences = [('welcome.py', '12'), ('anotherfile.py', '34')]
>>> po.append(entry)
>>> # to save our modified po file:
>>> # po.save()
>>> # or you may want to compile the po file
>>> # po.save_as_mofile('tests/test_utf8.mo')
"""

__author__    = 'David JEAN LOUIS <izimobil@gmail.com>'
__version__   = '0.5.2'
__all__       = ['pofile', 'POFile', 'POEntry', 'mofile', 'MOFile', 'MOEntry',
                 'detect_encoding', 'escape', 'unescape', 'detect_encoding',]

import codecs
import struct
import textwrap
import types
import re

default_encoding = 'utf-8'

# function pofile() {{{

def pofile(fpath, **kwargs):
    """
    Convenience function that parse the po/pot file *fpath* and return
    a POFile instance.

    **Keyword arguments**:
      - *fpath*: string, full or relative path to the po/pot file to parse
      - *wrapwidth*: integer, the wrap width, only useful when -w option was
        passed to xgettext (optional, default to 78)
      - *autodetect_encoding*: boolean, if set to False the function will
        not try to detect the po file encoding (optional, default to True)
      - *encoding*: string, an encoding, only relevant if autodetect_encoding
        is set to False
      - *check_for_duplicates*: whether to check for duplicate entries when
        adding entries to the file, default: False (optional)

    **Example**:

    >>> import polib
    >>> po = polib.pofile('tests/test_weird_occurrences.po',
    ...     check_for_duplicates=True)
    >>> po #doctest: +ELLIPSIS
    <POFile instance at ...>
    >>> import os, tempfile
    >>> all_attrs = ('msgctxt', 'msgid', 'msgstr', 'msgid_plural', 
    ...              'msgstr_plural', 'obsolete', 'comment', 'tcomment', 
    ...              'occurrences', 'flags', 'previous_msgctxt', 
    ...              'previous_msgid', 'previous_msgid_plural')
    >>> for fname in ['test_iso-8859-15.po', 'test_utf8.po']:
    ...     orig_po = polib.pofile('tests/'+fname)
    ...     tmpf = tempfile.NamedTemporaryFile().name
    ...     orig_po.save(tmpf)
    ...     try:
    ...         new_po = polib.pofile(tmpf)
    ...         for old, new in zip(orig_po, new_po):
    ...             for attr in all_attrs:
    ...                 if getattr(old, attr) != getattr(new, attr):
    ...                     getattr(old, attr)
    ...                     getattr(new, attr)
    ...     finally:
    ...         os.unlink(tmpf)
    >>> po_file = polib.pofile('tests/test_save_as_mofile.po')
    >>> tmpf = tempfile.NamedTemporaryFile().name
    >>> po_file.save_as_mofile(tmpf)
    >>> try:
    ...     mo_file = polib.mofile(tmpf)
    ...     for old, new in zip(po_file, mo_file):
    ...         if po_file._encode(old.msgid) != mo_file._encode(new.msgid):
    ...             'OLD: ', po_file._encode(old.msgid)
    ...             'NEW: ', mo_file._encode(new.msgid)
    ...         if po_file._encode(old.msgstr) != mo_file._encode(new.msgstr):
    ...             'OLD: ', po_file._encode(old.msgstr)
    ...             'NEW: ', mo_file._encode(new.msgstr)
    ...             print new.msgstr
    ... finally:
    ...     os.unlink(tmpf)
    """
    if kwargs.get('autodetect_encoding', True) == True:
        enc = detect_encoding(fpath)
    else:
        enc = kwargs.get('encoding', default_encoding)
    check_for_duplicates = kwargs.get('check_for_duplicates', False)
    parser = _POFileParser(
        fpath,
        encoding=enc,
        check_for_duplicates=kwargs.get('check_for_duplicates', False)
    )
    instance = parser.parse()
    instance.wrapwidth = kwargs.get('wrapwidth', 78)
    return instance

# }}}
# function mofile() {{{

def mofile(fpath, **kwargs):
    """
    Convenience function that parse the mo file *fpath* and return
    a MOFile instance.

    **Keyword arguments**:
      - *fpath*: string, full or relative path to the mo file to parse
      - *wrapwidth*: integer, the wrap width, only useful when -w option was
        passed to xgettext to generate the po file that was used to format
        the mo file (optional, default to 78)
      - *autodetect_encoding*: boolean, if set to False the function will
        not try to detect the po file encoding (optional, default to True)
      - *encoding*: string, an encoding, only relevant if autodetect_encoding
        is set to False
      - *check_for_duplicates*: whether to check for duplicate entries when
        adding entries to the file, default: False (optional)

    **Example**:

    >>> import polib
    >>> mo = polib.mofile('tests/test_utf8.mo', check_for_duplicates=True)
    >>> mo #doctest: +ELLIPSIS
    <MOFile instance at ...>
    >>> import os, tempfile
    >>> for fname in ['test_iso-8859-15.mo', 'test_utf8.mo']:
    ...     orig_mo = polib.mofile('tests/'+fname)
    ...     tmpf = tempfile.NamedTemporaryFile().name
    ...     orig_mo.save(tmpf)
    ...     try:
    ...         new_mo = polib.mofile(tmpf)
    ...         for old, new in zip(orig_mo, new_mo):
    ...             if old.msgid != new.msgid:
    ...                 old.msgstr
    ...                 new.msgstr
    ...     finally:
    ...         os.unlink(tmpf)
    """
    if kwargs.get('autodetect_encoding', True) == True:
        enc = detect_encoding(fpath, True)
    else:
        enc = kwargs.get('encoding', default_encoding)
    parser = _MOFileParser(
        fpath,
        encoding=enc,
        check_for_duplicates=kwargs.get('check_for_duplicates', False)
    )
    instance = parser.parse()
    instance.wrapwidth = kwargs.get('wrapwidth', 78)
    return instance

# }}}
# function detect_encoding() {{{

def detect_encoding(fpath, binary_mode=False):
    """
    Try to detect the encoding used by the file *fpath*. The function will
    return polib default *encoding* if it's unable to detect it.

    **Keyword argument**:
      - *fpath*: string, full or relative path to the mo file to parse.

    **Examples**:

    >>> print(detect_encoding('tests/test_noencoding.po'))
    utf-8
    >>> print(detect_encoding('tests/test_utf8.po'))
    UTF-8
    >>> print(detect_encoding('tests/test_utf8.mo', True))
    UTF-8
    >>> print(detect_encoding('tests/test_iso-8859-15.po'))
    ISO_8859-15
    >>> print(detect_encoding('tests/test_iso-8859-15.mo', True))
    ISO_8859-15
    """
    import re
    rx = re.compile(r'"?Content-Type:.+? charset=([\w_\-:\.]+)')
    if binary_mode:
        mode = 'rb'
    else:
        mode = 'r'
    f = open(fpath, mode)
    for l in f.readlines():
        match = rx.search(l)
        if match:
            f.close()
            return match.group(1).strip()
    f.close()
    return default_encoding

# }}}
# function escape() {{{

def escape(st):
    """
    Escape special chars and return the given string *st*.

    **Examples**:

    >>> escape('\\t and \\n and \\r and " and \\\\')
    '\\\\t and \\\\n and \\\\r and \\\\" and \\\\\\\\'
    """
    return st.replace('\\', r'\\')\
             .replace('\t', r'\t')\
             .replace('\r', r'\r')\
             .replace('\n', r'\n')\
             .replace('\"', r'\"')

# }}}
# function unescape() {{{

def unescape(st):
    """
    Unescape special chars and return the given string *st*.

    **Examples**:

    >>> unescape('\\\\t and \\\\n and \\\\r and \\\\" and \\\\\\\\')
    '\\t and \\n and \\r and " and \\\\'
    >>> unescape(r'\\n')
    '\\n'
    >>> unescape(r'\\\\n')
    '\\\\n'
    >>> unescape(r'\\\\n\\n')
    '\\\\n\\n'
    def unescape_repl(m):
        m = m.group(1)
        if m == 'n':
            return '\n'
        if m == 't':
            return '\t'
        if m == 'r':
            return '\r'
        if m == '\\':
            return '\\'
        return m # handles escaped double quote
    return re.sub(r'\\(\\|n|t|r|")', unescape_repl, st)
262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000

# }}}
# class _BaseFile {{{

class _BaseFile(list):
    """
    Common parent class for POFile and MOFile classes.
    This class must **not** be instanciated directly.
    """

    def __init__(self, *args, **kwargs):
        """
        Constructor.

        **Keyword arguments**:
          - *fpath*: string, path to po or mo file
          - *wrapwidth*: integer, the wrap width, only useful when -w option
            was passed to xgettext to generate the po file that was used to
            format the mo file, default to 78 (optional),
          - *encoding*: string, the encoding to use, defaults to
            "default_encoding" global variable (optional),
          - *check_for_duplicates*: whether to check for duplicate entries
            when adding entries to the file, default: False (optional).
        """
        list.__init__(self)
        # the opened file handle
        self.fpath = kwargs.get('fpath')
        # the width at which lines should be wrapped
        self.wrapwidth = kwargs.get('wrapwidth', 78)
        # the file encoding
        self.encoding = kwargs.get('encoding', default_encoding)
        # whether to check for duplicate entries or not
        self.check_for_duplicates = kwargs.get('check_for_duplicates', False)
        # header
        self.header = ''
        # both po and mo files have metadata
        self.metadata = {}
        self.metadata_is_fuzzy = 0

    def __str__(self):
        """
        String representation of the file.
        """
        ret = []
        entries = [self.metadata_as_entry()] + \
                  [e for e in self if not e.obsolete]
        for entry in entries:
            ret.append(entry.__str__(self.wrapwidth))
        for entry in self.obsolete_entries():
            ret.append(entry.__str__(self.wrapwidth))
        return '\n'.join(ret)

    def __contains__(self, entry):
        """
        Overriden method to implement the membership test (in and not in).
        The method considers that an entry is in the file if it finds an 
        entry that has the same msgid (case sensitive).

        **Keyword argument**:
          - *entry*: an instance of polib._BaseEntry

        **Tests**:
        >>> po = POFile()
        >>> e1 = POEntry(msgid='foobar', msgstr='spam')
        >>> e2 = POEntry(msgid='barfoo', msgstr='spam')
        >>> e3 = POEntry(msgid='foobar', msgstr='eggs')
        >>> e4 = POEntry(msgid='spameggs', msgstr='eggs')
        >>> po.append(e1)
        >>> po.append(e2)
        >>> e1 in po
        True
        >>> e2 not in po
        False
        >>> e3 in po
        True
        >>> e4 in po
        False
        """
        return self.find(entry.msgid, by='msgid') is not None

    def append(self, entry):
        """
        Overriden method to check for duplicates entries, if a user tries to
        add an entry that already exists, the method will raise a ValueError
        exception.

        **Keyword argument**:
          - *entry*: an instance of polib._BaseEntry

        **Tests**:
        >>> e1 = POEntry(msgid='foobar', msgstr='spam')
        >>> e2 = POEntry(msgid='foobar', msgstr='eggs')
        >>> po = POFile(check_for_duplicates=True)
        >>> po.append(e1)
        >>> try:
        ...     po.append(e2)
        ... except ValueError, e:
        ...     unicode(e)
        u'Entry "foobar" already exists'
        """
        if self.check_for_duplicates and entry in self:
            raise ValueError('Entry "%s" already exists' % entry.msgid)
        super(_BaseFile, self).append(entry)

    def insert(self, index, entry):
        """
        Overriden method to check for duplicates entries, if a user tries to
        insert an entry that already exists, the method will raise a ValueError
        exception.

        **Keyword arguments**:
          - *index*: index at which the entry should be inserted
          - *entry*: an instance of polib._BaseEntry

        **Tests**:
        >>> import polib
        >>> polib.check_for_duplicates = True
        >>> e1 = POEntry(msgid='foobar', msgstr='spam')
        >>> e2 = POEntry(msgid='barfoo', msgstr='eggs')
        >>> e3 = POEntry(msgid='foobar', msgstr='eggs')
        >>> po = POFile(check_for_duplicates=True)
        >>> po.insert(0, e1)
        >>> po.insert(1, e2)
        >>> try:
        ...     po.insert(0, e3)
        ... except ValueError, e:
        ...     unicode(e)
        u'Entry "foobar" already exists'
        """
        if self.check_for_duplicates and entry in self:
            raise ValueError('Entry "%s" already exists' % entry.msgid)
        super(_BaseFile, self).insert(index, entry)

    def __repr__(self):
        """Return the official string representation of the object."""
        return '<%s instance at %x>' % (self.__class__.__name__, id(self))

    def metadata_as_entry(self):
        """
        Return the metadata as an entry:

        >>> import polib
        >>> po = polib.pofile('tests/test_fuzzy_header.po')
        >>> unicode(po) == unicode(open('tests/test_fuzzy_header.po').read())
        True
        """
        e = POEntry(msgid='')
        mdata = self.ordered_metadata()
        if mdata:
            strs = []
            e._multiline_str['msgstr'] = ''
            for name, value in mdata:
                # Strip whitespace off each line in a multi-line entry
                strs.append('%s: %s' % (name, value))
            e.msgstr = '\n'.join(strs) + '\n'
            e._multiline_str['msgstr'] = '__POLIB__NL__'.join(
                    [s + '\n' for s in strs])
        if self.metadata_is_fuzzy:
            e.flags.append('fuzzy')
        return e

    def save(self, fpath=None, repr_method='__str__'):
        """
        Save the po file to file *fpath* if no file handle exists for
        the object. If there's already an open file and no fpath is
        provided, then the existing file is rewritten with the modified
        data.

        **Keyword arguments**:
          - *fpath*: string, full or relative path to the file.
          - *repr_method*: string, the method to use for output.
        """
        if self.fpath is None and fpath is None:
            raise IOError('You must provide a file path to save() method')
        contents = getattr(self, repr_method)()
        if fpath is None:
            fpath = self.fpath
        if repr_method == 'to_binary':
            fhandle = open(fpath, 'wb')
        else:
            fhandle = codecs.open(fpath, 'w', self.encoding)
            if type(contents) != types.UnicodeType:
                contents = contents.decode(self.encoding)
        fhandle.write(contents)
        fhandle.close()

    def find(self, st, by='msgid'):
        """
        Find entry which msgid (or property identified by the *by*
        attribute) matches the string *st*.

        **Keyword arguments**:
          - *st*: string, the string to search for
          - *by*: string, the comparison attribute

        **Examples**:

        >>> po = pofile('tests/test_utf8.po')
        >>> entry = po.find('Thursday')
        >>> entry.msgstr
        u'Jueves'
        >>> entry = po.find('Some unexistant msgid')
        >>> entry is None
        True
        >>> entry = po.find('Jueves', 'msgstr')
        >>> entry.msgid
        u'Thursday'
        """
        for e in self:
            if getattr(e, by) == st:
                return e
        return None

    def ordered_metadata(self):
        """
        Convenience method that return the metadata ordered. The return
        value is list of tuples (metadata name, metadata_value).
        """
        # copy the dict first
        metadata = self.metadata.copy()
        data_order = [
            'Project-Id-Version',
            'Report-Msgid-Bugs-To',
            'POT-Creation-Date',
            'PO-Revision-Date',
            'Last-Translator',
            'Language-Team',
            'MIME-Version',
            'Content-Type',
            'Content-Transfer-Encoding'
        ]
        ordered_data = []
        for data in data_order:
            try:
                value = metadata.pop(data)
                ordered_data.append((data, value))
            except KeyError:
                pass
        # the rest of the metadata won't be ordered there are no specs for this
        keys = metadata.keys()
        list(keys).sort()
        for data in keys:
            value = metadata[data]
            ordered_data.append((data, value))
        return ordered_data

    def to_binary(self):
        """
        Return the mofile binary representation.
        """
        import array
        import struct
        import types
        offsets = []
        entries = self.translated_entries()
        # the keys are sorted in the .mo file
        def cmp(_self, other):
            if _self.msgid > other.msgid:
                return 1
            elif _self.msgid < other.msgid:
                return -1
            else:
                return 0
        # add metadata entry
        entries.sort(cmp)
        mentry = self.metadata_as_entry()
        mentry.msgstr = mentry.msgstr.replace('\\n', '').lstrip()
        entries = [mentry] + entries
        entries_len = len(entries)
        ids, strs = '', ''
        for e in entries:
            # For each string, we need size and file offset.  Each string is
            # NUL terminated; the NUL does not count into the size.
            if e.msgid_plural:
                indexes = e.msgstr_plural.keys()
                indexes.sort()
                msgstr = []
                for index in indexes:
                    msgstr.append(e.msgstr_plural[index])
                msgid = self._encode(e.msgid + '\0' + e.msgid_plural)
                msgstr = self._encode('\0'.join(msgstr))
            else:
                msgid = self._encode(e.msgid)
                msgstr = self._encode(e.msgstr)
            offsets.append((len(ids), len(msgid), len(strs), len(msgstr)))
            ids  += msgid  + '\0'
            strs += msgstr + '\0'
        # The header is 7 32-bit unsigned integers.
        keystart = 7*4+16*entries_len
        # and the values start after the keys
        valuestart = keystart + len(ids)
        koffsets = []
        voffsets = []
        # The string table first has the list of keys, then the list of values.
        # Each entry has first the size of the string, then the file offset.
        for o1, l1, o2, l2 in offsets:
            koffsets += [l1, o1+keystart]
            voffsets += [l2, o2+valuestart]
        offsets = koffsets + voffsets
        output  = struct.pack("IIIIIII",
                             0x950412de,        # Magic number
                             0,                 # Version
                             entries_len,       # # of entries
                             7*4,               # start of key index
                             7*4+entries_len*8, # start of value index
                             0, 0)              # size and offset of hash table
        output += array.array("I", offsets).tostring()
        output += ids
        output += strs
        return output

    def _encode(self, mixed):
        """
        Encode the given argument with the file encoding if the type is unicode
        and return the encoded string.
        """
        if type(mixed) == types.UnicodeType:
            return mixed.encode(self.encoding)
        return mixed

# }}}
# class POFile {{{

class POFile(_BaseFile):
    '''
    Po (or Pot) file reader/writer.
    POFile objects inherit the list objects methods.

    **Example**:

    >>> po = POFile()
    >>> entry1 = POEntry(
    ...     msgid="Some english text",
    ...     msgstr="Un texte en anglais"
    ... )
    >>> entry1.occurrences = [('testfile', 12),('another_file', 1)]
    >>> entry1.comment = "Some useful comment"
    >>> entry2 = POEntry(
    ...     msgid="Peace in some languages",
    ...     msgstr="Pace سلام שלום Hasîtî 和平"
    ... )
    >>> entry2.occurrences = [('testfile', 15),('another_file', 5)]
    >>> entry2.comment = "Another useful comment"
    >>> entry3 = POEntry(
    ...     msgid='Some entry with quotes " \\"',
    ...     msgstr='Un message unicode avec des quotes " \\"'
    ... )
    >>> entry3.comment = "Test string quoting"
    >>> po.append(entry1)
    >>> po.append(entry2)
    >>> po.append(entry3)
    >>> po.header = "Some Header"
    >>> print(po)
    # Some Header
    msgid ""
    msgstr ""
    <BLANKLINE>
    #. Some useful comment
    #: testfile:12 another_file:1
    msgid "Some english text"
    msgstr "Un texte en anglais"
    <BLANKLINE>
    #. Another useful comment
    #: testfile:15 another_file:5
    msgid "Peace in some languages"
    msgstr "Pace سلام שלום Hasîtî 和平"
    <BLANKLINE>
    #. Test string quoting
    msgid "Some entry with quotes \\" \\""
    msgstr "Un message unicode avec des quotes \\" \\""
    <BLANKLINE>
    '''

    def __str__(self):
        """Return the string representation of the po file"""
        ret, headers = '', self.header.split('\n')
        for header in headers:
            if header[:1] in [',', ':']:
                ret += '#%s\n' % header
            else:
                ret += '# %s\n' % header
        return ret + _BaseFile.__str__(self)

    def save_as_mofile(self, fpath):
        """
        Save the binary representation of the file to *fpath*.

        **Keyword arguments**:
          - *fpath*: string, full or relative path to the file.
        """
        _BaseFile.save(self, fpath, 'to_binary')

    def percent_translated(self):
        """
        Convenience method that return the percentage of translated
        messages.

        **Example**:

        >>> import polib
        >>> po = polib.pofile('tests/test_pofile_helpers.po')
        >>> po.percent_translated()
        50
        >>> po = POFile()
        >>> po.percent_translated()
        100
        """
        total = len([e for e in self if not e.obsolete])
        if total == 0:
            return 100
        translated = len(self.translated_entries())
        return int((100.00 / float(total)) * translated)

    def translated_entries(self):
        """
        Convenience method that return a list of translated entries.

        **Example**:

        >>> import polib
        >>> po = polib.pofile('tests/test_pofile_helpers.po')
        >>> len(po.translated_entries())
        6
        """
        return [e for e in self if e.translated()]

    def untranslated_entries(self):
        """
        Convenience method that return a list of untranslated entries.

        **Example**:

        >>> import polib
        >>> po = polib.pofile('tests/test_pofile_helpers.po')
        >>> len(po.untranslated_entries())
        4
        """
        return [e for e in self if not e.translated() and not e.obsolete \
                and not 'fuzzy' in e.flags]

    def fuzzy_entries(self):
        """
        Convenience method that return the list of 'fuzzy' entries.

        **Example**:

        >>> import polib
        >>> po = polib.pofile('tests/test_pofile_helpers.po')
        >>> len(po.fuzzy_entries())
        2
        """
        return [e for e in self if 'fuzzy' in e.flags]

    def obsolete_entries(self):
        """
        Convenience method that return the list of obsolete entries.

        **Example**:

        >>> import polib
        >>> po = polib.pofile('tests/test_pofile_helpers.po')
        >>> len(po.obsolete_entries())
        4
        """
        return [e for e in self if e.obsolete]

    def merge(self, refpot):
        """
        XXX this could not work if encodings are different, needs thinking
        and general refactoring of how polib handles encoding...

        Convenience method that merge the current pofile with the pot file
        provided. It behaves exactly as the gettext msgmerge utility:

          - comments of this file will be preserved, but extracted comments
            and occurrences will be discarded
          - any translations or comments in the file will be discarded,
            however dot comments and file positions will be preserved

        **Keyword argument**:
          - *refpot*: object POFile, the reference catalog.

        **Example**:

        >>> import polib
        >>> refpot = polib.pofile('tests/test_merge.pot')
        >>> po = polib.pofile('tests/test_merge_before.po')
        >>> po.merge(refpot)
        >>> expected_po = polib.pofile('tests/test_merge_after.po')
        >>> unicode(po) == unicode(expected_po)
        True
        """
        for entry in refpot:
            e = self.find(entry.msgid)
            if e is None:
                e = POEntry()
                self.append(e)
            e.merge(entry)
        # ok, now we must "obsolete" entries that are not in the refpot
        # anymore
        for entry in self:
            if refpot.find(entry.msgid) is None:
                entry.obsolete = True

# }}}
# class MOFile {{{

class MOFile(_BaseFile):
    '''
    Mo file reader/writer.
    MOFile objects inherit the list objects methods.

    **Example**:

    >>> mo = MOFile()
    >>> entry1 = POEntry(
    ...     msgid="Some english text",
    ...     msgstr="Un texte en anglais"
    ... )
    >>> entry2 = POEntry(
    ...     msgid="I need my dirty cheese",
    ...     msgstr="Je veux mon sale fromage"
    ... )
    >>> entry3 = MOEntry(
    ...     msgid='Some entry with quotes " \\"',
    ...     msgstr='Un message unicode avec des quotes " \\"'
    ... )
    >>> mo.append(entry1)
    >>> mo.append(entry2)
    >>> mo.append(entry3)
    >>> print(mo)
    msgid ""
    msgstr ""
    <BLANKLINE>
    msgid "Some english text"
    msgstr "Un texte en anglais"
    <BLANKLINE>
    msgid "I need my dirty cheese"
    msgstr "Je veux mon sale fromage"
    <BLANKLINE>
    msgid "Some entry with quotes \\" \\""
    msgstr "Un message unicode avec des quotes \\" \\""
    <BLANKLINE>
    '''

    def __init__(self, *args, **kwargs):
        """
        MOFile constructor. Mo files have two other properties:
            - magic_number: the magic_number of the binary file,
            - version: the version of the mo spec.
        """
        _BaseFile.__init__(self, *args, **kwargs)
        self.magic_number = None
        self.version = 0

    def save_as_pofile(self, fpath):
        """
        Save the string representation of the file to *fpath*.

        **Keyword argument**:
          - *fpath*: string, full or relative path to the file.
        """
        _BaseFile.save(self, fpath)

    def save(self, fpath):
        """
        Save the binary representation of the file to *fpath*.

        **Keyword argument**:
          - *fpath*: string, full or relative path to the file.
        """
        _BaseFile.save(self, fpath, 'to_binary')

    def percent_translated(self):
        """
        Convenience method to keep the same interface with POFile instances.
        """
        return 100

    def translated_entries(self):
        """
        Convenience method to keep the same interface with POFile instances.
        """
        return self

    def untranslated_entries(self):
        """
        Convenience method to keep the same interface with POFile instances.
        """
        return []

    def fuzzy_entries(self):
        """
        Convenience method to keep the same interface with POFile instances.
        """
        return []

    def obsolete_entries(self):
        """
        Convenience method to keep the same interface with POFile instances.
        """
        return []

# }}}
# class _BaseEntry {{{

class _BaseEntry(object):
    """
    Base class for POEntry or MOEntry objects.
    This class must *not* be instanciated directly.
    """

    def __init__(self, *args, **kwargs):
        """Base Entry constructor."""
        self.msgid = kwargs.get('msgid', '')
        self.msgstr = kwargs.get('msgstr', '')
        self.msgid_plural = kwargs.get('msgid_plural', '')
        self.msgstr_plural = kwargs.get('msgstr_plural', {})
        self.obsolete = kwargs.get('obsolete', False)
        self.encoding = kwargs.get('encoding', default_encoding)
        self.msgctxt = kwargs.get('msgctxt', None)
        self._multiline_str = {}

    def __repr__(self):
        """Return the official string representation of the object."""
        return '<%s instance at %x>' % (self.__class__.__name__, id(self))

    def __str__(self, wrapwidth=78):
        """
        Common string representation of the POEntry and MOEntry
        objects.
        """
        if self.obsolete:
            delflag = '#~ '
        else:
            delflag = ''
        ret = []
        # write the msgctxt if any
        if self.msgctxt is not None:
            ret += self._str_field("msgctxt", delflag, "", self.msgctxt)
        # write the msgid
        ret += self._str_field("msgid", delflag, "", self.msgid)
        # write the msgid_plural if any
        if self.msgid_plural:
            ret += self._str_field("msgid_plural", delflag, "", self.msgid_plural)
        if self.msgstr_plural:
            # write the msgstr_plural if any
            msgstrs = self.msgstr_plural
            keys = list(msgstrs)
            keys.sort()
            for index in keys:
                msgstr = msgstrs[index]
                plural_index = '[%s]' % index
                ret += self._str_field("msgstr", delflag, plural_index, msgstr)
        else:
            # otherwise write the msgstr
            ret += self._str_field("msgstr", delflag, "", self.msgstr)
        ret.append('')
        return '\n'.join(ret)

    def _str_field(self, fieldname, delflag, plural_index, field):
        if (fieldname + plural_index) in self._multiline_str:
            field = self._multiline_str[fieldname + plural_index]
            lines = [''] + field.split('__POLIB__NL__')
        else:
            lines = field.splitlines(True)
            if len(lines) > 1:
                lines = ['']+lines # start with initial empty line
            else:
                lines = [field] # needed for the empty string case
        if fieldname.startswith('previous_'):
            # quick and dirty trick to get the real field name
            fieldname = fieldname[9:]

        ret = ['%s%s%s "%s"' % (delflag, fieldname, plural_index,
                                escape(lines.pop(0)))]
        for mstr in lines:
            ret.append('%s"%s"' % (delflag, escape(mstr)))
        return ret

# }}}
# class POEntry {{{

class POEntry(_BaseEntry):
    """
    Represents a po file entry.

    **Examples**:

    >>> entry = POEntry(msgid='Welcome', msgstr='Bienvenue')
    >>> entry.occurrences = [('welcome.py', 12), ('anotherfile.py', 34)]
    >>> print(entry)
    #: welcome.py:12 anotherfile.py:34
    msgid "Welcome"
    msgstr "Bienvenue"
    <BLANKLINE>
    >>> entry = POEntry()
    >>> entry.occurrences = [('src/some-very-long-filename-that-should-not-be-wrapped-even-if-it-is-larger-than-the-wrap-limit.c', 32), ('src/eggs.c', 45)]
    >>> entry.comment = 'A plural translation. This is a very very very long line please do not wrap, this is just for testing comment wrapping...'
    >>> entry.tcomment = 'A plural translation. This is a very very very long line please do not wrap, this is just for testing comment wrapping...'
    >>> entry.flags.append('c-format')
    >>> entry.previous_msgctxt = '@somecontext'
    >>> entry.previous_msgid = 'I had eggs but no spam !'
    >>> entry.previous_msgid_plural = 'I had eggs and %d spam !'
    >>> entry.msgctxt = '@somenewcontext'
    >>> entry.msgid = 'I have spam but no egg !'
    >>> entry.msgid_plural = 'I have spam and %d eggs !'
    >>> entry.msgstr_plural[0] = "J'ai du jambon mais aucun oeuf !"
    >>> entry.msgstr_plural[1] = "J'ai du jambon et %d oeufs !"
    >>> print(entry)
    #. A plural translation. This is a very very very long line please do not
    #. wrap, this is just for testing comment wrapping...
    # A plural translation. This is a very very very long line please do not wrap,
    # this is just for testing comment wrapping...
    #: src/some-very-long-filename-that-should-not-be-wrapped-even-if-it-is-larger-than-the-wrap-limit.c:32
    #: src/eggs.c:45
    #, c-format
    #| msgctxt "@somecontext"
    #| msgid "I had eggs but no spam !"
    #| msgid_plural "I had eggs and %d spam !"
    msgctxt "@somenewcontext"
    msgid "I have spam but no egg !"
    msgid_plural "I have spam and %d eggs !"
    msgstr[0] "J'ai du jambon mais aucun oeuf !"
    msgstr[1] "J'ai du jambon et %d oeufs !"
    <BLANKLINE>
    """

    def __init__(self, *args, **kwargs):
        """POEntry constructor."""
        _BaseEntry.__init__(self, *args, **kwargs)
        self.comment = kwargs.get('comment', '')
        self.tcomment = kwargs.get('tcomment', '')
        self.occurrences = kwargs.get('occurrences', [])
        self.flags = kwargs.get('flags', [])
        self.previous_msgctxt = kwargs.get('previous_msgctxt', None)
        self.previous_msgid = kwargs.get('previous_msgid', None)
        self.previous_msgid_plural = kwargs.get('previous_msgid_plural', None)