~dholbach/help-app/1426304

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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
import codecs
import copy
import glob
import os
import re
import shutil
import subprocess
import sys


def require(package):
    print('Missing prerequisites. Please run: '
          '"sudo apt install %s"' % package)
    sys.exit(1)

try:
    import polib
except ImportError:
    require('python3-polib')

from pelicanconf import PATH

# This defines how complete we expect translations to be before we
# generate HTML from them. Needs to be string.
TRANSLATION_COMPLETION_PERCENTAGE = '0'

BCP47_OVERRIDES = (
    ('zh_CN', 'zh-hans'),
    ('zh_TW', 'zh-hant'),
)


def find_bcp47_code(gettext_code):
    if gettext_code not in [c[0] for c in BCP47_OVERRIDES]:
        return gettext_code.lower().replace('_', '-')
    return [c[1] for c in BCP47_OVERRIDES
            if c[0] == gettext_code][0]


class PO4A(object):
    def __init__(self):
        self.default_args = [
            '-f', 'text',
            '-o', 'markdown',
            '-M', 'utf-8',
            ]
        if not shutil.which('po4a'):
            require('po4a')

    def run(self, po4a_command, additional_args, with_output=False):
        args = copy.copy(self.default_args)
        args += additional_args
        if with_output:
            ret = subprocess.Popen([po4a_command]+args, stdout=subprocess.PIPE)
        else:
            ret = subprocess.call([po4a_command]+args)
        return ret

    def gettextize(self, document_fns, pot_file):
        args = []
        for document_fn in document_fns:
            args += ['-m', document_fn]
        args += [
            '-p', pot_file,
            '-L', 'utf-8',
            ]
        ret = self.run('po4a-gettextize', args)
        return (not ret)

    def translate(self, doc, po_fn):
        args = [
            '-k', TRANSLATION_COMPLETION_PERCENTAGE,
            '-m', doc,
            '-p', po_fn,
            '-L', 'utf-8',
            ]
        return self.run('po4a-translate', args, with_output=True)


class POFile(object):
    def __init__(self, po_fn):
        self.po_fn = po_fn
        self.pofile = polib.pofile(po_fn)

    def merge(self, pot_file_ob):
        self.pofile.merge(pot_file_ob)

    def save(self):
        self.pofile.save(self.po_fn)

    def find_in_msgid(self, find_str, translated=True, fuzzy=True,
                      untranslated=True):
        entries = []
        if translated:
            entries += self.pofile.translated_entries()
        if fuzzy:
            entries += self.pofile.fuzzy_entries()
        if untranslated:
            entries += self.pofile.untranslated_entries()
        results = []
        for entry in entries:
            if find_str in entry.msgid:
                results += [entry]
        return results

    def replace_title_lines(self):
        results = {}
        for entry in self.find_in_msgid('Title: '):
            if entry.msgid.startswith('Title: '):
                if entry.linenum != 1:
                    print('Title line "%s" found, but at linenum "%s", '
                          'not 1.' % (entry.msgid, entry.linenum))
                    return False
                entry.msgid = entry.msgid.replace('Title: ', '')
                fn = entry.occurrences[0][0]
                results[fn] = entry.msgid
                if self.po_fn.endswith('.po'):
                    entry.msgstr = ''
        self.save()
        return True

    def rewrite_links(self, documents, bcp47):
        link_regex = r'\[.+?\]\(\{filename\}(.+?)\)'
        for entry in self.find_in_msgid('{filename}'):
            link_msgid = re.findall(link_regex, entry.msgid)[0]
            link_msgstr = list(re.findall(link_regex, entry.msgstr))
            translated_doc_fn = os.path.basename(
                documents.translated_doc_fn(link_msgid, bcp47))
            if not link_msgstr:
                entry.msgstr = entry.msgid
                link_msgstr = [link_msgid]
            entry.msgstr = entry.msgstr.replace(link_msgstr[0],
                                                translated_doc_fn)
        self.save()

    def find_translated_title_line(self, original_title):
        for entry in self.find_in_msgid(original_title):
            if entry.msgid == original_title:
                if entry.msgstr:
                    return entry.msgstr
                return entry.msgid


