<commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# License: MIT (see LICENSE file provided)
# vim600: fdm=marker tabstop=4 shiftwidth=4 expandtab ai

# Description {{{
"""
**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__    = '<NAME> <<EMAIL>>'
__version__   = '0.3.1'


# dependencies {{{
try:
    import struct
    import textwrap
    import warnings
except ImportError, exc:
    raise ImportError('polib requires python 2.3 or later with the standard' \
        ' modules "struct", "textwrap" and "warnings" (details: %s)' % exc)
# }}}

__all__ = ['pofile', 'POFile', 'POEntry', 'mofile', 'MOFile', 'MOEntry',
           'detect_encoding', 'quote', 'unquote']

# shortcuts for performance improvement {{{
# yes, yes, this is quite ugly but *very* efficient
_dictget    = dict.get
_listappend = list.append
_listpop    = list.pop
_strjoin    = str.join
_strsplit   = str.split
_strstrip   = str.strip
_strreplace = str.replace
_textwrap   = textwrap.wrap
# }}}

default_encoding = 'utf-8'

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

    **Example**:

    >>> import polib
    >>> po = polib.pofile('tests/test_utf8.po')
    >>> po #doctest: +ELLIPSIS
    <POFile instance at ...>
    >>> import os, tempfile
    >>> 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):
    ...             if old.msgid != new.msgid:
    ...                 old.msgid
    ...                 new.msgid
    ...             if old.msgstr != new.msgstr:
    ...                 old.msgid
    ...                 new.msgid
    ...     finally:
    ...         os.unlink(tmpf)
    """
    # pofile {{{
    if _dictget(kwargs, 'autodetect_encoding', True) == True:
        enc = detect_encoding(fpath)
    else:
        enc = _dictget(kwargs, 'encoding', default_encoding)
    parser = _POFileParser(fpath)
    instance = parser.parse()
    instance.wrapwidth = _dictget(kwargs, 'wrapwidth', 78)
    instance.encoding  = enc
    return instance
    # }}}


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

    **Example**:

    >>> import polib
    >>> mo = polib.mofile('tests/test_utf8.mo')
    >>> 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)
    """
    # mofile {{{
    if _dictget(kwargs, 'autodetect_encoding', True) == True:
        enc = detect_encoding(fpath)
    else:
        enc = _dictget(kwargs, 'encoding', default_encoding)
    parser = _MOFileParser(fpath)
    instance = parser.parse()
    instance.wrapwidth = _dictget(kwargs, 'wrapwidth', 78)
    instance.encoding = enc
    return instance
    # }}}


def detect_encoding(fpath):
    """
    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')
    UTF-8
    >>> print detect_encoding('tests/test_iso-8859-15.po')
    ISO_8859-15
    >>> print detect_encoding('tests/test_iso-8859-15.mo')
    ISO_8859-15
    """
    # detect_encoding {{{
    import re
    rx = re.compile(r'"?Content-Type:.+? charset=([\w_\-:\.]+)')
    f = open(fpath)
    for l in f:
        match = rx.search(l)
        if match:
            f.close()
            return _strstrip(match.group(1))
    f.close()
    return default_encoding
    # }}}


def quote(st):
    """
    Quote and return the given string *st*.

    **Examples**:

    >>> quote('\\t and \\n and \\r and " and \\\\')
    '\\\\t and \\\\n and \\\\r and \\\\" and \\\\\\\\'
    """
    # quote {{{
    st = _strreplace(st, '\\', r'\\')
    st = _strreplace(st, '\t', r'\t')
    st = _strreplace(st, '\r', r'\r')
    st = _strreplace(st, '\n', r'\n')
    st = _strreplace(st, '\"', r'\"')
    return st
    # }}}


def unquote(st):
    """
    Unquote and return the given string *st*.

    **Examples**:

    >>> unquote('\\\\t and \\\\n and \\\\r and \\\\" and \\\\\\\\')
    '\\t and \\n and \\r and " and \\\\'
    """
    # unquote {{{
    st = _strreplace(st, r'\"', '"')
    st = _strreplace(st, r'\n', '\n')
    st = _strreplace(st, r'\r', '\r')
    st = _strreplace(st, r'\t', '\t')
    st = _strreplace(st, r'\\', '\\')
    return st
    # }}}


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


    def __init__(self, fpath=None, wrapwidth=78, encoding=default_encoding):
        """
        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).
        """
        list.__init__(self)
        # the opened file handle
        self.fpath = fpath
        # the width at which lines should be wrapped
        self.wrapwidth = wrapwidth
        # the file encoding
        self.encoding = encoding
        # 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:
            _listappend(ret, entry.__str__(self.wrapwidth))
        for entry in self.obsolete_entries():
            _listappend(ret, entry.__str__(self.wrapwidth))
        return _strjoin('\n', ret)

    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"""
        e = POEntry(msgid='')
        mdata = self.ordered_metadata()
        if mdata:
            strs = []
            for name, value in mdata:
                # Strip whitespace off each line in a multi-line entry
                value = _strjoin('\n', [_strstrip(v)
                                        for v in _strsplit(value, '\n')])
                _listappend(strs, '%s: %s' % (name, value))
            e.msgstr = _strjoin('\n', strs) + '\n'
        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
        mode = 'w'
        if repr_method == 'to_binary':
            mode += 'b'
        fhandle = open(fpath, mode)
        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
        'Jueves'
        >>> entry = po.find('Some unexistant msgid')
        >>> entry is None
        True
        >>> entry = po.find('Jueves', 'msgstr')
        >>> entry.msgid
        'Thursday'
        """
        try:
            return [e for e in self if getattr(e, by) == st][0]
        except IndexError:
            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)
                _listappend(ordered_data, (data, value))
            except KeyError:
                pass
        # the rest of the metadata won't be ordered there are no specs for this
        keys = metadata.keys()
        keys.sort()
        for data in keys:
            value = metadata[data]
            _listappend(ordered_data, (data, value))
        return ordered_data

    def to_binary(self):
        """Return the mofile binary representation."""
        import struct
        import array
        output = ''
        offsets = []
        ids = strs = ''
        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
        entries.sort(cmp)
        # add metadata entry
        mentry = self.metadata_as_entry()
        mentry.msgstr = _strreplace(mentry.msgstr, '\\n', '').lstrip() + '\n'
        entries = [mentry] + entries
        entries_len = len(entries)
        for e in entries:
            # For each string, we need size and file offset.  Each string is
            # NUL terminated; the NUL does not count into the size.
            msgid = e._decode(e.msgid)
            msgstr = e._decode(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
    # }}}


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="I need my dirty cheese",
    ...     msgstr="Je veux mon sale fromage"
    ... )
    >>> entry2.occurrences = [('testfile', 15),('another_file', 5)]
    >>> entry2.comment = "Another useful comment"
    >>> entry3 = POEntry(
    ...     msgid='Some entry with quotes " \\"',
    ...     msgstr=u'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 "I need my dirty cheese"
    msgstr "Je veux mon sale fromage"
    <BLANKLINE>
    #. Test string quoting
    msgid "Some entry with quotes \\" \\""
    msgstr "Un message unicode avec des quotes \\" \\""
    <BLANKLINE>
    '''
    # class POFile {{{

    def __str__(self):
        """Return the string representation of the po file"""
        ret, headers = '', _strsplit(self.header, '\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
        """
        total = len([e for e in self if not e.obsolete])
        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() and not e.obsolete]

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

        **Example**:<commit_msg>fix for #8:  If a .po file has no entries  you would get a divide by 0 entry.<commit_after>#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# License: MIT (see LICENSE file provided)
