Skip to content

Instantly share code, notes, and snippets.

@tatupesonen
Created November 18, 2022 14:52
Show Gist options
  • Save tatupesonen/158576c60a30b335cb73a73a4ff5ac5c to your computer and use it in GitHub Desktop.
Save tatupesonen/158576c60a30b335cb73a73a4ff5ac5c to your computer and use it in GitHub Desktop.
Translate
const path = require('path');
const YAML = require('yaml')
fs = require('fs');
const exec = require('child_process').execSync;
const filenames = [];
function fromDir(startPath, filter) {
if (!fs.existsSync(startPath)) {
return;
}
var files = fs.readdirSync(startPath);
for (var i = 0; i < files.length; i++) {
var filename = path.join(startPath, files[i]);
var stat = fs.lstatSync(filename);
if (stat.isDirectory()) {
fromDir(filename, filter); //recurse
} else if (filename.endsWith(filter)) {
filenames.push(filename);
};
};
};
const getTranslation = (val) => {
const command = `trans -b :ja "${val}"`;
const res = exec(command);
return res.toString();
}
const recursiveReplace = (obj) => {
const keys = Object.keys(obj);
for (const key of keys) {
if (typeof obj[key] === "string") {
if (obj[key].includes("{")) continue;
const translation = getTranslation(obj[key]);
console.log(`${obj[key]} -> ${translation}`);
obj[key] = translation.replaceAll("\n", "");
}
else {
recursiveReplace(obj[key]);
}
}
}
const init = async () => {
fromDir('.', '.yml');
for(const file of filenames) {
console.log("Translating " + file)
const read = fs.readFileSync(file, 'utf-8');
let parsed;
try {
parsed = YAML.parse(read);
} catch(e) {
console.log("Failed parsing " + file);
continue;
}
recursiveReplace(parsed);
const stuff = YAML.stringify(parsed);
fs.writeFileSync(file, stuff);
console.log("Saved " + file);
}
}
init();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment