Git Pre-push/Pre-commit Hooks

Pre-push/Pre-commit hooks are nothing but commands which you would want to run every time you push/commit something. It might not sound very interesting, but using them with Jest and ESLint can protect the quality of your code at a much, much higher level.

"How?" you ask

Pre hooks run a shell command which you specify and if the command fails with exit status 1, the process will get terminated. We store the shell commands inside the .git/hooks directory of the root of the project. So imagine that you won't be able to push the code if your tests are failing or your js files are not properly linted. That sounds interesting right?



Your next question might be, how do you make sure that everyone adds those commands to the pre-push hooks folder?

Don't worry, we have that covered as well. Let me introduce you to an awesome NPM module called husky.

Using Husky

Just run npm install --save-dev husky or yarn add --dev husky

After installing these node-modules, all you need to do is specify which command you would like to execute before pushing/committing your code. And this can be specified within package.json. It will make sure to add the commands to your local git hooks folder while setting up (npm install) the machine.

We used husky's prepush hook to make sure that every line of code which is being pushed is linted and all the tests pass.

If you look at the package.json file of our boilerplate, you would find this snippet:

{
  "scripts": {
    "prepush": "npm run lint && npm run test",
    "postinstall": "rm -rf .git/hooks/pre-push && node node_modules/husky/bin/install.js && rm -rf .git/hooks/pre-commit"
  },
  "devDependencies": {
    "husky": "^0.14.3"
  }
}

As you can see, we are doing npm run lint and npm run test every time the developer tries to push something. If any of the commands fail, the developer would not be allowed to push, greatly reducing the chances of build failure/PR check failure in CIs.



Internally, these modules write in .git/hooks folder in pre-commit/pre-push files. After adding these modules and doing npm install, you will find something like this in .git/hooks/pre-push:

#!/bin/sh
#husky 0.14.3

command_exists () {
  command -v "$1" >/dev/null 2>&1
}

has_hook_script () {
  [ -f package.json ] && cat package.json | grep -q "\"$1\"[[:space:]]*:"
}
...
...

This code is autogenerated by the node module so we don't have to worry about it. If you are not able to find this file, it means that your hooks were not properly installed. Please uninstall and install the module again or do npm run postinstall.

Note: In the case of Windows machines, make sure that you have bash(Cygwin). Prepush hooks will fail if you use Command Prompt

The code till here can be found on the branch chapter/6/6.2

results matching ""

    No results matching ""