-
-
Save jrson83/da31e49df3d367f3e0145f61c06db8de to your computer and use it in GitHub Desktop.
Beanstalk / general-purpose JSON mass updater
This file contains hidden or 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
const fs = require('fs'); | |
const cliArgs = process.argv.slice(2); | |
const key = cliArgs[0]; | |
const val = cliArgs[1]; | |
function parseJSON(string) { | |
const sanitised = string.replace(/\s\$\w*/g, substr => `"__SANITISED__${substr}"`); | |
return JSON.parse(sanitised); | |
} | |
function serialiseJSON(json) { | |
const string = JSON.stringify(json, null, 2); | |
return string.replace(/\"__SANITISED__\s\$\w*"/g, substr => substr.slice(15, -1)); | |
} | |
function readJSON(file) { | |
return new Promise((resolve, reject) => { | |
fs.readFile(file, 'utf8', (err, data) => { | |
if (err) { | |
reject(err); | |
} else { | |
resolve(parseJSON(data)); | |
} | |
}); | |
}); | |
} | |
function writeJSON(file, data) { | |
const json = serialiseJSON(data); | |
return new Promise((resolve, reject) => { | |
fs.writeFile(file, json, 'utf8', err => { | |
if (err) { | |
reject(err); | |
} else { | |
resolve(); | |
} | |
}); | |
}); | |
} | |
async function updateFile(file) { | |
const json = await readJSON(file); | |
if (typeof json.OptionSettings === 'object') { | |
// Beanstalk config | |
const configItems = Object.values(json.OptionSettings); | |
const item = configItems.find(object => object.OptionName === key); | |
if (item) { | |
item.Value = val; | |
return writeJSON(file, json); | |
} else { | |
console.warn('Item not found'); | |
} | |
} else if (json[key] !== undefined) { | |
// Plain JSON files | |
json[key] = val; | |
return writeJSON(file, json); | |
} | |
} | |
function updateFiles() { | |
return Promise.all([ | |
updateFile(__dirname + '/devConfig.json'), | |
updateFile(__dirname + '/config/prod.template.json'), | |
updateFile(__dirname + '/config/staging.template.json') | |
]).then(() => { | |
console.log('All done!'); | |
}); | |
} | |
updateFiles(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment