~chromium-team/chromium-browser/translations-pump

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
"""Common functions to all gettext file formats"""

 
from io import StringIO
import re
import logging

def gettext_file_sorting_function(item):
    r"""Used to sort .items of txln_info pairs so gettext output files are
    consistently ordered.

    >>> gettext_file_sorting_function(("s", {"langs":{"l":["1","2"]}, "refs":[{"grdfile":"f1"},{"grdfile":"f2"}]}))
    (('f1', 'f2'), 's')
    >>> gettext_file_sorting_function(("s", {"refs":[{"grdfile":"f1"},{"grdfile":"f2"}]}))
    (('f1', 'f2'), 's')
    >>> gettext_file_sorting_function(("s", {"langs":{"l":["1","2"]}, "refs":[]}))
    ((), 's')
    >>> gettext_file_sorting_function(("s", {"langs":{"l":["1","2"]},}))
    ((), 's')
    """
    return tuple([tuple(sorted(r["grdfile"] for r in item[1].get("refs", []))), item[0]])


def grd_msg_write_in_po(header, text, outfile):
    r"""Rewrite a message into several lines in a gettext file.  Outside,
    string literals are concatenated together. We cater to that by making each
    line into a "-delimited line with the newline encoded into the string.

    >>> f = StringIO(); grd_msg_write_in_po("asdf", "12<ph name=\"AB\" />3\n4<ph name=\"C\"/>56", f).getvalue()
    'asdf ""\n"12%{AB}3\\n"\n"4%{C}56"\n'
    """

    if "%{" in text:
        logging.warn("Text from GRD, %r, looks like it has percent-openbrace already, which would be confusing later.", text)

    text = re.sub(r'<ph\s+name="([^"]+)"\s*/>', r"%{\1}", text)
    outfile.write('{0} ""\n'.format(header))
    outfile.write('"' + '\\n"\n"'.join(line.replace("\\", "\\\\") for line in text.split("\n")) + '"\n')

    return outfile