Skip to content

Instantly share code, notes, and snippets.

@jbreckmckye
Created March 13, 2018 11:04
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jbreckmckye/0eb00647e1ad7731ee40e3d4df9be4c1 to your computer and use it in GitHub Desktop.
Save jbreckmckye/0eb00647e1ad7731ee40e3d4df9be4c1 to your computer and use it in GitHub Desktop.
Beanstalk / general-purpose JSON mass updater
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