-
Notifications
You must be signed in to change notification settings - Fork 33
/
generate-i18n.ts
269 lines (221 loc) · 7.44 KB
/
generate-i18n.ts
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
import { execSync } from 'child_process';
import * as deepl from 'deepl-node';
import { existsSync, readFileSync, writeFileSync } from 'fs';
declare type Message = Record<string, string>;
declare type Format = 'arb' | 'json';
let sourceLocale = 'en';
function getSourceMessages({ path, filename }: { path: string; filename: string }) {
return getMessages({ filePath: `${path}/${filename}` });
}
function getMessagesPathByLocale({ path, locale, format = 'json' }: { path: string; locale: string; format?: Format }) {
if (format === 'arb') {
return `${path}/messages.${locale}.arb`;
}
return `${path}/${locale}.json`;
}
function getMessagesByLocale({ path, locale, format }: { path: string; locale: string; format: Format }): Message {
const filePath = getMessagesPathByLocale({ path, locale, format });
return getMessages({ filePath });
}
function getMessages({ filePath }: { filePath: string }): Message {
if (!existsSync(filePath)) {
console.log('File does not exist', filePath);
return {};
}
const data = readFileSync(filePath, 'utf8');
if (!data) {
return {};
}
const messages = JSON.parse(data);
return messages;
}
function setMessagesByLocale({
path,
locale,
messages,
format,
}: {
path: string;
locale: string;
messages: Message;
format: Format;
}) {
const data = JSON.stringify(messages, null, 2);
writeFileSync(getMessagesPathByLocale({ path, locale, format }), data, 'utf8');
}
function removeDeletedTranslations({
sourceMessages,
targetMessages,
}: {
sourceMessages: Message;
targetMessages: Message;
}) {
const newTargetMessages: Record<string, string> = {};
for (const [key] of Object.entries(sourceMessages)) {
if (targetMessages[key]) {
newTargetMessages[key] = targetMessages[key];
}
}
return newTargetMessages;
}
function sortMessageLikeSourceMessage({
sourceMessages,
targetMessages,
}: {
sourceMessages: Message;
targetMessages: Message;
}) {
const newTargetMessages: Record<string, string> = {};
for (const [key] of Object.entries(sourceMessages)) {
if (targetMessages[key]) {
newTargetMessages[key] = targetMessages[key];
}
}
return newTargetMessages;
}
async function flattenFile(filePath: string) {
const data = readFileSync(filePath, 'utf8');
const messages = JSON.parse(data);
function flattenObject(entries: [string, any][]) {
const result: Record<string, string> = {};
function flatten(obj: any, prefix = '') {
for (const [key, value] of Object.entries(obj)) {
const newKey = prefix ? `${prefix}.${key}` : key;
if (typeof value === 'object' && value !== null) {
flatten(value, newKey);
} else {
result[newKey] = value as string;
}
}
}
for (const [key, value] of entries) {
flatten(value, key);
}
return result;
}
// Sort by name
const sortedMessages = Object.entries(messages).sort((a, b) => a[0].localeCompare(b[0]));
return flattenObject(sortedMessages);
}
async function flattenAllFiles(options: { i18nFilesPath: string; locales: string[] }) {
for (const locale of options.locales) {
const filePath = options.i18nFilesPath + '/' + locale + '.json';
const sourceMessages = await flattenFile(filePath);
writeFileSync(filePath, JSON.stringify(sourceMessages, null, 2), 'utf8');
}
}
export default async function runExecutor(options: {
i18nFilesPath: string;
sourceLocaleFileName?: string;
sourceLocale?: string;
format?: Format;
locales: string[];
}) {
if (!process.env.DEEPL_API_KEY) {
throw new Error('DEEPL_API_KEY is not set');
}
const translator = new deepl.Translator(process.env.DEEPL_API_KEY);
const format = options.format ?? 'json';
let sourceMessages = getSourceMessages({
path: options.i18nFilesPath,
filename: options.sourceLocaleFileName ?? 'messages.json',
});
// Convert back to Record<string, string>
sourceMessages = Object.entries(sourceMessages)
.sort((a, b) => a[0].localeCompare(b[0]))
.reduce(
(acc, [key, value]) => {
acc[key] = value;
return acc;
},
{} as Record<string, string>,
);
setMessagesByLocale({
path: options.i18nFilesPath,
locale: options.sourceLocale,
messages: sourceMessages,
format,
});
if (options.sourceLocale) {
sourceLocale = options.sourceLocale;
}
console.log(`Processing source locale ${sourceLocale}`);
console.log(`Locales to translate to: ${options.locales.join(', ')}`);
for (const locale of options.locales) {
let deeplLocal = locale;
if (deeplLocal === 'en') {
deeplLocal = 'en-US';
}
console.log(`Translating to locale ${locale}`);
const targetMessages = getMessagesByLocale({ path: options.i18nFilesPath, locale, format });
// Remove duplicate and save file to disk
const newTargetMessages = removeDeletedTranslations({ sourceMessages, targetMessages });
setMessagesByLocale({ path: options.i18nFilesPath, locale, messages: newTargetMessages, format });
let newTranslatedMessages = 0;
for (const [key, value] of Object.entries(sourceMessages)) {
if (format === 'arb' && key.startsWith('@')) {
if (key === '@@locale') {
newTargetMessages[key] = locale;
} else {
newTargetMessages[key] = value;
}
continue;
}
if (!newTargetMessages[key]) {
// Replace all variables present in the text between { and } by {XX_count_XX} to avoid deepl to translate them
let valueWithReplacedVariables = value;
const variables = value.match(/{.*?}/g);
if (variables) {
let i = 0;
for (const variable of variables) {
valueWithReplacedVariables = value.replace(variable, `{XX_${i++}}`);
}
}
const translationResult = await translator.translateText(
valueWithReplacedVariables,
sourceLocale as deepl.SourceLanguageCode,
deeplLocal as deepl.TargetLanguageCode,
);
let translatedText = translationResult.text;
// Put the variable back
if (variables) {
let i = 0;
for (const variable of variables) {
translatedText = translationResult.text.replace(`{XX_${i++}}`, variable);
}
}
newTargetMessages[key] = translatedText;
newTranslatedMessages++;
// Save every new translation just in case the script crashes or is interrupted
setMessagesByLocale({ path: options.i18nFilesPath, locale, messages: newTargetMessages, format });
}
}
// Save file with sorted keys for easier diffing
setMessagesByLocale({
path: options.i18nFilesPath,
locale,
messages: sortMessageLikeSourceMessage({ sourceMessages, targetMessages: newTargetMessages }),
format,
});
// Format with prettier
execSync(
`prettier --ignore-unknown --write "${getMessagesPathByLocale({ path: options.i18nFilesPath, locale, format })}"`,
{
stdio: 'inherit',
},
);
console.log(`Done processing locale ${locale} with ${newTranslatedMessages} new translations`);
}
return { success: true };
}
// flattenAllFiles({
// i18nFilesPath: __dirname + '/projects/plugin/src/i18n',
// locales: ['en', 'ar', 'el', 'fr', 'it'],
// });
runExecutor({
i18nFilesPath: __dirname + '/projects/plugin/src/i18n',
sourceLocaleFileName: 'en.json',
sourceLocale: 'en',
format: 'json',
locales: ['ar', 'de', 'el', 'es', 'fr', 'it', 'nl', 'pl', 'pt-PT', 'pt-BR', 'ru'],
});