Git Hooks with Husky

Git Hooks with Husky

posted in dev-setup on

Avoid pushing changes that break the build with githooks and Husky.

typicode/husky : 🐺 Git hooks made easy

Hooks

git hooks
Run a program before certain points in gits execution.

They are defined in .git\hooks.
You can find some example files in that directory. Remove their .sample suffix to test them out.

Husky

Hooks are saved locally and not pushed to the remote. Husky allows you to easily make the git hooks part of the repository itself.

npm install husky --save-dev

Add to package.json

{
  "husky": {
    "hooks": {
      "pre-push": "bash prepush.sh",
      "pre-commit": "npm run lint"
    }
  }
}

It’s also possible to put the json (without the husky node) in a .huskyrc or .huskyrc.json file.

prepush.sh

Prepush script that works around the frontend project package.json not being in the root of the git repository.

#!/bin/sh

# Path Juggling
originalPath=`pwd`
if [ "`git rev-parse --show-cdup`" != "" ]; then cd `git rev-parse --show-cdup`; fi
cd ./frontend-project-folder/

# Linting
npm run lint
if [ $? -ne 0 ]; then
    cd $originalPath
    exit -1
fi

# Testing
npm test
if [ $? -ne 0 ]; then
  cd $originalPath
  exit -1
fi

# Build
npm run build
hasBuildErrors=$?

cd $originalPath
exit $hasBuildErrors

Other

More control with .huskyrc.js and environment variables.

const tasks = arr => arr.join(' && ');

module.exports = {
  'hooks': {
    'pre-commit': tasks([
      'echo $HUSKY_GIT_PARAMS',
      'echo $HUSKY_GIT_STDIN',
      'echo $HUSKY_DEBUG',
      'echo $HUSKY_SKIP_INSTALL'
    ])
  }
};

Other interesting reads
Tags: git