Created
May 24, 2018 12:13
-
-
Save masives/58af0f7b5c2ee25fd6f5fbfb09b83551 to your computer and use it in GitHub Desktop.
precommit hook for eslint and stylelint
This file contains 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
#!/bin/bash | |
## PRECOMMIT LINTING | |
# list staged files | |
STAGED_FILES_TS="$(git diff --cached --name-only | grep "\.ts$")" | |
STAGED_FILES_SCSS="$(git diff --cached --name-only | grep "\.scss$")" | |
STAGED_FILES_VUE="$(git diff --cached --name-only | grep "\.vue$")" | |
# Define helper variables | |
PASS_LINT=true | |
PASS_STAGING_COMPARATION=true | |
RED='\033[41m' | |
GREEN='\033[0;32m' | |
NC='\033[0m' | |
printf "Running Linters: \n" | |
# # Run tslint for scss and get the output and return code | |
if [[ -n "$STAGED_FILES_TS" ]]; then | |
printf "Running tslint \n" | |
tslint=$(yarn tslint $STAGED_FILES_TS) | |
ret_code=$? | |
# If it didn't pass, announce it failed and print the output | |
if [ $ret_code != 0 ]; then | |
printf "${RED}tslint failed:${NC} \n" | |
printf "$tslint \n" | |
PASS_LINT=false | |
else | |
printf "${GREEN}tslint passed.${NC} \n" | |
fi | |
fi | |
# Run stylelint for scss and vue, get the output and return code | |
if [[ -n "$STAGED_FILES_SCSS" ]] || [[ -n "$STAGED_FILES_VUE" ]]; then | |
printf "Running stylelint \n" | |
stylelint=$(yarn stylelint $STAGED_FILES_SCSS $STAGED_FILES_VUE) | |
ret_code=$? | |
# If it didn't pass, announce it failed and print the output | |
if [ $ret_code != 0 ]; then | |
printf "${RED}Stylelint failed:${NC} \n" | |
printf "$stylelint \n" | |
PASS_LINT=false | |
else | |
printf "${GREEN}Stylelint passed.${NC} \n" | |
fi | |
fi | |
# Check if staged files differ from working tree | |
ALL_STAGED_FILES="$(git diff --cached --name-only)" | |
for file in $ALL_STAGED_FILES | |
do | |
compared_file=$(git diff --color --name-only $file) | |
if [[ -n $compared_file ]]; then | |
printf "${RED}Staged file differs from working directory:${NC} $file. \n" | |
PASS_STAGING_COMPARATION=false | |
fi | |
if $PASS_STAGING_COMPARATION; then | |
printf "${GREEN}Staged files don't differ from working directory${NC} \n" | |
fi | |
done | |
# Fail commit if necessary | |
if ! $PASS_LINT; then | |
printf "${RED}COMMIT FAILED:${NC} Your commit contains files that should pass ESLint but do not. Please fix the ESLint errors and try again. \n" | |
exit 1 | |
elif ! $PASS_STAGING_COMPARATION; then | |
printf "${RED}COMMIT FAILED:${NC} Your commit contains files that have been changed after staging. Please stage them and try again. \n" | |
exit 1 | |
else | |
printf "${GREEN}COMMIT SUCCEEDED${NC} \n" | |
fi | |
exit 0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment