~chromium-team/chromium-browser/chromium-translations-tools.head

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
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
#!/usr/bin/python
# -*- coding: utf-8 -*-

# (c) 2010-2011, Fabien Tassin <fta@ubuntu.com>

# Convert a desktop file to Gettext files and back

import sys, getopt, os, codecs, re, time
from datetime import datetime

class DesktopFile(dict):
    """ Read and write a desktop file """
    def __init__(self, desktop = None, src_pkg = None, verbose = False):
        self.changed = False
        self.data = []
        self.headers = {}
        self.template = {}
        self.translations = {}
        self.src_pkg = src_pkg
        self.mtime = None
        self.verbose = verbose
        if desktop is not None:
            self.read_desktop_file(desktop)

    def read_desktop_file(self, filename):
        self.data = []
        self.template = {}
        self.mtime = os.path.getmtime(filename)
        fd = codecs.open(filename, "rb", encoding="utf-8")
        section = None
        for line in fd.readlines():
            m = re.match(r'^\[(.*?)\]', line)
            if m is not None:
                section = m.group(1)
                assert section not in self.template, "Duplicate section [%s]" % section
                self.template[section] = {}
            m = re.match(r'^(Name|GenericName|Comment)(\[\S+\]|)=(.*)', line)
            if m is None:
                self.data.append(line)
                continue
            assert section is not None, "Found a '%s' outside a section" % m.group(1)
            entry = m.group(1)
            value = m.group(3)
            if m.group(2) == "":
                # master string
                self.data.append(line)
                assert entry not in self.template[section], \
                    "Duplicate entry '%s' in section [%s]" % (entry, section)
                self.template[section][entry] = value
                if value not in self.translations:
                    self.translations[value] = {}
            else:
                # translation
                lang = m.group(2)[1:-1]
                string = self.template[section][entry]
                assert entry in self.template[section], \
                    "Translation found for lang '%s' in section [%s] before master entry '%s'" % \
                    (lang, section, entry)
                if lang not in self.translations[string]:
                    self.translations[string][lang] = value
        fd.close()

    def dump(self):
        for section in sorted(self.template.keys()):
            print "[%s]:" % section
            for entry in sorted(self.template[section].keys()):
                print "  '%s': '%s'" % (entry, self.template[section][entry])
        print
        for string in sorted(self.translations.keys()):
            print "'%s':" % string
            for lang in sorted(self.translations[string].keys()):
                print "   '%s' => '%s'" % (lang, self.translations[string][lang])

    def write_desktop(self, file):
        fd = codecs.open(file, "wb", encoding="utf-8")
        for ent in self.data:
            fd.write(ent)
            m = re.match(r'^(Name|GenericName|Comment)=(.*)', ent)
            if m is None:
                continue
            k = m.group(2)
            if k not in self.translations:
                continue
            for lang in sorted(self.translations[k].keys()):
                fd.write("%s[%s]=%s\n" % (m.group(1), lang, self.translations[k][lang]))

    def write_gettext_header(self, fd, mtime = None, last_translator = None, lang_team = None):
        mtime = "YEAR-MO-DA HO:MI+ZONE" if mtime is None else \
            datetime.fromtimestamp(mtime).strftime("%Y-%m-%d %H:%M+0000")
        last_translator = "FULL NAME <EMAIL@ADDRESS>" if last_translator is None else \
            last_translator
        lang_team = "LANGUAGE <LL@li.org>" if lang_team is None else lang_team
        fd.write("""\
# %s desktop file.
# Copyright (C) 2010-2011 Fabien Tassin
# This file is distributed under the same license as the %s package.
# Fabien Tassin <fta@ubuntu.com>, 2010-2011.
#
msgid ""
msgstr ""
"Project-Id-Version: %s\\n"
"Report-Msgid-Bugs-To: https://bugs.launchpad.net/ubuntu/+source/%s/+filebug\\n"
"POT-Creation-Date: %s\\n"
"PO-Revision-Date: %s\\n"
"Last-Translator: %s\\n"
"Language-Team: %s\\n"
"MIME-Version: 1.0\\n"
"Content-Type: text/plain; charset=UTF-8\\n"
"Content-Transfer-Encoding: 8bit\\n"

""" % (self.src_pkg, self.src_pkg, self.src_pkg, self.src_pkg,
       datetime.fromtimestamp(self.mtime).strftime("%Y-%m-%d %H:%M+0000"),
       mtime, last_translator, lang_team))
                 
    def write_gettext_string(self, fd, string, translation = None, usage = None):
        if translation is None:
            translation = ""
        if usage is not None:
            fd.write("#. %s\n" % usage)
        fd.write('msgid "%s"\nmsgstr "%s"\n\n' % (string, translation))

    def get_usage(self, string):
        res = []
        for section in sorted(self.template.keys()):
            for entry in sorted(self.template[section].keys()):
                if self.template[section][entry] == string:
                    res.append("[%s] %s" % (section, entry))
        return ", ".join(res)

    def read_gettext_string(self, fd):
        string = {}
        cur = None
        while 1:
            s = fd.readline()
            if len(s) == 0 or s == "\n":
                break # EOF or end of block
            if s.rfind('\n') == len(s) - 1:
                s = s[:-1]  # chomp
            if s.find("# ") == 0 or s == "#":  # translator-comment
                if 'comment' not in string:
                    string['comment'] = ''
                string['comment'] += s[2:]
                continue
            if s.find("#:") == 0: # reference
                if 'reference' not in string:
                    string['reference'] = ''
                string['reference'] += s[2:]
                if s[2:].find(" id: ") == 0:
                    string['id'] = s[7:].split(' ')[0]
                continue
            if s.find("#.") == 0: # extracted-comments
                if 'extracted' not in string:
                    string['extracted'] = ''
                string['extracted'] += s[2:]
                if s[2:].find(" - condition: ") == 0:
                    if 'conditions' not in string:
                        string['conditions'] = []
                    string['conditions'].append(s[16:])
                continue
            if s.find("#~") == 0: # obsolete messages
                continue
            if s.find("#") == 0: # something else
                print "%s not expected. Skip" % repr(s)
                continue  # not supported/expected
            if s.find("msgid ") == 0:
                cur = "string"
                if cur not in string:
                    string[cur] = u""
                else:
                    string[cur] += "\n"
                string[cur] += s[6:]
                continue
            if s.find("msgstr ") == 0:
                cur = "translation"
                if cur not in string:
                    string[cur] = u""
                else:
                    string[cur] += "\n"
                string[cur] += s[7:]
                continue
            if s.find('"') == 0:
                if cur is None:
                    print "'%s' not expected here. Skip" % s
                    continue
                string[cur] += "\n" + s
                continue
            print "'%s' not expected here. Skip" % s
        return None if string == {} else string

    def merge_gettext_string(self, string, lang):
        msg = string['string'][1:-1]
        if msg == "": # header
            self.headers[lang] = {}
            map(lambda x: self.headers[lang].setdefault(x.split(": ")[0], x.split(": ")[1]),
                string['translation'][4:-3].replace('\\n"\n"', '\n').replace('"\n"', '').split('\n'))
            return
        if msg not in self.translations:
            return  # obsolete string
        translation = string['translation'][1:-1]
        if translation == "": # no translation
            return
        if lang not in self.translations[msg]:
            if self.verbose:
                print "merge translation for lang '%s' string '%s'" % (lang, msg)
            self.translations[msg][lang] = translation
        elif self.translations[msg][lang] != translation:
            if self.verbose:
                print "update translation for lang '%s' string '%s'" % (lang, msg)
            self.translations[msg][lang] = translation

    def read_gettext_file(self, filename):
        fd = codecs.open(filename, "rb", encoding="utf-8")
        strings = []
        while 1:
            string = self.read_gettext_string(fd)
            if string is None:
                break
            strings.append(string)
        fd.close()
        return strings

    def get_langs(self):
        langs = []
        for st in self.translations:
            for lang in self.translations[st]:
                if lang not in langs:
                    langs.append(lang)
        return sorted(langs)

    def export_gettext_file(self, directory, template_name = "desktop_file", lang = None):
        filename = os.path.join(directory, "%s.pot" % template_name if lang is None else "%s.po" % lang)
        # if there's already a file with this name, compare its content and only update it
        # when it's needed
        update = False
        if not os.path.exists(filename):
            update = True
        else:
            # compare the strings
            strings = self.read_gettext_file(filename)[1:]
            old = sorted(map(lambda x: x['string'][1:-1], strings))
            new = sorted(self.translations.keys())
            if old != new:
                update = True
                if self.verbose:
                    print "strings differ for %s. Update" % filename
            if not update:
                # compare string descriptions
                old = map(lambda x: x['extracted'][1:],
                          sorted(strings, lambda a, b: cmp(a['string'][1:-1], b['string'][1:-1])))
                new = map(lambda x: self.get_usage(x), sorted(self.translations.keys()))
                if old != new:
                    update = True
                    if self.verbose:
                        print "string descriptions differ for %s. Update" % filename
            if not update and lang is not None:
                # compare translations
                old = map(lambda x: x['translation'][1:-1],
                          sorted(strings, lambda a, b: cmp(a['string'][1:-1], b['string'][1:-1])))
                new = map(lambda x: self.translations[x][lang] if lang in self.translations[x] else "",
                          sorted(self.translations.keys()))
                if old != new:
                    update = True
                    if self.verbose:
                        print "translations differ for %s. Update" % filename
        if not update:
            return
        if self.verbose:
            print "update %s" % filename
        fd = codecs.open(filename, 'wb', encoding='utf-8')
        last_translator = None
        lang_team = None
        if lang is None:
            self.mtime = time.time()
            mtime = None
        else:
            mtime = time.time()
            if lang in self.headers and 'Last-Translator' in self.headers[lang]:
                last_translator = self.headers[lang]['Last-Translator']
            if lang in self.headers and 'Language-Team' in self.headers[lang]:
                lang_team = self.headers[lang]['Language-Team']
            else:
                lang_team = "%s <%s@li.org>" % (lang, lang)
        self.write_gettext_header(fd, mtime = mtime, last_translator = last_translator, lang_team = lang_team)
        for string in sorted(self.translations.keys()):
            val = self.translations[string][lang] \
                if lang is not None and lang in self.translations[string] else None
            self.write_gettext_string(fd, string, val, usage = self.get_usage(string))
        fd.close()
        self.changed = True

    def export_gettext_files(self, directory):
        if not os.path.isdir(directory):
            os.makedirs(directory, 0755)
        self.export_gettext_file(directory)
        for lang in self.get_langs():
            self.export_gettext_file(directory, lang = lang)

    def import_gettext_files(self, directory):
        """ Import strings from gettext 'po' files, ignore the 'pot'.
        Only merge strings matching our desktop file """
        assert os.path.isdir(directory)
        for file in os.listdir(directory):
            lang, ext = os.path.splitext(file)
            if ext != '.po':
                continue
            for string in self.read_gettext_file(os.path.join(directory, file)):
                self.merge_gettext_string(string, lang)

