Skip to content

Instantly share code, notes, and snippets.

@komakino
Last active April 9, 2020 10:35
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 komakino/d9855721f3d17f3debfbba3d10830c66 to your computer and use it in GitHub Desktop.
Save komakino/d9855721f3d17f3debfbba3d10830c66 to your computer and use it in GitHub Desktop.
Sync json locale files
#!/usr/bin/env node
var fs = require("fs");
const readJson = (path) => {
let raw = fs.readFileSync(path)
try {
return JSON.parse(raw)
} catch (error) {
return {}
}
}
const defaultLocale = 'en-US.json'
const defaultData = readJson(defaultLocale)
const getFiles = (path) => {
const fileNames = fs.readdirSync(path)
const jsonFiles = fileNames.filter(file => /\.json$/.test(file) && file !== defaultLocale)
const files = {}
return jsonFiles.reduce((files, file) => {
files[file] = readJson(`${path}${file}`)
return files
}, files)
}
const isString = (subject) => typeof subject === "string"
const isSameType = (a, b) => typeof a === typeof b
const sync = (data = {}, defaultData) => {
for (key of Object.keys(defaultData)) {
if (!(key in data)) {
if (isString(defaultData[key])) {
data[key] = ""
} else {
data[key] = sync(data[key], defaultData[key])
}
} else {
if (!isSameType(data[key], defaultData[key])) {
throw new Error(`Different types found for key "${key}". Aborting.`)
}
if (!isString(data[key])) {
data[key] = sync(data[key], defaultData[key])
}
}
}
return data
}
const map = getFiles('./')
for (let [locale, data] of Object.entries(map)) {
console.group(locale)
console.log('Syncing...')
let synced = JSON.stringify(sync(data, defaultData), null, 2)
fs.writeFileSync(locale, synced);
console.log('Done.')
console.groupEnd()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment