Git Hooks

Git Hooks

Introduction

Git hooks are scripts that run automatically every time a particular event occurs in a Git repository. They let you customize Git's internal behavior and trigger customizable actions at key points in the development life cycle.

Husky

Husky is the package we used to install git hooks into the project.

You can use it to lint your commit messages, run tests, lint code, etc... when you commit or push. Husky supports all Git hooks.

Official website & docs can be found here (opens in a new tab)

Configuration

First, we need to install husky package : npm -D i husky then we run these 2 commands to add husky to the project:

  npm set-script prepare "husky install"
  npm run prepare

the first command will just create a script in package.json, the second one will install husky, which does create a folder .husky inside the project root.

now, to add a pre-commit hook, that will be executed before each commit, we run this command :

npx husky add .husky/pre-commit "command_to_run"

a file called pre-commit under .husky/ will be created, with the command inside it.

Hooks used in the project

the folder .husky/ contains the following :

.
├── _/
├── commit-msg
└── pre-commit

hook commit-msg:

It is a hook that check commit messages if the obey to commitlnt conventential rules. check this section

#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"
 
npx commitlint --edit
 

hook pre-commit:

It is a hook used to be run before each commit, so it actually runs static analysis on the staged files:

#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"
 
  npx lint-staged
 

Because it will be expensive to run static tests on the whole project code base each time, we use the package lint-staged to only lint staged files, by installing it as a dev dependency, the add the follwing to the package.json :

 "lint-staged": {
    "*.{js,jsx,ts,tsx}": "eslint --fix"
  },

Here is the result of a commit that actually has static test failing :