-
Notifications
You must be signed in to change notification settings - Fork 0
/
check_translations.js.example
76 lines (68 loc) · 2.92 KB
/
check_translations.js.example
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
#!/usr/bin/env node
const fs = require('fs');
const _ = require('lodash');
const path = require('path');
const projectId = 'focal-welder-174713';
const KEEP_ENGLISH_FLAG = '--keep-english';
// Imports the Google Cloud client library
const { Translate } = require('@google-cloud/translate').v2;
// Instantiates a client
const translate = new Translate({ projectId });
//Args
const destinationLanguages = ['ru', 'cn', 'es', 'fr', 'it', 'th', 'de'];
const languageGoogleAPICodes = { ru: 'ru', cn: 'zh-CN', es: 'es', fr: 'fr', it: 'it', th: 'th', de: 'de' };
const languageNamesMap = {
ru: 'Russian',
cn: 'Chinese',
es: 'Spanish',
fr: 'French',
it: 'Italian',
th: 'Thai',
de: 'German',
};
function replaceJokerValues(origin, target) {
let targetReplaced = target;
const reg = /{{[^{}]+}}/g;
const originMatches = [...origin.matchAll(reg)];
const targetMatches = [...target.matchAll(reg)];
targetMatches.forEach((match, i) => {
targetReplaced = targetReplaced.replace(match[0], originMatches[i][0]);
});
return targetReplaced;
}
async function translateMissingValues(originLanguage, targetLanguage, languageKey) {
if (_.isObject(originLanguage)) {
await Promise.all(
Object.keys(originLanguage).map(async (key) => {
if (_.isObject(originLanguage[key])) {
if (!targetLanguage[key]) {
targetLanguage[key] = {};
}
await translateMissingValues(originLanguage[key], targetLanguage[key], languageKey);
} else if (!targetLanguage[key]) {
console.log(`Translating '${originLanguage[key]}' to ${languageNamesMap[languageKey]}`);
if (originLanguage[key].includes(KEEP_ENGLISH_FLAG)) {
originLanguage[key] = originLanguage[key].replace(KEEP_ENGLISH_FLAG, '');
targetLanguage[key] = originLanguage[key];
} else {
targetLanguage[key] = replaceJokerValues(
originLanguage[key],
(await translate.translate(originLanguage[key], languageGoogleAPICodes[languageKey]))[0]
);
}
}
})
);
}
}
destinationLanguages.forEach((languageKey, index) => {
const fileName = `src/i18n/${languageKey}.json`;
const originLanguage = JSON.parse(fs.readFileSync(path.resolve(`src/i18n/en.json`), 'utf-8'));
const targetLanguage = JSON.parse(fs.readFileSync(path.resolve(`src/i18n/${languageKey}.json`), 'utf-8'));
translateMissingValues(originLanguage, targetLanguage, languageKey).then(() => {
fs.writeFileSync(fileName, JSON.stringify(targetLanguage, null, 4));
});
if (index === destinationLanguages.length - 1) {
fs.writeFileSync(`src/i18n/en.json`, JSON.stringify(originLanguage, null, 4));
}
});