DEV Community

Ethan Carlsson
Ethan Carlsson

Posted on • Edited on

Using Git Hooks To Run your Tests and/or Linter

Original article: https://www.ethancarlsson.dev/blog/githooks

If you're looking to set up a simple way to run
code before each commit in a pre-commit hook for
a Javascript project, this is how I did it.

Setup

Hooks don't actually depend on anything other than git, but
I'm using vite and yarn in this project.
It would work the same with any build tool,
and if you use npm just replace yarn [command] with npm run [command].

For the hook to work you need to write this code in
{YOUR_PROJECT_ROOT}/.git/hooks/pre-commit.
So to get started write one of the following into your
terminal from your project root:

For vim: vim .git/hooks/pre-commit

For nano: nano .git/hooks/pre-commit

For VS Code: code .git/hooks/pre-commit

Or create and edit the file in whatever other way you like.

Code

#!/bin/bash

yarn lint
linting_result=$?

if [[ $linting_result -ne 0 ]]
then
  echo "LINT FAILED!"
  echo 'Please fix linting problems before committing.'
  exit 1
fi

yarn test
test_result=$?

if [[ $test_result -ne 0 ]]
then
  echo "TESTS FAILED!"
  echo 'Please make sure tests pass before committing.'
  exit 1
fi
Enter fullscreen mode Exit fullscreen mode

The yarn test and yarn lint commands work exactly the same as
they do when called from the command line at the root of my project.

I get the exit code and check to see if it equals zero here:

linting_result=$?

if [[ $linting_result -ne 0 ]]
Enter fullscreen mode Exit fullscreen mode

if it doesn't equal 0 (-ne 0), I echo a message
and exit the bash code with another non-zero exit code,

then
  echo "LINT FAILED!"
  echo 'Please fix linting problems before committing.'
  exit 1
fi
Enter fullscreen mode Exit fullscreen mode

If either the tests or the linter fail they exit
with a code of 1. But if it exits with a different code
I'd like to know why, so I exit with anything non-zero and don't
let the commit go forward.

Next steps

All you need to do now is run chmod +x .git/hooks/pre-commit, to make the code executable,
and the code will run on every commit.

Check out the documentation and add
whatever other hooks you like. I run the same code on push as well using
the pre-push hook for example

Top comments (0)