Skip to content

Instantly share code, notes, and snippets.

@andronoob
Last active August 23, 2022 16:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andronoob/eff442b8058781f829b925ff1c5d625d to your computer and use it in GitHub Desktop.
Save andronoob/eff442b8058781f829b925ff1c5d625d to your computer and use it in GitHub Desktop.
NodeJS script for fixing sabotaged zh_CN translation of Bitcoin Core project
const fs = require('fs');
const xmljs = require('xml-js'); // https://github.com/nashwaan/xml-js
const toBeFixedXML = fs.readFileSync("for_use_bitcoin_qt-translation-023x_zh_CN.xlf", "utf-8");
const goodOneXML = fs.readFileSync("bitcoin_zh_CN.ts");
const params = {
compact: true,
spaces: 2,
};
var toBeFixed = xmljs.xml2json(toBeFixedXML, params);
var goodOne = xmljs.xml2json(goodOneXML, params);
//fs.writeFileSync("toBeFixed.json", toBeFixed);
//fs.writeFileSync("goodOne.json", goodOne);
fs.writeFileSync("toBeFixed.xml", xmljs.json2xml(toBeFixed, params));
//fs.writeFileSync("goodOne.xml", xmljs.json2xml(goodOne, params));
var toBeFixedObj = JSON.parse(toBeFixed);
var goodOneObj = JSON.parse(goodOne);
function getTranslatedText(resname, sourceText) {
let context = goodOneObj.TS.context.find((item) => item.name._text === resname);
if (context == null) {
console.error(`cannot find context. resname=${resname} sourceText=${sourceText}`);
return;
}
let message = context.message;
if (!Array.isArray(message)) message = [message];
let matched = message.filter((item) => item.source._text === sourceText);
switch (matched.length) {
case 0:
console.error(`no result matched. resname=${resname} sourceText=${sourceText}`);
return;
case 1:
return matched[0].translation._text;
default:
console.error(`matched more than one result. resname=${resname} sourceText=${sourceText}`);
console.error(matched);
return;
}
}
function fixTranslationUnit(resname, unit) {
if (Array.isArray(unit)) {
unit.forEach((item) => fixTranslationUnit(resname, item));
} else {
let sourceText = unit.source._text;
let translatedText = getTranslatedText(resname, sourceText);
if (translatedText == null) {
if (unit.target != null && unit.target._text === sourceText) {
unit.target._text = "SABOTAGED";
console.log(`mark as SABOTAGED resname=${resname} sourceText=${sourceText}`);
}
} else {
unit.target._text = translatedText;
}
};
}
function fixTranslationGroup(group) {
if (Array.isArray(group)) {
group.forEach((item) => fixTranslationGroup(item));
} else {
let resname = group._attributes.resname;
let unit = group["trans-unit"];
fixTranslationUnit(resname, unit);
}
}
toBeFixedObj.xliff.file.forEach((item) => fixTranslationGroup(item.body.group));
var fixed = JSON.stringify(toBeFixedObj);
var fixedXML = xmljs.json2xml(fixed, params)
fs.writeFileSync("fixed_for_use_bitcoin_qt-translation-023x_zh_CN.xlf", fixedXML);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment