Last active
October 10, 2023 13:39
-
-
Save posquit0/b6eea4273868f0da707c9719a9ea59ad to your computer and use it in GitHub Desktop.
Git Pre Commit Hook for ESLint and Jest
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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 $? |
how would this work with coverage threshold? like for commit to fail if test coverage is below certain percentage?
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
This article shows an arguably better approach, as the use of
lint-staged
andhusky
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.