Skip to content

Commit

Permalink
Optimized pre-commit-hook action. (#574)
Browse files Browse the repository at this point in the history
* Optimized pre-commit-hook action.
 - Added template inorder  to run grunt lint only if there are staged changes.
 - Added grunt lint-nofix task to run linter in no-fix mode.
 - Fixed some linting changes too.

* changed var to let and const keywords

* updated inline comment in grunt githooks configuration
  • Loading branch information
frappelatte28 authored Jan 10, 2021
1 parent 4da9b7b commit a7d8cb0
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 1 deletion.
13 changes: 12 additions & 1 deletion Gruntfile.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,13 @@ module.exports = function(grunt) {
fix: true
},
src: ['src/**/*.js', 'test/tests/**/*.js']
},
sourceNofix: {
options: {
configFile: './.eslintrc',
fix: false
},
src: ['src/**/*.js', 'test/tests/**/*.js']
}
},
webpack: {
Expand Down Expand Up @@ -59,7 +66,10 @@ module.exports = function(grunt) {
},
githooks: {
all: {
'pre-commit':'lint' //runs linting test before every git commit
options:{
template:"templates/pre-commit-hook.js"
},
'pre-commit':'lint-nofix' //runs elint in -nofix mode before every git commit
}
}
});
Expand All @@ -73,6 +83,7 @@ module.exports = function(grunt) {
grunt.loadNpmTasks('grunt-githooks');

grunt.registerTask('lint', ['eslint:source']);
grunt.registerTask('lint-nofix', ['eslint:sourceNofix']);
grunt.registerTask('default', ['webpack:prod', 'decomment']);
grunt.registerTask('dev', ['eslint','connect','webpack:dev', 'decomment']);
grunt.registerTask('serve', 'connect:server:keepalive');
Expand Down
32 changes: 32 additions & 0 deletions templates/pre-commit-hook.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
// hooks/pre-commit.js

const exec = require('child_process').exec;
// Executes shell commands synchronously
const sh = require('child_process').execSync;

exec('git diff --cached --quiet', function (err, stdout, stderr) {

// only run if there are staged changes
// i.e. what you would be committing if you ran "git commit" without "-a" option.
if (err) {

// stash unstaged changes - only test what's being committed
sh('git stash --keep-index --quiet');

exec('grunt {{task}}', function (err, stdout, stderr) {

console.log(stdout);

// restore stashed changes
sh('git stash pop --quiet');

let exitCode = 0;
if (err) {
console.log(stderr);
exitCode = -1;
}
process.exit(exitCode);
});
}

});

0 comments on commit a7d8cb0

Please sign in to comment.