Skip to content

Instantly share code, notes, and snippets.

@mirismaili
Last active June 21, 2021 08:08
Show Gist options
  • Save mirismaili/54abf152192205cf615ec1ec90518fd9 to your computer and use it in GitHub Desktop.
Save mirismaili/54abf152192205cf615ec1ec90518fd9 to your computer and use it in GitHub Desktop.
Es-lint precommit hook
#!/bin/bash
# Created on 1400/3/31 (2021/6/21).
# Author: [S. Mahdi Mir-Ismaili](https://mirismaili.github.io)
# Based on: https://gist.github.com/linhmtran168/2286aeafe747e78f53bf
STAGED_FILES=$(git diff --cached --name-only --diff-filter=ACM | grep ".jsx\{0,1\}$")
if [[ "$STAGED_FILES" == "" ]]; then
exit 0
fi
# Colors and styles based on: https://www.npmjs.com/package/ansi-colors-and-styles
T="\x1b[0m" # RESET
B="\x1b[1m" # BRIGHT
I="\x1b[2m" # DIM
U="\x1b[4m" # UNDERSCORE
N="\x1b[5m" # BLINK
V="\x1b[7m" # REVERSE
H="\x1b[8m" # HIDDEN
K="\x1b[30m" # FG_BLACK
R="\x1b[31m" # FG_RED
G="\x1b[32m" # FG_GREEN
Y="\x1b[33m" # FG_YELLOW
E="\x1b[34m" # FG_BLUE
M="\x1b[35m" # FG_MAGENTA
C="\x1b[36m" # FG_CYAN
W="\x1b[37m" # FG_WHITE
_K="\x1b[40m" # BG_BLACK
_R="\x1b[41m" # BG_RED
_G="\x1b[42m" # BG_GREEN
_Y="\x1b[43m" # BG_YELLOW
_E="\x1b[44m" # BG_BLUE
_M="\x1b[45m" # BG_MAGENTA
_C="\x1b[46m" # BG_CYAN
_W="\x1b[47m" # BG_WHITE
PASS=true
# Check for eslint
PATH=$PWD/node_modules/.bin:$PATH
which eslint &>/dev/null
if [[ "$?" == 1 ]]; then
echo -e "\t${_R}Please install eslint${T}"
exit 1
fi
echo -e "\nValidating Javascript:\n"
for FILE in $STAGED_FILES; do
eslint --max-warnings=0 "$FILE" # "--max-warnings=0" => throws on warnings (like errors)
if mycmd; then
echo -e "\t${G}ESLint Passed: $FILE${T}"
else
echo -e "\t${R}ESLint Failed: $FILE${T}"
PASS=false
fi
done
echo -e "\nJavascript validation completed!\n"
if ! $PASS; then
echo -e "${_R}${W}${B}COMMIT FAILED:\n"
echo -e "Your commit contains files that should pass ESLint but do not. "
echo -e "Please fix the ESLint errors and try again.${T}\n"
exit 1
else
echo -e "${_G}COMMIT SUCCEEDED${T}\n"
fi
exit $?
@mirismaili
Copy link
Author

Put it as pre-commit in .git/hooks/

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