Skip to content

Instantly share code, notes, and snippets.

@iamdevlinph
Last active July 28, 2018 14:56
Show Gist options
  • Save iamdevlinph/bacca84cca51af7c5cb060d59eea18b5 to your computer and use it in GitHub Desktop.
Save iamdevlinph/bacca84cca51af7c5cb060d59eea18b5 to your computer and use it in GitHub Desktop.
Node script to lock versions of dependencies in package.json
const fs = require('fs');
const log = string => console.log(`\x1b[33m${string}\x1b[0m`);
log('\nRunning lock-version.js\nThe purpose of this script is to lock the npm versions of all packages to the current installed version to avoid breaking changes caused by accidental package updates.\n');
prompt('This will lock all package versions to the current version installed.\nThis will remove ^ and ~ from the version number\nProceed? y/n: ', proceed => {
proceed = proceed.toLowerCase();
switch (proceed) {
case 'y':
readFile();
break;
default:
log('\nExiting')
process.exit();
}
});
// ask user to lock all or decide for each
function readFile() {
fs.readFile('package.json', 'utf8', (err, data) => {
const packageJson = JSON.parse(data);
const deps = packageJson.dependencies;
const devDeps = packageJson.devDependencies;
log(`\nFound: \n${Object.keys(deps).length} dependencies\n${Object.keys(devDeps).length} devDependencies`);
prompt('\nProceed in locking the versions? y/n: ', decision => {
decision = decision.toLowerCase();
switch (decision) {
case 'y':
lockVersions(packageJson, deps, devDeps);
break;
default:
log('\nExiting locking')
process.exit(1);
}
});
});
}
function lockVersions(packageJson, depsObj, devDepsObj) {
log('\nLocking dependencies...');
let lockedDeps = {};
for (const dep in depsObj) {
if (!depsObj.hasOwnProperty(dep)) continue;
lockedDeps[dep] = lock(depsObj[dep]);
}
packageJson.dependencies = lockedDeps;
log('Locking devDependencies...');
let lockedDevDeps = {};
for (const dep in devDepsObj) {
if (!devDepsObj.hasOwnProperty(dep)) continue;
lockedDevDeps[dep] = lock(devDepsObj[dep]);
}
packageJson.devDependencies = lockedDevDeps;
fs.writeFile('package.json', `${JSON.stringify(packageJson, null, 4)}\n`, err => {
if (err) throw err;
log('\nAll versions has been locked\n');
process.exit();
})
}
function lock(version) {
return version.replace(/^[\^~]/ig, '')
}
function prompt(question, callback) {
var stdin = process.stdin,
stdout = process.stdout;
stdin.resume();
stdout.write(question);
stdin.once('data', function (data) {
callback(data.toString().trim());
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment