Skip to content

Instantly share code, notes, and snippets.

@brookjordan
Last active September 2, 2019 05:04
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 brookjordan/617c6a67547d53b5e972e059e9867816 to your computer and use it in GitHub Desktop.
Save brookjordan/617c6a67547d53b5e972e059e9867816 to your computer and use it in GitHub Desktop.
Find the path to a TradeGecko i18n translation
const mode = process.env.MODE || 'STRICT';
const isCaseInsensitive = mode.includes('i');
const isSubstring = mode.includes('s');
const isVerbose = mode.includes('v');
console.log(`Searching for string '${process.env.FIND}'${
mode === 'STRICT'
? ''
: isSubstring
? ' in substring mode'
: isCaseInsensitive
? ' in case insensitive mode'
: ''
}${
isVerbose
? ' with verbose output'
: ''
}.`)
let parseYAML;
try {
const root = require('child_process').execSync('npm root -g').toString().trim();
parseYAML = require(root + '/yamljs').parse;
} catch (err) {
console.error('Install yamljs globally first with: "npm install -g yamljs"');
process.exit(1);
}
const fs = require('fs');
const toFind = process.env.FIND || 'Edit';
function collapseWhiteSpace(str) {
return str.trim().replace(/[ \n\t\r]+/g, '').toLowerCase();
}
function findTranslationPath(toFind, obj, atPath = '') {
let keys = Object.keys(obj);
let found = [];
keys.forEach(key => {
let translation = obj[key] || '';
let path = atPath ? `${atPath}.${key}` : key;
if (typeof translation === 'string') {
if ((
isSubstring > -1 && collapseWhiteSpace(translation).includes(collapseWhiteSpace(toFind)))
|| (isCaseInsensitive > -1 && (translation.toLowerCase() === toFind.toLowerCase()))
|| (mode === 'STRICT' && (translation === toFind))
) {
found.push({
path,
translation,
});
}
} else {
found = found.concat(findTranslationPath(toFind, translation, path));
}
});
return found;
}
let yamlTxt = fs.readFileSync('./config/locales/client.en.yml', { encoding: 'utf8' });
let json;
try {
json = parseYAML(yamlTxt);
} catch(e) {
console.log(`Error parsing yaml: ${e}`);
process.exit(1);
}
let results = findTranslationPath(toFind, json);
console.log('');
if (results.length === 0) {
console.log('No results found.');
} else {
console.log('Found within the following locations:');
results.forEach(result => {
let verboseString = isVerbose
? ` | ${result.translation.replace(/\n/g, '\\n')}`
: '';
console.log(`- ${
result.path.replace(/^en\.js\./, '')
}${
verboseString
}`);
});
}
function tg-i18n-path
{
if [[ $1 == '-h' ]]; then
echo 'Available search modes are "i" and "s":'
echo ' - findtranslation String => exact match for "String"'
echo ' - findtranslation String i => case insensitive match for "string"'
echo ' - findtranslation String s => case insensitive substring match "string"'
echo 'To print the value of the translation, add "v" to the flag.:'
echo ' - findtranslation String sv => the same as "s" but will also print the full translation'
return
fi
need_script=false
if [ ! -f ./t-path.js ]; then
echo ""
echo "Script not found. Adding…"
addFindTranslationFile
need_script=true
fi
echo ""
if [ -z "$2" ]; then
FIND="$1" NODE_PATH=/usr/local/lib/node_modules node t-path.js
else
FIND="$1" MODE="$2" NODE_PATH=/usr/local/lib/node_modules node t-path.js
fi
echo ""
if $need_script; then
echo "Removing added script…"
rm ./t-path.js
fi
}
function addFindTranslationFile
{
cat >"./t-path.js" <<'ENDOFSCRIPT'
var k=process.env.MODE||"STRICT",l=k.includes("i"),m=k.includes("s"),n=k.includes("v");console.log("Searching for string '"+process.env.FIND+"'"+("STRICT"===k?"":m?" in substring mode":l?" in case insensitive mode":"")+(n?" with verbose output":"")+".");var p;try{var q=require("child_process").execSync("npm root -g").toString().trim();p=require(q+"/yamljs").parse}catch(a){console.error('Install yamljs globally first with: "npm install -g yamljs"'),process.exit(1)}
var r=require("fs"),t=process.env.FIND||"Edit",u=r.readFileSync("./config/locales/client.en.yml",{encoding:"utf8"}),v;try{v=p(u)}catch(a){console.log("Error parsing yaml: "+a),process.exit(1)}var x=w(t,v);console.log("");0===x.length?console.log("No results found."):(console.log("Found within the following locations:"),x.forEach(function(a){var f=n?" | "+a.a.replace(/\n/g,"\\n"):"";console.log("- "+a.path.replace(/^en\.js\./,"")+f)}));
function w(a,f,e){e=void 0===e?"":e;var g=[];Object.keys(f).forEach(function(b){var c=f[b]||"";b=e?e+"."+b:b;"string"===typeof c?(-1<m&&c.trim().replace(/[ \n\t\r]+/g,"").toLowerCase().includes(a.trim().replace(/[ \n\t\r]+/g,"").toLowerCase())||-1<l&&c.toLowerCase()===a.toLowerCase()||"STRICT"===k&&c===a)&&g.push({path:b,a:c}):g=g.concat(w(a,c,b))});return g};
ENDOFSCRIPT
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment