Install git commit hooks after npm install using grunt
If you working on larger teams it good be a good idea to run some code quality tools before some commit. This can be done by a pre-commit hook. But how to make sure everyone has the same hook in there project. We can copy them direct after a project was build with npm install
. There are scripts
block in the package.json where we can declare commands or scripts that will be executed at a specific event, for example install
, postinstall
or uninstall
.
So in our case we want copy a pre-commit file from our project into the .git/hooks
folder.The minimal grunt file would look like this:
module.exports = function(grunt) {
grunt.initConfig({
"copy": {
"hooks": {
"files": {
// copy the pre-commit file from the hooks folder in the project into the .git/hooks folder
".git/hooks/pre-commit": "hooks/pre-commit"
}
}
}
});
grunt.loadNpmTasks('grunt-contrib-copy');
}
and in the package.json file we add a scripts section with a post install script that just calls the grunt task:
"scripts": {
"postinstall": "grunt copy:hooks"
}
Written by Andreas Köberle
Related protips
1 Response
Hi Andreas. I implemented a similar method using grunt-contrib-copy however I found that the copied file was not an executable and as a result was not run by Git. Did you find a similar issue?
Instead I used grunt-shell and copied the pre-commit executable in to .git/hooks like so.
shell: {
hooks: {
command: 'cp git-hooks/pre-commit .git/hooks/'
}
}