forked from Acode-Foundation/Acode
-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathlang.js
More file actions
executable file
·408 lines (361 loc) · 8.73 KB
/
lang.js
File metadata and controls
executable file
·408 lines (361 loc) · 8.73 KB
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
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
const path = require("node:path");
const fs = require("node:fs");
const yargs = require("yargs");
const { hideBin } = require("yargs/helpers");
const readline = require("node:readline");
const args = yargs(hideBin(process.argv))
.alias("a", "all")
.alias("b", "bulk").argv;
const dir = path.resolve(__dirname, "../src/lang");
const read = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
const enLang = path.join(dir, "en-us.json");
const list = fs.readdirSync(dir);
const len = list.length;
let command = "";
let arg = "";
let val = "";
if (args._.length > 3) {
console.error("Invalid arguments", args._);
process.exit(0);
} else {
command = args._[0];
arg = args._[1];
val = args._[2];
}
switch (command) {
case "add":
case "remove":
case "update":
case "update-key":
case "search":
case "check":
update();
break;
case "add-all":
addToAllFiles();
break;
case "bulk-add":
bulkAddStrings();
break;
default:
console.error(`Missing/Invalid arguments.
use 'add' to add a new string
use 'add-all <key> <value>' to add the same string to ALL language files at once
use 'bulk-add <json-file>' to add multiple strings from a JSON file to all language files
use 'remove' to remove a string
use 'search' to search a string
use 'update' to update a string
use 'update-key' to update a key
use 'check' to check a string`);
process.exit();
}
/**
* Adds a key-value pair to ALL language files at once
* Usage: pnpm lang add-all "key" "value"
*/
function addToAllFiles() {
if (!arg || !val) {
console.error('Usage: pnpm lang add-all "<key>" "<value>"');
console.error('Example: pnpm lang add-all "hello world" "Hello World"');
process.exit(1);
}
const key = arg.toLowerCase();
let addedCount = 0;
let skippedCount = 0;
for (const lang of list) {
const file = path.resolve(dir, lang);
const text = fs.readFileSync(file, "utf8");
const strings = JSON.parse(text);
if (key in strings) {
console.log(`${lang}: Skipped (already exists)`);
skippedCount++;
continue;
}
strings[key] = val;
const newText = JSON.stringify(strings, undefined, 2);
fs.writeFileSync(file, newText, "utf8");
console.log(`${lang}: Added ✓`);
addedCount++;
}
console.log(
`\nDone! Added to ${addedCount} files, skipped ${skippedCount} files.`,
);
process.exit(0);
}
/**
* Bulk add multiple strings from a JSON file to ALL language files
* Usage: pnpm lang bulk-add strings.json
*
* JSON file format:
* {
* "key1": "value1",
* "key2": "value2"
* }
*/
function bulkAddStrings() {
if (!arg) {
console.error("Usage: pnpm lang bulk-add <json-file>");
console.error("Example: pnpm lang bulk-add new-strings.json");
console.error("\nJSON file format:");
console.error("{");
console.error(' "key1": "value1",');
console.error(' "key2": "value2"');
console.error("}");
process.exit(1);
}
const jsonFilePath = path.resolve(process.cwd(), arg);
if (!fs.existsSync(jsonFilePath)) {
console.error(`File not found: ${jsonFilePath}`);
process.exit(1);
}
let newStrings;
try {
const jsonContent = fs.readFileSync(jsonFilePath, "utf8");
newStrings = JSON.parse(jsonContent);
} catch (err) {
console.error(`Error parsing JSON file: ${err.message}`);
process.exit(1);
}
const keys = Object.keys(newStrings);
if (keys.length === 0) {
console.error("No strings found in the JSON file.");
process.exit(1);
}
console.log(
`Adding ${keys.length} strings to ${list.length} language files...\n`,
);
for (const lang of list) {
const file = path.resolve(dir, lang);
const text = fs.readFileSync(file, "utf8");
const strings = JSON.parse(text);
let addedCount = 0;
let skippedCount = 0;
for (const key of keys) {
const lowerKey = key.toLowerCase();
if (lowerKey in strings) {
skippedCount++;
continue;
}
strings[lowerKey] = newStrings[key];
addedCount++;
}
if (addedCount > 0) {
const newText = JSON.stringify(strings, undefined, 2);
fs.writeFileSync(file, newText, "utf8");
}
console.log(`${lang}: Added ${addedCount}, Skipped ${skippedCount}`);
}
console.log(`\nDone! Added ${keys.length} strings to all language files.`);
process.exit(0);
}
async function update() {
let key;
if (command === "check") {
let total = 0;
let done = 0;
fs.readFile(enLang, "utf-8", (err, data) => {
if (err) {
console.error(err);
process.exit(0);
return;
}
let error = false;
const fix = arg === "fix";
const enLangData = JSON.parse(data);
list.forEach((file, i) => {
if (file === "en-us.json") return;
let flagError = false;
let langFile = path.join(dir, file);
const exit = (i, len) => {
if (i + 1 === len) {
if (!error) {
console.log("\nGOOD NEWS! No Error Found\n");
}
process.exit(0);
}
};
fs.readFile(langFile, "utf-8", (err, data) => {
if (err) {
console.error(err);
process.exit(1);
return;
}
let langError = () => {
if (!flagError) {
error = true;
flagError = true;
console.log(`-------------- ${file}`);
}
};
const langData = JSON.parse(data);
flagError = false;
for (let enKey in enLangData) {
const key = Object.keys(langData).find((k) => {
try {
if (new RegExp(`^${escapeRegExp(k)}$`, "i").test(enKey)) {
return true;
}
return false;
} catch (e) {
console.log({ e, k });
return false;
}
});
if (!key) {
langError();
if (fix) {
langData[enKey] = enLangData[enKey];
}
console.log(`Missing: ${enKey} ${fix ? "✔" : ""}`);
} else if (key !== enKey) {
langError();
console.log(`Fix: "${key} --> ${enKey}" ${fix ? "✔" : ""}`);
if (fix) {
const val = langData[key];
delete langData[key];
langData[enKey] = val;
}
}
}
if (flagError) {
if (fix) {
total += 1;
const langJSONData = JSON.stringify(langData, undefined, 2);
fs.writeFile(langFile, langJSONData, (err) => {
if (err) {
console.error(err);
process.exit(1);
}
done += 1;
exit(done, total);
});
}
console.log("\n");
}
if (!fix) {
exit(i, len);
}
});
});
});
return;
}
if (!arg) {
getStr("string: ").then((res) => {
key = res.toLowerCase();
arg = res;
askTranslation();
});
return;
}
key = arg.toLowerCase();
let newKey = val;
askTranslation();
if (command === "update-key" && !newKey) {
newKey = await getStr("new key: ");
}
function askTranslation(i = 0) {
const lang = list[i];
const langName = lang.split(".")[0];
if (command === "add") {
if (!args.a) {
getStr(`${langName}: `).then(addString);
return;
}
addString();
} else if (command === "remove") {
update((strings) => {
if (key in strings) {
delete strings[key];
console.log(`Removed: ${key}`);
return strings;
} else {
console.error("String not exists");
}
});
} else if (command === "update-key") {
update((strings) => {
const val = strings[key];
delete strings[key];
strings[newKey] = val;
return strings;
});
} else if (command === "update") {
if (val) {
update((strings) => {
strings[key] = val;
return strings;
});
} else {
getStr(`${langName}: `).then((res) => {
res = res || arg;
update((strings) => {
strings[key] = res;
return strings;
});
});
}
} else if (command === "search") {
update((string) => {
if (key in string) console.log(`${key}(${langName}): ${string[key]}`);
else {
console.log(`${key} not exists`);
process.exit();
}
});
}
function update(modify) {
const file = path.resolve(dir, lang);
const text = fs.readFileSync(file, "utf8");
const strings = modify(JSON.parse(text));
if (strings) {
const newText = JSON.stringify(strings, undefined, 2);
fs.writeFile(file, newText, "utf8", (err) => {
if (err) {
console.error(err);
process.exit(1);
}
next();
});
} else {
next();
}
function next() {
if (i === list.length - 1) {
process.exit();
} else {
askTranslation(++i);
}
}
}
function addString(string) {
string = string || arg;
update((strings) => {
if (key in strings) {
console.error("String already exists");
process.exit(1);
} else {
strings[key] = string;
return strings;
}
});
}
}
}
function getStr(str) {
return new Promise((resolve, reject) => {
if (val) {
resolve(val);
return;
}
read.question(str, (res) => {
resolve(res);
});
});
}
function escapeRegExp(text) {
return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
}