# vim600: fdm=marker tabstop=4 shiftwidth=4 expandtab ai

# Description {{{
"""
**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__    = '<NAME> <<EMAIL>>'
__version__   = '0.3.1'


# dependencies {{{
try:
    import struct
    import textwrap
    import warnings
except ImportError, exc:
    raise ImportError('polib requires python 2.3 or later with the standard' \
        ' modules "struct", "textwrap" and "warnings" (details: %s)' % exc)
# }}}

__all__ = ['pofile', 'POFile', 'POEntry', 'mofile', 'MOFile', 'MOEntry',
           'detect_encoding', 'quote', 'unquote']

# shortcuts for performance improvement {{{
# yes, yes, this is quite ugly but *very* efficient
_dictget    = dict.get
_listappend = list.append
_listpop    = list.pop
_strjoin    = str.join
_strsplit   = str.split
_strstrip   = str.strip
_strreplace = str.replace
_textwrap   = textwrap.wrap
# }}}

default_encoding = 'utf-8'

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

    **Example**:

    >>> import polib
    >>> po = polib.pofile('tests/test_utf8.po')
    >>> po #doctest: +ELLIPSIS
    <POFile instance at ...>
    >>> import os, tempfile
    >>> 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):
    ...             if old.msgid != new.msgid:
    ...                 old.msgid
    ...                 new.msgid
    ...             if old.msgstr != new.msgstr:
    ...                 old.msgid
    ...                 new.msgid
    ...     finally:
    ...         os.unlink(tmpf)
    """
    # pofile {{{
    if _dictget(kwargs, 'autodetect_encoding', True) == True:
        enc = detect_encoding(fpath)
    else:
        enc = _dictget(kwargs, 'encoding', default_encoding)
    parser = _POFileParser(fpath)
    instance = parser.parse()
    instance.wrapwidth = _dictget(kwargs, 'wrapwidth', 78)
    instance.encoding  = enc
    return instance
    # }}}


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

    **Example**:

    >>> import polib
    >>> mo = polib.mofile('tests/test_utf8.mo')
    >>> 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)
    """
    # mofile {{{
    if _dictget(kwargs, 'autodetect_encoding', True) == True:
        enc = detect_encoding(fpath)
    else:
        enc = _dictget(kwargs, 'encoding', default_encoding)
    parser = _MOFileParser(fpath)
    instance = parser.parse()
    instance.wrapwidth = _dictget(kwargs, 'wrapwidth', 78)
    instance.encoding = enc
    return instance
    # }}}


def detect_encoding(fpath):
    """
    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')
    UTF-8
    >>> print detect_encoding('tests/test_iso-8859-15.po')
    ISO_8859-15
    >>> print detect_encoding('tests/test_iso-8859-15.mo')
    ISO_8859-15
    """
    # detect_encoding {{{
    import re
    rx = re.compile(r'"?Content-Type:.+? charset=([\w_\-:\.]+)')
    f = open(fpath)
    for l in f:
        match = rx.search(l)
        if match:
            f.close()
            return _strstrip(match.group(1))
    f.close()
    return default_encoding
    # }}}


def quote(st):
    """
    Quote and return the given string *st*.

    **Examples**:

    >>> quote('\\t and \\n and \\r and " and \\\\')
    '\\\\t and \\\\n and \\\\r and \\\\" and \\\\\\\\'
    """
    # quote {{{
    st = _strreplace(st, '\\', r'\\')
    st = _strreplace(st, '\t', r'\t')
    st = _strreplace(st, '\r', r'\r')
    st = _strreplace(st, '\n', r'\n')
    st = _strreplace(st, '\"', r'\"')
    return st
    # }}}


def unquote(st):
    """
    Unquote and return the given string *st*.

    **Examples**:

    >>> unquote('\\\\t and \\\\n and \\\\r and \\\\" and \\\\\\\\')
    '\\t and \\n and \\r and " and \\\\'
    """
    # unquote {{{
    st = _strreplace(st, r'\"', '"')
    st = _strreplace(st, r'\n', '\n')
    st = _strreplace(st, r'\r', '\r')
    st = _strreplace(st, r'\t', '\t')
    st = _strreplace(st, r'\\', '\\')
    return st
    # }}}


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


    def __init__(self, fpath=None, wrapwidth=78, encoding=default_encoding):
        """
        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).
        """
        list.__init__(self)
        # the opened file handle
        self.fpath = fpath
        # the width at which lines should be wrapped
        self.wrapwidth = wrapwidth
        # the file encoding
        self.encoding = encoding
        # 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:
            _listappend(ret, entry.__str__(self.wrapwidth))
        for entry in self.obsolete_entries():
            _listappend(ret, entry.__str__(self.wrapwidth))
        return _strjoin('\n', ret)

    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"""
        e = POEntry(msgid='')
        mdata = self.ordered_metadata()
        if mdata:
            strs = []
            for name, value in mdata:
                # Strip whitespace off each line in a multi-line entry
                value = _strjoin('\n', [_strstrip(v)
                                        for v in _strsplit(value, '\n')])
                _listappend(strs, '%s: %s' % (name, value))
            e.msgstr = _strjoin('\n', strs) + '\n'
        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
        mode = 'w'
        if repr_method == 'to_binary':
            mode += 'b'
        fhandle = open(fpath, mode)
        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
        'Jueves'
        >>> entry = po.find('Some unexistant msgid')
        >>> entry is None
        True
        >>> entry = po.find('Jueves', 'msgstr')
        >>> entry.msgid
        'Thursday'
        """
        try:
            return [e for e in self if getattr(e, by) == st][0]
        except IndexError:
            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)
                _listappend(ordered_data, (data, value))
            except KeyError:
                pass
        # the rest of the metadata won't be ordered there are no specs for this
        keys = metadata.keys()
        keys.sort()
        for data in keys:
            value = metadata[data]
            _listappend(ordered_data, (data, value))
        return ordered_data

    def to_binary(self):
        """Return the mofile binary representation."""
        import struct
        import array
        output = ''
        offsets = []
        ids = strs = ''
        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
        entries.sort(cmp)
        # add metadata entry
        mentry = self.metadata_as_entry()
        mentry.msgstr = _strreplace(mentry.msgstr, '\\n', '').lstrip() + '\n'
        entries = [mentry] + entries
        entries_len = len(entries)
        for e in entries:
            # For each string, we need size and file offset.  Each string is
            # NUL terminated; the NUL does not count into the size.
            msgid = e._decode(e.msgid)
            msgstr = e._decode(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
    # }}}


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="I need my dirty cheese",
    ...     msgstr="Je veux mon sale fromage"
    ... )
    >>> entry2.occurrences = [('testfile', 15),('another_file', 5)]
    >>> entry2.comment = "Another useful comment"
    >>> entry3 = POEntry(
    ...     msgid='Some entry with quotes " \\"',
    ...     msgstr=u'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 "I need my dirty cheese"
    msgstr "Je veux mon sale fromage"
    <BLANKLINE>
    #. Test string quoting
    msgid "Some entry with quotes \\" \\""
    msgstr "Un message unicode avec des quotes \\" \\""
    <BLANKLINE>
    '''
    # class POFile {{{

    def __str__(self):
        """Return the string representation of the po file"""
        ret, headers = '', _strsplit(self.header, '\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
        """
        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() and not e.obsolete]

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

        **Example**:
{'fraction_non_alphanumeric': 0.1311583033624479, 'fraction_numerical': 0.008506022720785522, 'mean_word_length': 1.942633966067529, 'pattern_counts': {'":': 0, '<': 25, '<?xml version=': 0, '>': 361, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 14, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6463756', 'n_tokens_mistral': 10805, 'n_tokens_neox': 10325, 'n_words': 3199}