Merge branch 'master' of /home/angel/src/../git/mp-5.x
[mp-5.x.git] / tools / po2mpsl.mpsl
blobff7502dedd9a8e8fde3f19f0e354f624b545fd4d
1 /*
3         Parses .po files and dumps MPSL code.
5         Angel Ortega <angel@triptico.com>
7 */
9 sub convert_po_line(line)
11     return line->sregex('/^\s*"/')->
12                 sregex('/"$/')->
13                 split()->
14                 map(
15                     sub (e) {
16                         (ord(e) > 127) &&
17                         sprintf("\\x{%04x}", ord(e)) ||
18                         e;
19                     }
20                 )->
21                 join();
25 sub parse_po_file(pofile)
27         local f;
28         local r = [];
30         /* only UTF-8 po files are supported */
31         encoding('UTF-8');
33         if ((f = open(pofile, "r")) != NULL) {
35                 local l;
36                 local i = 0;
37                 local v = [];
39                 while ((l = read(f)) != NULL) {
41                         l = mp.chomp(l);
43                         local s = regex(l, [ '/^(msgid|msgstr)*/', '/\s*\".*\"$/' ]);
44                         s[1] = convert_po_line(s[1]);
46                         if (s[0] eq 'msgid') {
47                                 i = 0;
48                                 push(v, [[], []]);
49                         }
50                         else
51                         if (s[0] eq 'msgstr') {
52                                 i = 1;
53                         }
55                         if (s[1]) {
56                                 push(v[-1][i], s[1]);
57                         }
58                 }
60                 push(r, "/* Built by po2mpsl - Don't modify, change the .po file instead */");
61                 push(r, "__I18N__ = {");
63                 foreach (l, v) {
64                         if (size(l[1]))
65                                 push(r, "\t\"" ~ join(l[0]) ~ "\" => \"" ~ join(l[1]) ~ "\",");
66                 }
68                 push(r, "\t\"-\" => \"-\"\n};\n");
70                 close(f);
71         }
73         /* back to default encoding */
74         encoding();
76         return join(r, "\n");
79 /* main */
81 foreach (f, glob('po/*.po')) { /**/
82         local output = parse_po_file(f);
84         /* strip extension and path */
85         f = shift(split(f, '.po'));
86         f = pop(split(f, '/'));
88         local o = open('lang/' ~ f ~ '.mpsl', 'w');
89         write(o, output);
90         close(o);
93 mp.exit();