Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sisilicon
GitHub Repository: sisilicon/worldedit-be
Path: blob/master/tools/po2lang.mjs
1780 views
1
import fs from "fs";
2
import path from "path";
3
import polib from "pofile";
4
import { globSync } from "glob";
5
6
const BPdir = "BP/texts";
7
const RPdir = "RP/texts";
8
const srcDir = "texts";
9
10
function getLang(file) {
11
return path.basename(file).replace(".po", "");
12
}
13
14
function convertFile(inPath, outPath) {
15
const po = polib.parse(fs.readFileSync(inPath, "utf-8"));
16
17
let newlines = [];
18
for (const entry of po.items) {
19
if (entry.msgid !== "" && !(entry.msgid !== "pack.description" && outPath.includes("BP"))) {
20
const string = entry.msgstr[0].replace(/\\"/, '"').replace(/\n/, "~LINEBREAK~");
21
newlines.push(`${entry.msgid}=${string}\n`);
22
if (outPath.includes("BP")) break;
23
}
24
}
25
if (newlines.length > 0) {
26
newlines[newlines.length - 1] = newlines[newlines.length - 1].replace(/\n$/, "");
27
}
28
fs.writeFileSync(outPath, newlines.join(""), { encoding: "utf-8" });
29
// console.log(`${inPath} converted to ${outPath}`);
30
}
31
32
function convertLang(filename) {
33
const lang = getLang(filename);
34
convertFile(filename, `${BPdir}/${lang}.lang`);
35
convertFile(filename, `${RPdir}/${lang}.lang`);
36
}
37
38
function updateLangJson() {
39
globSync(srcDir + "/*.po", (err, files) => {
40
if (err) throw err;
41
const languages = files.map(getLang);
42
for (const folder of [RPdir, BPdir]) {
43
const arr = languages.map((l) => ` "${l}"`);
44
const json = "[\n" + arr.join(",\n") + "\n]";
45
fs.writeFileSync(path.join(folder, "languages.json"), json, "utf-8");
46
}
47
});
48
}
49
50
export default function (args) {
51
// Remove old .lang files
52
for (const file of [...globSync(`${BPdir}/*.lang`), ...globSync(`${RPdir}/*.lang`)]) {
53
if (!file.includes("AUTO_GENERATED")) fs.unlinkSync(file);
54
}
55
// Convert all .po files
56
for (const file of globSync(`${srcDir}/*.po`)) convertLang(file);
57
updateLangJson();
58
59
if (args.watch) {
60
// Watch for changes in the source directory
61
fs.watch(srcDir, { recursive: true }, (eventType, filename) => {
62
if (!filename.endsWith(".po")) return;
63
convertLang(path.join(srcDir, filename));
64
updateLangJson();
65
});
66
}
67
}
68
69