class PO(object):
    def __init__(self, po4a):
        self.translations_dir = os.path.abspath(os.path.join(PATH, '../po'))
        self.fake_lang_code = 'en_US'
        self.fake_po_fn = os.path.join(self.translations_dir,
                                       '%s.po' % self.fake_lang_code)
        self.pot_fn = os.path.join(self.translations_dir, 'help.pot')
        self.pot_file_ob = POFile(self.pot_fn)
        self.po4a = po4a
        self.langs = {}
        for po_fn in glob.glob(self.translations_dir+'/*.po'):
            self.add_language(po_fn)

    def add_language(self, po_fn):
        gettext_code = os.path.basename(po_fn).split('.po')[0]
        self.langs[po_fn] = {
            'bcp47': find_bcp47_code(gettext_code),
            'gettext_code': gettext_code,
            'pofile': None,
        }

    def _remove_fake_po_file(self):
        if os.path.exists(self.fake_po_fn):
            os.remove(self.fake_po_fn)

    def __del__(self):
        self._remove_fake_po_file()

    def load_pofile(self, po_fn):
        if not self.langs[po_fn]['pofile']:
            self.langs[po_fn]['pofile'] = POFile(po_fn)

    def generate_pot_file(self, documents):
        if not self.po4a.gettextize(documents.docs, self.pot_fn):
            return False
        if not self.pot_file_ob.replace_title_lines():
            return False
        for po_fn in self.langs:
            self.load_pofile(po_fn)
            self.langs[po_fn]['pofile'].merge(self.pot_file_ob.pofile)
            if not self.langs[po_fn]['pofile'].replace_title_lines():
                return False
        return True

    # we generate a fake translation for en-US which is going to be
    # the default
    def generate_fake_pofile(self):
        self._remove_fake_po_file()
        shutil.copy(self.pot_fn, self.fake_po_fn)
        self.add_language(self.fake_po_fn)

    def find_translated_title_line(self, original_title, po_fn):
        return self.langs[po_fn]['pofile'].find_translated_title_line(
            original_title)

    def rewrite_links(self, documents):
        for po_fn in self.langs:
            self.load_pofile(po_fn)
            self.langs[po_fn]['pofile'].rewrite_links(
                documents, self.langs[po_fn]['bcp47'])


class Documents(object):
    def __init__(self):
        self.docs = []
        for dirpath, dirnames, fns in os.walk(PATH):
            for fn in fns:
                fn = os.path.relpath(os.path.join(dirpath, fn),
                                     os.path.join(PATH, '..'))
                self.docs += [fn]

    def translated_doc_fn(self, fn, bcp47_code):
        match = [doc for doc in self.docs
                 if os.path.basename(doc) == os.path.basename(fn)]
        if not match:
            return None
        return '%s.%s.md' % (match[0].split('.md')[0],
                             bcp47_code)

    def _call_po4a_translate(self, doc, po_fn, po4a):
        res = po4a.translate(doc, po_fn)
        return codecs.decode(res.communicate()[0])

    def write_translated_markdown(self, po, po4a):
        for po_fn in po.langs:
            for doc_fn in self.docs:
                output = self._call_po4a_translate(doc_fn, po_fn, po4a)
                title_line = output.split('\n')[0].split('Title: ')[1]
                translated_title_line = po.find_translated_title_line(
                    title_line, po_fn)
                output = '\n'.join([line for line in output.split('\n')][1:])
                new_path = self.translated_doc_fn(doc_fn,
                                                  po.langs[po_fn]['bcp47'])
                text = "Title: %s\nDate:\n\n" % (translated_title_line)
                text += output
                if os.path.exists(new_path):
                    os.remove(new_path)
                if not os.path.exists(os.path.dirname(new_path)):
                    os.makedirs(os.path.dirname(new_path))
                with open(new_path, 'w', encoding='utf-8') as f:
                    f.write(text)


class Translations(object):
    def __init__(self):
        self._cleanup()
        self.documents = Documents()
        self.po4a = PO4A()
        self.po = PO(self.po4a)

    def _cleanup(self):
        r = subprocess.Popen(['bzr', 'ignored'], stdout=subprocess.PIPE)
        fns = [os.path.join(PATH, '../..', f.split(' ')[0])
               for f in codecs.decode(r.communicate()[0]).split('\n')
               if f.strip() != '']
        fns = [f for f in fns if os.path.exists(f)]
        for f in fns:
            try:
                shutil.rmtree(f)
            except NotADirectoryError:
                os.remove(f)

    def generate_pot_file(self):
        return self.po.generate_pot_file(self.documents)

    def generate_translations(self):
        self.po.generate_fake_pofile()
        self.po.rewrite_links(self.documents)
        self.documents.write_translated_markdown(self.po, self.po4a)