Skip to content

Instantly share code, notes, and snippets.

@andybee
Created August 10, 2017 11:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andybee/2869555da42e76844940ad3975d68ce3 to your computer and use it in GitHub Desktop.
Save andybee/2869555da42e76844940ad3975d68ce3 to your computer and use it in GitHub Desktop.
Pre-commit hook for linting JS with ESLint before committing
#!/bin/sh
STAGED_FILES=$(git diff --cached --name-only --diff-filter=ACM | grep -v "^node_modules/" | grep ".jsx\{0,1\}$")
ESLINT="$(git rev-parse --show-toplevel)/node_modules/.bin/eslint"
if [[ "$STAGED_FILES" = "" ]]; then
exit 0
fi
PASS=true
# provide notice that linting is in progress, can be quite slow
echo "\nLinting JavaScript..."
# check for ESLint
if [[ ! -x "$ESLINT" ]]; then
echo "\033[41m\`node_modules/.bin/eslint\` not found\033[0m have you run \`npm install\`?\n"
exit 1
fi
# run all staged JS/JSX files through ESLint
for FILE in $STAGED_FILES
do
"$ESLINT" "$FILE"
if [[ "$?" != 0 ]]; then
PASS=false
fi
done
# provide result
if ! $PASS; then
echo "\n\033[41mCommit Failed\033[0m Your commit contains files that should pass ESLint but do not. Please fix the ESLint errors and try again.\n"
exit 1
else
echo "Linting OK\n"
fi
exit $?
@andybee
Copy link
Author

andybee commented Aug 10, 2017

This is a variant of a script I found by shettyrahul8june.

Main changes were to reduce the amount of output for my personal preferences (I just wanted to know it was in progress and ESLint was already returning detailed errors for each problem including a filename).

I also added a filter for node_modules from the staged files because of an internal company policy to commit the node_modules folder and, even though ESLint is set to ignore it, it slows the hook process down attempting and error'ing them.

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