Skip to content

Commit

Permalink
Updated Node JS, some npm packages and added some git hooks
Browse files Browse the repository at this point in the history
  • Loading branch information
Priyank Parashar committed Jun 13, 2018
1 parent c326d0a commit bd3b00f
Show file tree
Hide file tree
Showing 10 changed files with 1,698 additions and 60 deletions.
73 changes: 73 additions & 0 deletions .githooks/logger.js
@@ -0,0 +1,73 @@
var chalk;
try {
chalk = require('chalk');
} catch (e) {
// do nothing
}

var boxen;
try {
boxen = require('boxen');
} catch (e) {
// do nothing
}

var stripAnsi;
try {
stripAnsi = require('strip-ansi');
} catch (e) {
// do nothing
}

var logger = {
chalkProxy: function (fnName, msg) {
if (chalk && chalk[fnName]) {
return chalk[fnName](msg);
} else {
return msg;
}
},
stripAnsi: function (msg) {
if (stripAnsi) {
return stripAnsi(msg);
} else {
return msg;
}
},
boxen: function (msg, options) {
if (boxen) {
return boxen(msg, options);
} else {
return msg;
}
},
log: function (msg) {
console.log(msg);
},
info: function (msg) {
if (chalk) {
msg = chalk.blue(msg);
}
console.log(msg);
},
warn: function (msg) {
if (chalk) {
msg = chalk.yellow(msg);
}
console.log(msg);
},
error: function (msg) {
if (chalk) {
msg = chalk.red(msg);
}
console.log(msg);
},
success: function (msg) {
if (chalk) {
msg = chalk.green(msg);
}
console.log(msg);
}
};

module.exports = logger;
23 changes: 23 additions & 0 deletions .githooks/post-checkout/post-checkout-check-node-version.js
@@ -0,0 +1,23 @@
#!/usr/bin/env node

// This Git hook finds mismatches between Node version in use and the .nvmrc file and informs the user

var fs = require('fs'),
path = require('path');

var logger = require('../logger.js');

var nodeVersion = process.versions.node;
try {
var dotNvmrcPath = path.resolve(__dirname, '../../.nvmrc'),
dotNvmrcContents = fs.readFileSync(dotNvmrcPath, 'utf8');
if(dotNvmrcContents !== nodeVersion) {
logger.log('');
logger.success(' ✓ .nvmrc suggests: Node JS ' + dotNvmrcContents);
logger.warn(' ✗ You currently use: Node JS ' + nodeVersion);
logger.warn('\nYou might want to run:');
logger.warn(' $ nvm use\n');
}
} catch (e) {
logger.warn('\nWarning: Unable to read the .nvmrc file\n');
}
155 changes: 155 additions & 0 deletions .githooks/post-checkout/post-checkout-check-npm-install-status.js
@@ -0,0 +1,155 @@
#!/usr/bin/env node

// This Git hook finds mismatches between top-level node_modules/ and package.json and informs the user
// One of the commands which you may use to initiate this hook:
// $ git checkout

var t1 = new Date();

var fs = require('fs'),
path = require('path'),
http = require('https');

var returnExitCode = (process.argv[2] === 'returnExitCode');

var semverFilePath = __dirname + '/../semver.js'; // This file needs to be placed outside this folder (post-checkout/),
// otherwise git-hooks package would attempt to execute it as well

// http://stackoverflow.com/questions/11944932/how-to-download-a-file-with-node-js-without-using-third-party-libraries/22907134#22907134
function download (url, dest, cb) {
var file = fs.createWriteStream(dest);
var request = http.get(url, function (response) {
response.pipe(file);
file.on('finish', function () {
file.close(cb); // close() is async, call cb after close completes.
});
}).on('error', function (err) { // Handle errors
fs.unlink(dest); // Delete the file async. (But we don't check the result)
if (cb) {
cb(err.message);
}
});
request.setTimeout(15000, function () {
// Note: It appears that in some cases of network failure, there is some weird problem with Node JS
// due to which request.abort() may not work fine (eg: When trying to access a URL and network is
// enabled in VirtualBox guest machine, but internet is disconnected in host machine).
// Using process.kill() as a fallback.
request.abort();
request.destroy();
fs.unlink(dest); // Delete the file async. (But we don't check the result)
cb('Timed out');
process.kill(process.pid, 'SIGKILL');
});
};

