~nskaggs/help-app/functional-test-template

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
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
import codecs
import glob
import os
import re
import shutil
from collections import OrderedDict

from translations.utils import (
    find_bcp47_code,
    full_path,
    Markdown,
    normalise_path,
    require,
    use_top_level_dir,
    verify_file_type,
)

from translations.po4a import PO4A

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

from pelicanconf import (
    DOCS_PATH,
    HIDE_FROM_POT,
    I18N_BUILD_DIR,
    META_TAGS,
    TRANSLATIONS_DIR,
)


class POFile(object):
    pofile = None

    def __init__(self, po_fn):
        self.po_fn = po_fn
        self.load()

    def load(self):
        self.pofile = polib.pofile(full_path(self.po_fn))

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

    def save(self):
        self.pofile.save(full_path(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 hide_attr_list_statements(self):
        entries = []
        for statement in HIDE_FROM_POT:
            entries.extend(self.find_in_msgid(statement))
        statements = r'|'.join(HIDE_FROM_POT)
        for entry in entries:
            matches = re.findall(r'(.*?)\s*?(%s)\s*?' % statements,
                                 entry.msgid)
            # [('How do I update my system?', '!!T')]
            if len(matches) == 1 and len(matches[0]) == 2:
                entry.msgid = matches[0][0]
                entry.comment = matches[0][1]
            if matches[0][1] in entry.msgstr:
                entry.msgstr = entry.msgstr.replace(' %s' % matches[0][1], '')
        self.save()

    def readd_attr_list_statements(self):
        entries = []
        for entry_group in [self.pofile.translated_entries(),
                            self.pofile.fuzzy_entries(),
                            self.pofile.untranslated_entries()]:
            for entry in entry_group:
                for statement in HIDE_FROM_POT:
                    if statement in entry.comment:
                        entries += [entry]
        for entry in entries:
            if not entry.msgid.endswith(entry.comment):
                entry.msgid += ' %s' % entry.comment
            if entry.msgstr and not entry.msgstr.endswith(entry.comment):
                entry.msgstr += ' %s' % entry.comment
            entry.comment = ''
        self.save()

    def safeguard_meta_tags(self):
        for tag in META_TAGS:
            for entry in self.find_in_msgid(tag):
                if entry.msgid == tag:
                    entry.msgstr = entry.msgid
        self.save()

    def find_title_lines(self):
        results = []
        for entry in self.find_in_msgid('Title: '):
            if entry.msgid.startswith('Title: '):
                where = entry.occurrences[0][0]
                first_line = codecs.open(full_path(where),
                                         encoding='utf-8').readline().strip()
                results += [(entry, first_line)]
        return results

    def replace_title_lines(self):
        for entry, first_line in self.find_title_lines():
            if entry.msgid.startswith(first_line):
                entry.msgid = first_line
            else:
                print('Title line "%s" found, but not on the first line '
                      'of "%s".' % (entry.msgid, entry.linenum))
                return False
            entry.msgid = entry.msgid.replace('Title: ', '')
            if self.po_fn.endswith('.po'):
                entry.msgstr = ''
        self.save()
        return True

    def find_link_in_markdown_message(self, entry):
        link_regex = r'\[.+?\]\(\{filename\}(.+?)\).*?'
        link_msgid = re.findall(link_regex, entry.msgid)[0]
        link_msgstr = list(re.findall(link_regex, entry.msgstr))
        return (link_msgid, link_msgstr)

    def rewrite_links(self, documents, bcp47):
        for entry in self.find_in_msgid('{filename}'):
            (link_msgid, link_msgstr) = \
                self.find_link_in_markdown_message(entry)
            if [doc for doc in documents.docs if doc.endswith(link_msgid)]:
                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 and entry.msgstr:
                return entry.msgstr
        return original_title


class PO(object):
    def __init__(self, po4a):
        self.fake_lang_code = 'en_US'
        self.fake_po_fn = normalise_path(
            os.path.join(TRANSLATIONS_DIR,
                         '%s.po' % self.fake_lang_code))
        self.pot_fn = normalise_path(os.path.join(TRANSLATIONS_DIR,
                                                  'help.pot'))
        self.pot_file_ob = POFile(self.pot_fn)
        self.po4a = po4a
        self.langs = {}
        for po_fn in glob.glob(TRANSLATIONS_DIR+'/*.po'):
            self.add_language(normalise_path(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 gettextize(self, documents):
        if not self.po4a.gettextize(documents.docs, self.pot_fn):
            return False
        self.pot_file_ob.load()
        return True

    def generate_pot_file(self, documents):
        if not self.gettextize(documents):
            return False
        if not self.pot_file_ob.replace_title_lines():
            return False
        self.pot_file_ob.hide_attr_list_statements()
        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
            self.langs[po_fn]['pofile'].hide_attr_list_statements()
        return True

    # we generate a fake translation for en-US which is going to be
    # the default
    def generate_fake_pofile(self):
        pwd = use_top_level_dir()
        self._remove_fake_po_file()
        shutil.copy(self.pot_fn, self.fake_po_fn)
        os.chdir(pwd)
        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'])

    def safeguard_meta_tags(self):
        for po_fn in self.langs:
            self.load_pofile(po_fn)
            self.langs[po_fn]['pofile'].safeguard_meta_tags()


class Documents(object):
    def __init__(self):
        md = Markdown()
        self.docs = [fn for fn in self.find_docs()
                     if verify_file_type(fn) and md.can_convert_md_file(fn)]

    def find_docs(self):
        docs = []
        for dirpath, dirnames, fns in os.walk(DOCS_PATH):
            docs += [normalise_path(os.path.join(dirpath, fn))
                     for fn in fns
                     if fn.endswith('.md')]
        return docs

    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:
            po.langs[po_fn]['pofile'].readd_attr_list_statements()
            for doc_fn in self.docs:
                output = self._call_po4a_translate(doc_fn, po_fn, po4a)

                # Extract the metadata from the first line
                first_line = output.split('\n')[0]
                metadata_keys = re.findall(r'\w+:', first_line)
                metadata_values = re.split(r'[\s]?\w+:\s', first_line)[1:]
                metadata = OrderedDict(zip(metadata_keys, metadata_values))
                if 'Date:' not in metadata:
                    metadata['Date:'] = ''

                # Replace the title string by its translated version
                translated_title_line = po.find_translated_title_line(
                    metadata['Title:'], po_fn)
                metadata['Title:'] = translated_title_line

                # Remove the metadata line
                content = '\n'.join([line for line in output.split('\n')][1:])
                new_path = os.path.join(
                    I18N_BUILD_DIR,
                    self.translated_doc_fn(doc_fn, po.langs[po_fn]['bcp47']))

                # Flatten the metadata dict into a string
                metadata_serialized = '\n'.join(
                    "{} {}".format(key, val)
                    for (key, val) in metadata.items())

                # Join the metadata and content into the final,
                # translated markdown text
                text = metadata_serialized + '\n' + content
                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)
            po.langs[po_fn]['pofile'].hide_attr_list_statements()


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

    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.po.safeguard_meta_tags()
        self.documents.write_translated_markdown(self.po, self.po4a)