-
Notifications
You must be signed in to change notification settings - Fork 6
/
presets_merge_labels.js
94 lines (80 loc) · 2.22 KB
/
presets_merge_labels.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
84
85
86
87
88
89
90
91
92
93
94
/*
* Updates XML presets files using translations from Transifex
*/
const fs = require('fs');
const xml2js = require('xml2js');
const Hash = require("object-hash");
const PRESETS_DIR = "./public/presets";
const LOCALES_DIR = "./src/config/locales/presets";
const XML_RGX = /^[A-Za-z0-9_\-]+\.xml$/;
const JSON_RGX = /^[A-Za-z0-9_\-]+\.json$/;
// Load in-memory all translation files
let locales = {};
fs.readdirSync(LOCALES_DIR).forEach((file) => {
if(JSON_RGX.test(file) && file !== "en.json") {
try {
const localeJson = JSON.parse(fs.readFileSync(LOCALES_DIR+"/"+file, 'utf8'));
locales = Object.assign(locales, localeJson);
}
catch(e) {
throw new Error("Can't parse translation file: "+file+" ("+e.message+")");
}
}
});
// Function for adding translation to given object
const addTranslation = entry => {
Object.entries(entry).forEach(e => {
const [ k, v ] = e;
if(k === "$") {
Object.entries(v).forEach(ve => {
const [ vk, vv ] = ve;
if([ "text", "name", "display_values", "display_value"].includes(vk)) {
const strhash = Hash(vv);
Object.keys(locales).forEach(l => {
if(locales[l][strhash] && locales[l][strhash] !== vv) {
v[l+"."+vk] = locales[l][strhash];
}
});
}
});
}
else {
addTranslation(v);
}
});
return entry;
};
// Read all presets files, add translations, and rewrite them
fs.readdirSync(PRESETS_DIR).forEach((file) => {
if(XML_RGX.test(file)) {
try {
const xml = fs.readFileSync(PRESETS_DIR+"/"+file, 'utf8');
// Parse XML content
xml2js.parseString(xml, (err, result) => {
if (err) {
throw new Error("Parse error", e.message);
}
else {
// Append translations to JS object
result = addTranslation(result);
// Rewrite XML file
const newXml = (new xml2js.Builder({ renderOpts: { pretty: true, indent: '\t' } })).buildObject(result);
fs.writeFile(PRESETS_DIR+"/"+file, newXml, function(err) {
if(err) {
throw new Error(err);
}
else {
console.log("[INFO] Preset file "+file+" updated");
}
});
}
});
}
catch(e) {
throw new Error("Can't update preset: "+file+" ("+e.message+")");
}
}
else {
console.log("[INFO] Ignored file "+file);
}
});