-
-
Save posquit0/b6eea4273868f0da707c9719a9ea59ad to your computer and use it in GitHub Desktop.
#!/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 $? |
Works well, thx. Small typo in the comment where you check for jest.
# Check for jest
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.
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.
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!!
Put this file to
.git/hooks/pre-commit