You can run any pre-commit command (Shell, Gulp, Grunt etc..) and it will ignore all the unstaged changes that wasn't added to the git index (using the command git add
).
First install the package in your devDependencies
:
npm install git-pre-commit --save-dev
Or by using yarn:
yarn add git-pre-commit --dev
Now, add to your package.json
the entry:
"scripts": {
"precommit": "<task to run>"
}
That is it! No more that you need to do (except for writing what to run :) )
Note: If your root directory has a yarn.lock
file, all the scripts will be run using yarn
.
So for example you can do something like that to run Gulp task named pre-commit
:
"scripts": {
"precommit": "gulp lint"
}
Or just a shell command:
"scripts": {
"precommit": "echo Hello_World"
}
Have fun!
Most of the git pre-commit hooks are WRONG!
Why? Because most of the pre-commit hooks also take into account the unstaged changes when performing the task.
Lets take for example the most common pre-commit hook: lint.
So what usually people do?
You try to perform a commit and then your pre-commit hook runs and lints all of your files.
There are 2 issues with that common approach:
#1 - When you have some unstaged changes and you would like to commit only the staged changes (the ones you performed git add
on) your lint task checks the file itself and doesn't know if the code there will be part of the commit or not.
This resolves into 2 possible situations:
git add
the changes, now the lint task passes BUT you ended up with the fixing changes outside of your commit.#2 - It lints all the files and not just the changed files. This is not addressed in this package as it is not the point of it. (For example on how to lint only the changed files you can checkout my eslint example that also uses the git-pre-commit
package).
Like I said, this package fixes issue #1 by stashing your unstaged changes and returning the changes to the unstaged state once the pre-commit task has finished (with or without errors).
Even in this package repository I'm using the package pre-commit hook to lint all of the js files.
For example on how to address the #2 issue:
It lints all the files and not just the changed files
Take a look at my eslint example that does just that. It will save you and your team A LOT of time!