forked from CoStarGroup/auto-localize
-
Notifications
You must be signed in to change notification settings - Fork 1
/
localize.js
executable file
·83 lines (64 loc) · 2.89 KB
/
localize.js
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
var googleTranslate = require('google-translate')('XXXXXXXXXXX');
if (process.argv.length < 3) {
console.log('Usage: node ' + process.argv[1] + ' FILENAME');
process.exit(1);
}
var filename = process.argv[2];
var langs = ['es-MX', 'de-DE', 'fr-FR'];
var fs = require('fs');
var xml2js = require('xml2js');
var Enumerable = require('linq');
var parser = new xml2js.Parser();
var builder = new xml2js.Builder();
var Sync = require('sync');
// read the file to auto-localize
fs.readFile(filename, 'utf8', function (err, data) {
// check for errors
if (err) {
return console.log(err);
}
// parse the XML into a JSON object
parser.parseString(data, function(err, json) {
Sync(function(){
// select the current english language terms to localize
// could use a query here but we'll just use the convention that the first one is English
var terms = Enumerable.from(json.terms.items[0].item).select('$._').toArray();
// throw away any existing translations
json.terms.items.splice(1, json.terms.items.length);
// loop through all the supported languages
langs.map(function(lang, index) {
var translations;
// translate all the terms at once into the language
console.log('Translating', terms.length, 'terms into', lang);
// The result will be passed to a Sync callback
var result = googleTranslate.translate.sync(null, terms, 'en', lang.substr(0, 2));
if (result.length > 0) {
// flatten down the Google translate response to just what we need
translations = Enumerable.from(result).select('$.translatedText').toArray();
} else {
translations = [result.translatedText];
}
// create a deep copy of the English terms that were localized
var items = JSON.parse(JSON.stringify(json.terms.items[0]));
// set the language for these terms
items.$.culture = langs[index];
// loop through the results and update the JSON
translations.map(function(translation, index) {
// use the results to update the English terms to the localized terms
items.item[index]._ = translation;
});
// add the localized items
json.terms.items.push(items);
});
// convert the updated JSON back into XML
var xml = builder.buildObject(json);
// write the XML updates to disk
fs.writeFile('Localization.xml', xml, function (err) {
if (err) {
return console.log(err);
}
console.log('Localization.xml terms updated');
});
});
});
});