def usage():
    appname = sys.argv[0].rpartition('/')[2]
    print """
Usage: %s [options] --import-desktop master.desktop
              [--export-gettext to-launchpad]
              [--import-gettext from-launchpad]
              [--export-desktop improved.desktop]
              [--project-name somename]

  Convert a desktop file to Gettext files and back

  options could be:
    -v | --verbose    verbose mode
    --import-desktop file   master desktop file (mandatory)
    --import-gettext dir    GetText files to merge
    --export-gettext dir    merged GetText files
    --export-desktop file   improved desktop file
    --project-name name     project or source package name

""" % appname

if '__main__' == __name__:
    sys.stdout = codecs.getwriter('utf8')(sys.stdout)
    try:
        opts, args = getopt.getopt(sys.argv[1:], "dhv",
                                   [ "verbose", "project-name=",
                                     "import-desktop=", "export-desktop=",
                                     "import-gettext=", "export-gettext=" ])
    except getopt.GetoptError, err:
        print str(err)
        usage()
        sys.exit(2)

    verbose = False
    desktop_in = None
    desktop_out = None
    gettext_in = None
    gettext_out = None
    project_name = "misconfigured-project"
    for o, a in opts:
        if o in ("-v", "--verbose"):
            verbose = True
        elif o in ("-h", "--help"):
            usage()
            sys.exit()
        elif o == "--project-name":
            project_name = a
        elif o == "--import-desktop":
            desktop_in = a
        elif o == "--export-desktop":
            desktop_out = a
        elif o == "--import-gettext":
            gettext_in = a
        elif o == "--export-gettext":
            gettext_out = a

    if desktop_in is None:
        print "Error: --import-desktop is mandatory"
        usage()
        sys.exit(2)

    df = DesktopFile(desktop_in, src_pkg = project_name, verbose = verbose)
    if gettext_in is not None:
        df.import_gettext_files(gettext_in)
    if gettext_out is not None:
        df.export_gettext_files(gettext_out)
    if desktop_out is not None:
        if desktop_in != desktop_out or df.changed:
            df.write_desktop(desktop_out)
    exit(1 if df.changed else 0)