Skip to content

Instantly share code, notes, and snippets.

@geuis
Last active April 9, 2017 08:38
Show Gist options
  • Save geuis/1489bbd1a8e47e86db38 to your computer and use it in GitHub Desktop.
Save geuis/1489bbd1a8e47e86db38 to your computer and use it in GitHub Desktop.
Force jshint validation with pre-commit hook (bash)
#!/bin/sh
# Run changed javascript files through jshint before commiting and prevent bad
# code from being committed.
# If you need to prevent newly added js from being checked because its in a
# library like bower_components, add a .jshintignore file and list the directory
# INSTALL: Add as a file in your repo as .git/hooks/pre-commit
FILES=$(git diff --cached --name-only --diff-filter=ACM| grep ".js$")
if [ "$FILES" = "" ]; then
exit 0
fi
echo "\nValidating changed js files..."
pass=true
for file in ${FILES}; do
result=$(jshint ${file})
if [ "$result" != "" ]; then
echo 'failed\n'
echo "$result"
pass=false
fi
done
if ! $pass; then
exit 1
else
echo 'passed\n'
exit 0
fi
@anddoutoi
Copy link

A suggestion for improvement would be to throw in a git show :$(file) or something that makes sure it's actually linting the content that is staged and not the content on disk. If you git add something that contains errors, fix the errors but forgets to git add again you will commit errors.

@letsgetrandy
Copy link

+1 for linting the actual staged content. Had this become a problem in the past, where people would stage a broken change, fix it but fail to commit, and then push the broken change. Very frustrating.

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