Skip to content

Instantly share code, notes, and snippets.

@posquit0
Last active October 10, 2023 13:39
Show Gist options
  • Save posquit0/b6eea4273868f0da707c9719a9ea59ad to your computer and use it in GitHub Desktop.
Save posquit0/b6eea4273868f0da707c9719a9ea59ad to your computer and use it in GitHub Desktop.
Git Pre Commit Hook for ESLint and Jest
#!/usr/bin/env bash
STAGED_FILES=$(git diff --cached --name-only --diff-filter=ACM | grep '\.jsx\?$')
BIN_PATH="$(git rev-parse --show-toplevel)/node_modules/.bin"
eslint() {
ESLINT="$BIN_PATH/eslint"
# Check for eslint
if [[ ! -x "$ESLINT" ]]; then
printf "\t\033[41mPlease install ESLint\033[0m\n"
exit 1
fi
echo "Linting modified files"
echo $STAGED_FILES | xargs $ESLINT
if [[ $? == 0 ]]; then
printf "\n\033[1;32mLint Passed\033[0m\n"
else
printf "\n\033[41mLint Failed:\033[0m Fix lint errors and try again!\n"
exit 1
fi
}
jest() {
JEST="$BIN_PATH/jest"
# Check for jest
if [[ ! -x "$JEST" ]]; then
printf "\t\033[41mPlease install Jest\033[0m\n"
exit 1
fi
echo "Testing related to modified files"
$JEST --bail --findRelatedTests $STAGED_FILES
if [[ $? == 0 ]]; then
printf "\n\033[1;32mTest Passed\033[0m\n"
else
printf "\n\033[41mTest Failed:\033[0m Fix test errors and try again!\n"
exit 1
fi
}
# Exit if no files modified
if [[ "$STAGED_FILES" = "" ]]; then
exit 0
fi
eslint
jest
exit $?
@posquit0
Copy link
Author

Put this file to .git/hooks/pre-commit

@brennanforgues
Copy link

brennanforgues commented Nov 15, 2017

Works well, thx. Small typo in the comment where you check for jest.
# Check for jest

@pratyushcrd
Copy link

pratyushcrd commented Dec 21, 2017

Thanks for script posquit0.

If adding the file directly doesn't works, do: chmod +x ./.git/hooks/pre-commit
I faced a issue where I pre-commit hooks weren't executing. Directly copying the file or copying it over by script might not give the file execute permissions.

@elyobo
Copy link

elyobo commented Mar 4, 2018

This article shows an arguably better approach, as the use of lint-staged and husky avoids a lot of boilerplate and also means that any user that clones the repo for a project will get the behaviour without having to set up their precommit hooks.

@sammysium
Copy link

how would this work with coverage threshold? like for commit to fail if test coverage is below certain percentage?

@aclarknexient
Copy link

This gist helped me to write a new hook, thank you for sharing it, I really appreciate you doing that!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment