Skip to content

Commit a7d8cb0

Browse files
Optimized pre-commit-hook action. (#574)
* 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
1 parent 4da9b7b commit a7d8cb0

File tree

2 files changed

+44
-1
lines changed

2 files changed

+44
-1
lines changed

Gruntfile.js

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,13 @@ module.exports = function(grunt) {
2828
fix: true
2929
},
3030
src: ['src/**/*.js', 'test/tests/**/*.js']
31+
},
32+
sourceNofix: {
33+
options: {
34+
configFile: './.eslintrc',
35+
fix: false
36+
},
37+
src: ['src/**/*.js', 'test/tests/**/*.js']
3138
}
3239
},
3340
webpack: {
@@ -59,7 +66,10 @@ module.exports = function(grunt) {
5966
},
6067
githooks: {
6168
all: {
62-
'pre-commit':'lint' //runs linting test before every git commit
69+
options:{
70+
template:"templates/pre-commit-hook.js"
71+
},
72+
'pre-commit':'lint-nofix' //runs elint in -nofix mode before every git commit
6373
}
6474
}
6575
});
@@ -73,6 +83,7 @@ module.exports = function(grunt) {
7383
grunt.loadNpmTasks('grunt-githooks');
7484

7585
grunt.registerTask('lint', ['eslint:source']);
86+
grunt.registerTask('lint-nofix', ['eslint:sourceNofix']);
7687
grunt.registerTask('default', ['webpack:prod', 'decomment']);
7788
grunt.registerTask('dev', ['eslint','connect','webpack:dev', 'decomment']);
7889
grunt.registerTask('serve', 'connect:server:keepalive');

templates/pre-commit-hook.js

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
// hooks/pre-commit.js
2+
3+
const exec = require('child_process').exec;
4+
// Executes shell commands synchronously
5+
const sh = require('child_process').execSync;
6+
7+
exec('git diff --cached --quiet', function (err, stdout, stderr) {
8+
9+
// only run if there are staged changes
10+
// i.e. what you would be committing if you ran "git commit" without "-a" option.
11+
if (err) {
12+
13+
// stash unstaged changes - only test what's being committed
14+
sh('git stash --keep-index --quiet');
15+
16+
exec('grunt {{task}}', function (err, stdout, stderr) {
17+
18+
console.log(stdout);
19+
20+
// restore stashed changes
21+
sh('git stash pop --quiet');
22+
23+
let exitCode = 0;
24+
if (err) {
25+
console.log(stderr);
26+
exitCode = -1;
27+
}
28+
process.exit(exitCode);
29+
});
30+
}
31+
32+
});

0 commit comments

Comments
 (0)