Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Git pre-commit hook to perform linting on only the changes which will be committed.
#!/bin/bash
#
# A hook script to perform linting before allowing a commit,
# to avoid unnecessary noise or extra work to rebase commits.
# Based on: http://stackoverflow.com/a/20480591/1435658
# Necessary to support .nvm and gitx
export PATH=/usr/local/bin/:$PATH
# First, stash index and work dir, keeping only the
# to-be-committed changes in the working directory.
# Will also stash uncommitted files
old_stash=$(git rev-parse -q --verify refs/stash)
git stash save -q -u --keep-index
new_stash=$(git rev-parse -q --verify refs/stash)
# If there were no changes (e.g., `--amend` or `--allow-empty`)
# then nothing was stashed, and we should skip everything,
# including the tests themselves. (Presumably the tests passed
# on the previous commit, so there is no need to re-run them.)
if [ "$old_stash" = "$new_stash" ]; then
echo "pre-commit script: no changes to test"
sleep 1 # XXX hack, editor may erase message
exit 0
fi
# Run npm linting script (`eslint .`)
npm run lint -s
status=$?
# Restore changes
git reset --hard -q && git stash apply --index -q && git stash drop -q
# Exit with status from test-run: nonzero prevents commit
exit $status
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.