element-desktop/scripts/copy-res.ts

82 lines
2.4 KiB
TypeScript
Raw Normal View History

#!/usr/bin/env -S npx ts-node
2021-07-01 10:32:09 +00:00
// copies resources into the lib directory.
import parseArgs from "minimist";
import * as chokidar from "chokidar";
import * as path from "path";
import * as fs from "fs";
2021-07-01 10:32:09 +00:00
const argv = parseArgs(process.argv.slice(2), {});
const watch = argv.w;
const verbose = argv.v;
function errCheck(err?: Error): void {
2021-07-01 10:32:09 +00:00
if (err) {
console.error(err.message);
process.exit(1);
}
}
const I18N_BASE_PATH = "src/i18n/strings/";
2022-12-15 11:00:58 +00:00
const INCLUDE_LANGS = fs.readdirSync(I18N_BASE_PATH).filter((fn) => fn.endsWith(".json"));
2021-07-01 10:32:09 +00:00
// Ensure lib, lib/i18n and lib/i18n/strings all exist
2022-12-15 11:00:58 +00:00
fs.mkdirSync("lib/i18n/strings", { recursive: true });
2021-07-01 10:32:09 +00:00
type Translations = Record<string, Record<string, string> | string>;
function genLangFile(file: string, dest: string): void {
const translations: Translations = {};
2022-12-15 11:00:58 +00:00
[file].forEach(function (f) {
2021-07-01 10:32:09 +00:00
if (fs.existsSync(f)) {
try {
Object.assign(translations, JSON.parse(fs.readFileSync(f).toString()));
2021-07-01 10:32:09 +00:00
} catch (e) {
console.error("Failed: " + f, e);
throw e;
}
}
});
const json = JSON.stringify(translations, null, 4);
const filename = path.basename(file);
fs.writeFileSync(dest + filename, json);
if (verbose) {
console.log("Generated language file: " + filename);
}
}
/*
2021-07-01 10:32:09 +00:00
watch the input files for a given language,
regenerate the file, and regenerating languages.json with the new filename
*/
function watchLanguage(file: string, dest: string): void {
2021-07-01 10:32:09 +00:00
// XXX: Use a debounce because for some reason if we read the language
// file immediately after the FS event is received, the file contents
// appears empty. Possibly https://github.com/nodejs/node/issues/6112
let makeLangDebouncer: NodeJS.Timeout | undefined;
const makeLang = (): void => {
2021-07-01 10:32:09 +00:00
if (makeLangDebouncer) {
clearTimeout(makeLangDebouncer);
}
makeLangDebouncer = setTimeout(() => {
2021-07-01 11:03:38 +00:00
genLangFile(file, dest);
2021-07-01 10:32:09 +00:00
}, 500);
};
2022-12-15 11:00:58 +00:00
chokidar.watch(file).on("add", makeLang).on("change", makeLang).on("error", errCheck);
2021-07-01 10:32:09 +00:00
}
// language resources
const I18N_DEST = "lib/i18n/strings/";
INCLUDE_LANGS.forEach((file): void => {
2021-07-01 10:32:09 +00:00
genLangFile(I18N_BASE_PATH + file, I18N_DEST);
}, {});
if (watch) {
2022-12-15 11:00:58 +00:00
INCLUDE_LANGS.forEach((file) => watchLanguage(I18N_BASE_PATH + file, I18N_DEST));
2021-07-01 10:32:09 +00:00
}