public
Created

to_delphi_i18n

  • Download Gist
to_delphi_i18n.d
D
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
/**
* Usage: to_delphi_i18n.exe lang_json1 [lang_json2...]
* Scans 'lang_json1' JSON-file then [lang_json2...] and adds it's data to generated
* 'my_i18n.pas'.
*
* JSON-file example:
---
{
"message1": "Message1 Text",
"message2": "Message2 Text"
}
---
* usage example(Delphi):
---
uses my_i18n;
...
SetLanguage(0);
some_string := i18n.message1;
---
*
*/
import std.stdio, std.file, std.conv;
 
string to_delphi_string(string data)
{
string s = "'";
foreach (ubyte c; cast(ubyte[])(data))
{ if (c < 32 || c > 127 || c == '\'')
s ~= "'#" ~ to!string(c) ~ "'";
else
s ~= c;
}
return s ~ "'";
}
 
int main(string[] args)
{
if (args.length < 2)
{ writeln("usage to_delphi_i18n.exe file1 [file2, ...]");
return 1;
}
auto files = args[1..$];
foreach (file_; files)
if (!exists(file_))
{ writefln("File '%s' doesn't exits", file_);
return 1;
}
string[string][] data;
//Part 1.
foreach (file_; files)
{ string[string] hashMap;
//JSON parse file
import std.json;
auto str = cast(string)std.file.read(file_);
auto js = parseJSON(str);
if (js.type != JSON_TYPE.OBJECT)
{ writefln("File '%s': expected JSON OBJECT", file_);
return 1;
}
foreach (key, value; js.object)
{ if (value.type == JSON_TYPE.STRING)
hashMap[key] = value.str;
else
{ writefln("JSON expected string value for key '%s' in file '%s'", key, file_);
return 1;
}
}
data ~= hashMap;
}
//add key/value pairs for other languages
foreach (i, aa; data)
{ foreach (key; aa.byKey)
{ foreach (j, ab; data)
{ if (i == j) continue;
if ((key in ab) is null)
ab[key] = aa[key];
}
}
}
//save to generated file
auto f = File("my_i18n.pas", "w+");
string s = "unit my_i18n;\ninterface\ntype\n"
~ " Tmy_i18n_BEFCFE32_A9A0_426D_968A_51E11788BF2C = record\n";
foreach (key; data[0].byKey)
s ~= " " ~ key ~ ": string;\n";
s ~= " end;\nvar\n i18n: Tmy_i18n_BEFCFE32_A9A0_426D_968A_51E11788BF2C;\n"
~ "procedure SetLanguage(lang: Integer);\n\nimplementation\n\n"
~ "procedure SetLanguage(lang: Integer);\nbegin\n";
foreach (i; 0..files.length)
{ s ~= " if lang = " ~ to!string(i) ~ " then\n with i18n do\n begin\n";
foreach (key, value; data[i])
s ~= " " ~ key ~ " := " ~ to_delphi_string(value) ~ ";\n";
s ~= " end;\n";
}
s ~= "end;\n\nend.\n";
f.write(s);
return 0;
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.