Created
November 27, 2018 18:31
-
-
Save leye0/98175487e3fe0d6e7a6a1cff0835fff1 to your computer and use it in GitHub Desktop.
Merge YAML source translation into destination translation and only add missing entries
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Little script to add missing source translation into destination translation file so it is easier to maintain | |
// Usage: | |
// add-missing-translations src=en dest=fr | |
const fs = require('fs'); | |
const YAML = require('yaml'); | |
function toKeyValues(args) { | |
return args.map(arg => arg.split('=')) | |
.reduce((args, [value, key]) => { | |
args[value] = key; | |
return args; | |
}, {}); | |
} | |
var args = toKeyValues(process.argv.slice(2)); | |
const sourceContent = fs.readFileSync(`./${args.src}.yml`, 'utf8'); | |
const src = sourceContent.trim().length > 0 ? YAML.parse(sourceContent) : {}; | |
const destContent = fs.readFileSync(`./${args.dest}.yml`, 'utf8'); | |
const dest = destContent.trim().length > 0 ? YAML.parse(destContent) : {}; | |
// Iterate through source translation feed destination translation | |
// https://stackoverflow.com/questions/7549574/merge-js-objects-without-overwriting | |
function deepmerge(object1, object2) { | |
var merged = {}; | |
for (var each in object2) { | |
if (object1.hasOwnProperty(each) && object2.hasOwnProperty(each)) { | |
if (typeof(object1[each]) == "object" && typeof(object2[each]) == "object") { | |
merged[each] = deepmerge(object1[each], object2[each]); | |
} else { | |
// Original line in the copied example: | |
// The purpose was to concatenate value from source and value from destination | |
// merged[each] = [object1[each], object2[each]]; | |
// Instead, we keep the original value | |
merged[each] = object1[each]; | |
} | |
} else if(object2.hasOwnProperty(each)) { | |
merged[each] = object2[each]; | |
} | |
} | |
for (var each in object1) { | |
if (!(each in object2) && object1.hasOwnProperty(each)) { | |
merged[each] = object1[each]; | |
} | |
} | |
return merged; | |
} | |
var result = deepmerge(dest, src); | |
fs.writeFileSync(`./${args.dest}.yml`, YAML.stringify(result), 'utf8'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment