forked from frappe/books
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgenerateTranslations.ts
323 lines (274 loc) · 8.72 KB
/
generateTranslations.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
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
import fs from 'fs/promises';
import path from 'path';
import { UnknownMap } from 'utils/types';
import { generateCSV, parseCSV } from '../utils/csvParser';
import {
getIndexFormat,
getWhitespaceSanitized,
schemaTranslateables,
} from '../utils/translationHelpers';
/* eslint-disable no-console, @typescript-eslint/no-floating-promises */
const translationsFolder = path.resolve(__dirname, '..', 'translations');
const PATTERN = /(?<!\w)t`([^`]+)`/g;
type Content = { fileName: string; content: string };
function shouldIgnore(p: string, ignoreList: string[]): boolean {
const name = p.split(path.sep).at(-1) ?? '';
return ignoreList.includes(name);
}
async function getFileList(
root: string,
ignoreList: string[],
extPattern = /\.(js|ts|vue)$/
): Promise<string[]> {
const contents: string[] = await fs.readdir(root);
const files: string[] = [];
const promises: Promise<void>[] = [];
for (const c of contents) {
const absPath = path.resolve(root, c);
const isDir = (await fs.stat(absPath)).isDirectory();
if (isDir && !shouldIgnore(absPath, ignoreList)) {
const pr = getFileList(absPath, ignoreList, extPattern).then((fl) => {
files.push(...fl);
});
promises.push(pr);
} else if (absPath.match(extPattern) !== null) {
files.push(absPath);
}
}
await Promise.all(promises);
return files;
}
async function getFileContents(fileList: string[]): Promise<Content[]> {
const contents: Content[] = [];
const promises: Promise<void>[] = [];
for (const fileName of fileList) {
const pr = fs.readFile(fileName, { encoding: 'utf-8' }).then((content) => {
contents.push({ fileName, content });
});
promises.push(pr);
}
await Promise.all(promises);
return contents;
}
async function getAllTStringsMap(
contents: Content[]
): Promise<Map<string, string[]>> {
const strings: Map<string, string[]> = new Map();
const promises: Promise<void>[] = [];
contents.forEach(({ fileName, content }) => {
const pr = getTStrings(content).then((ts) => {
if (ts.length === 0) {
return;
}
strings.set(fileName, ts);
});
promises.push(pr);
});
await Promise.all(promises);
return strings;
}
function getTStrings(content: string): Promise<string[]> {
return new Promise((resolve) => {
const tStrings = tStringFinder(content);
resolve(tStrings);
});
}
function tStringFinder(content: string): string[] {
return [...content.matchAll(PATTERN)].map(([, t]) => {
t = getIndexFormat(t);
return getWhitespaceSanitized(t);
});
}
function tStringsToArray(
tMap: Map<string, string[]>,
tStrings: string[]
): string[] {
const tSet: Set<string> = new Set();
for (const k of tMap.keys()) {
tMap.get(k)!.forEach((s) => tSet.add(s));
}
for (const ts of tStrings) {
tSet.add(ts);
}
return Array.from(tSet).sort();
}
function printHelp() {
const shouldPrint = process.argv.findIndex((i) => i === '-h') !== -1;
if (shouldPrint) {
console.log(
`Usage: ` +
`\tyarn script:translate\n` +
`\tyarn script:translate -h\n` +
`\tyarn script:translate -l [language_code]\n` +
`\n` +
`Example: $ yarn script:translate -l de\n` +
`\n` +
`Description:\n` +
`\tPassing a language code will create a '.csv' file in\n` +
`\tthe 'translations' subdirectory. Translated strings are to\n` +
`\tbe added to this file.\n\n` +
`\tCalling the script without args will update the translation csv\n` +
`\tfile with new strings if any. Existing translations won't\n` +
`\tbe removed.\n` +
`\n` +
`Parameters:\n` +
`\tlanguage_code : An ISO 693-1 code or a locale identifier.\n` +
`\n` +
`Reference:\n` +
`\tISO 693-1 codes: https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes\n` +
`\tLocale identifier: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl#locale_identification_and_negotiation`
);
}
return shouldPrint;
}
function getLanguageCode() {
const i = process.argv.findIndex((i) => i === '-l');
if (i === -1) {
return '';
}
return process.argv[i + 1] ?? '';
}
function getTranslationFilePath(languageCode: string) {
return path.resolve(translationsFolder, `${languageCode}.csv`);
}
async function regenerateTranslation(tArray: string[], path: string) {
// Removes old strings, adds new strings
const storedCSV = await fs.readFile(path, { encoding: 'utf-8' });
const storedMatrix = parseCSV(storedCSV);
const map: Map<string, string[]> = new Map();
for (const row of storedMatrix) {
const tstring = row[0];
map.set(tstring, row.slice(1));
}
const matrix = tArray.map((source) => {
const stored = map.get(source) ?? [];
const translation = stored[0] ?? '';
const context = stored[1] ?? '';
return [source, translation, context];
});
const csv = generateCSV(matrix);
await fs.writeFile(path, csv, { encoding: 'utf-8' });
console.log(`\tregenerated: ${path}`);
}
async function regenerateTranslations(languageCode: string, tArray: string[]) {
// regenerate one file
if (languageCode.length !== 0) {
const path = getTranslationFilePath(languageCode);
regenerateTranslation(tArray, path);
return;
}
// regenerate all translation files
console.log(`Language code not passed, regenerating all translations.`);
for (const filePath of await fs.readdir(translationsFolder)) {
if (!filePath.endsWith('.csv')) {
continue;
}
regenerateTranslation(tArray, path.resolve(translationsFolder, filePath));
}
}
async function writeTranslations(languageCode: string, tArray: string[]) {
const path = getTranslationFilePath(languageCode);
try {
const stat = await fs.stat(path);
if (!stat.isFile()) {
throw new Error(`${path} is not a translation file`);
}
console.log(
`Existing file found for '${languageCode}': ${path}\n` +
`regenerating it's translations.`
);
regenerateTranslations(languageCode, tArray);
} catch (err) {
if ((err as NodeJS.ErrnoException).code !== 'ENOENT') {
throw err;
}
const matrix = tArray.map((s) => [s, '', '']);
const csv = generateCSV(matrix);
await fs.writeFile(path, csv, { encoding: 'utf-8' });
console.log(`Generated translation file for '${languageCode}': ${path}`);
}
}
async function getTStringsFromJsonFileList(
fileList: string[]
): Promise<string[]> {
const promises: Promise<void>[] = [];
const schemaTStrings: string[][] = [];
for (const filePath of fileList) {
const promise = fs
.readFile(filePath, { encoding: 'utf8' })
.then((content) => {
const schema = JSON.parse(content) as Record<string, unknown>;
const tStrings: string[] = [];
pushTStringsFromSchema(schema, tStrings, schemaTranslateables);
return tStrings;
})
.then((ts) => {
schemaTStrings.push(ts);
});
promises.push(promise);
}
await Promise.all(promises);
return schemaTStrings.flat();
}
function pushTStringsFromSchema(
map: UnknownMap | UnknownMap[],
array: string[],
translateables: string[]
) {
if (Array.isArray(map)) {
for (const item of map) {
pushTStringsFromSchema(item, array, translateables);
}
return;
}
if (typeof map !== 'object') {
return;
}
for (const key of Object.keys(map)) {
const value = map[key];
if (translateables.includes(key) && typeof value === 'string') {
array.push(value);
}
if (typeof value !== 'object') {
continue;
}
pushTStringsFromSchema(
value as UnknownMap | UnknownMap[],
array,
translateables
);
}
}
async function getSchemaTStrings() {
const root = path.resolve(__dirname, '../schemas');
const fileList = await getFileList(root, ['tests', 'regional'], /\.json$/);
return await getTStringsFromJsonFileList(fileList);
}
async function run() {
if (printHelp()) {
return;
}
const root = path.resolve(__dirname, '..');
const ignoreList = ['node_modules', 'dist_electron', 'scripts'];
const languageCode = getLanguageCode();
console.log();
const fileList: string[] = await getFileList(root, ignoreList);
const contents: Content[] = await getFileContents(fileList);
const tMap: Map<string, string[]> = await getAllTStringsMap(contents);
const schemaTStrings: string[] = await getSchemaTStrings();
const tArray: string[] = tStringsToArray(tMap, schemaTStrings);
try {
await fs.stat(translationsFolder);
} catch (err) {
if ((err as NodeJS.ErrnoException).code !== 'ENOENT') {
throw err;
}
await fs.mkdir(translationsFolder);
}
if (languageCode === '') {
regenerateTranslations('', tArray);
return;
}
writeTranslations(languageCode, tArray);
}
run();