Web   ·   Wiki   ·   Activities   ·   Blog   ·   Lists   ·   Chat   ·   Meeting   ·   Bugs   ·   Git   ·   Translate   ·   Archive   ·   People   ·   Donate
summaryrefslogtreecommitdiffstats
path: root/examples/6_Maths_matchingAnglesAndShapes/js/mo2js.py
blob: f2804eb9dea76d1e83e90a99868cfa2594955d70 (plain)
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
#! /usr/bin/env python

import codecs
import gettext
import json

# TBD: generate $.i18n.choose_pluralized_msg. Similar to how python
# gettext does this.

def context_and_key(key):
    """Return a tuple containing the context (or None) and the message
    key."""
    # A context, if present, is prepended to the key, with a \x04
    # character in between.
    (context, separator, k) = key.partition(u'\x04')
    if (separator != ''):
        return (context, k)
    else:
        return (None, key)

def group_pluralized_forms(dict):
    """Return a dictionary where the pluralized forms from dict are
    grouped. Elements of the form
    (msg, i) -> tr1
    ...
    (msg, j) -> trn
    are grouped into:
    msg -> [tr1, ..., trn]
    """
    result = {}
    keys = dict.keys()
    keys.sort()
    for k in keys:
        translation = dict[k]
        if type(k) is tuple:
            # A pluralized form k = (msg, n)
            k = k[0]
            if k not in result:
                result[k] = []
            result[k].append(translation)
        else:
            result[k] = translation
    return result

def path(key):
    """Return the path in the dictionary for key"""
    (context, key) = context_and_key(key)
    if context is not None:
        return ['contextualized_strings', context, key]
    else:
        return ['strings', key]

def store_translation(dictionary, key, translation):
    p = path(key)
    while len(p) > 1:
        x = p.pop(0)
        if x not in dictionary:
            dictionary[x] = {}
        dictionary = dictionary[x]
    dictionary[p[0]] = translation

def gettext_json(fp, indent = False):
    result = {}
    tr = gettext.GNUTranslations(fp)
    dictionary = group_pluralized_forms(tr._catalog)
    for k, v in group_pluralized_forms(tr._catalog).items():
        store_translation(result, k, v)
    return json.dumps(result, ensure_ascii = False, indent = indent)

def usage(argv0):
    print 'Usage:'
    print '\t' + argv0 + ' language mo-file js-file'

if __name__ == '__main__':
    import sys
    if len(sys.argv) != 4:
        usage(sys.argv[0])
        sys.exit(1)
    [lang, mo, js] = sys.argv[1:]
    f = codecs.open(js, encoding='utf-8', mode='w+')
    lang = sys.argv[1]
    f.write('$.i18n.%s =\n' % lang);
    f.write(gettext_json(open(mo, 'r'), True))
    f.write(';\n');
    f.write('$.i18n.setLocale(\'%s\');\n' % lang);