// http://stackoverflow.com/questions/171251/how-can-i-merge-properties-of-two-javascript-objects-dynamically/171256#171256
function mergeObjects (obj1, obj2) {
var obj3 = {};
for (var attr in obj1) {
obj3[attr] = obj1[attr];
}
for (var attr in obj2) {
obj3[attr] = obj2[attr];
}
return obj3;
}

function readFileAsJson (filePath) {
try {
var data = fs.readFileSync(filePath, 'utf-8');
json = JSON.parse(data);
return json;
} catch (e) {
return null;
}
}

function exitWithCodeIfRequired(exitCode) {
if (returnExitCode) {
process.exit(exitCode);
} else {
process.exit(0);
}
}

var getPathRelativeToCwd = function (strPath) {
// For calculating the relative path, preferring "process.env.PWD" first since that gives more accurate value on
// the systems where it is available. Falling back to "process.cwd()" for remaining cases
// (See: https://github.com/nodejs/node/issues/13668 - process.cwd() does not match the PWD environment variable)
return path.relative(
(process.env || {}).PWD || process.cwd(),
path.resolve(__dirname, strPath)
);
};

function main (rootPath) {
var semver = require(semverFilePath);

var mainPackageJsonPath = path.resolve(rootPath, 'package.json'),
mainPackageJson = readFileAsJson(mainPackageJsonPath),
allDependencies = mergeObjects(mainPackageJson.dependencies, mainPackageJson.devDependencies),
mismatchFound = false,
invalidFound = false;

var updateMessages = [];
Object.keys(allDependencies).forEach(function (packageName, index) {
var packageJson = readFileAsJson(path.resolve(rootPath, 'node_modules', packageName, 'package.json'));
var valid = packageJson && semver.valid(packageJson.version);
if (!valid) {
invalidFound = true;
}
var match = valid && semver.satisfies(packageJson.version, allDependencies[packageName]);
if (!match) {
mismatchFound = true;
}
if (!valid || !match) {
updateMessages.push(packageName + ' : ' + ((packageJson && packageJson.version) || 'NA') + ' -> ' + allDependencies[packageName]);
}
});

var t2 = new Date();
if (!mismatchFound && !invalidFound) {
// All npm packages are loosely matching. It might be fine to skip running "$ npm install"
return 0;
} else {
var chalk = require('chalk');
console.log(chalk.yellow('\n' + updateMessages.length + '/' + Object.keys(allDependencies).length + ' npm packages need to be updated: (' + ((t2 - t1) / 1000) + ' seconds)'));
console.log(' ' + updateMessages.join('\n '));
console.log(chalk.yellow(
'You might want to run "$ npm install" for ' +
getPathRelativeToCwd(mainPackageJsonPath) +
'\n'
));
return 1;
}
};

function initiateCheck () {
var rootPath,
returnCode;

rootPath = path.resolve(__dirname, '..', '..');
returnCode = main(rootPath);

rootPath = path.resolve(rootPath, 'live-css');
returnCode = main(rootPath) || returnCode;

exitWithCodeIfRequired(returnCode);
}

try {
fs.statSync(semverFilePath);
initiateCheck();
} catch (e) {
var url = 'https://raw.githubusercontent.com/npm/node-semver/master/semver.js';
console.log('\nDownloading (timeout: 15s) ' + url + ' (to be used in post-checkout Git hook)');
download(url, semverFilePath, function (errMsg) {
if (errMsg) {
console.log('Error: ' + errMsg);
console.log('Unable to download semver.js. Skipping detection of top-level mismatches between node_modules/ and package.json.\n');
exitWithCodeIfRequired(1);
return;
}
initiateCheck();
});
}

0 comments on commit bd3b00f

Please sign in to comment.