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 $?
@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