Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
git hook for commit-msg to use ESLint as a soft guard of code quality (lets things pass if the committer is committed to committing)
#!/bin/bash
# Uses ESLint as a soft guard of code quality for your repo
# allows commits to go through if re-attempted within a pre-set interval
# copy to .git/hooks/commit-msg to have things work
# Based on: https://gist.github.com/wesbos/8aec9d2ff7f7cf9dd65ca2c20d5dfc23
PRESET_TIME_INTERVAL=60
LAST_RUN_DATE_FILE="$HOME/.eslint.commit-msg-hook.last-failed-run"
if [ ! -f $LAST_RUN_DATE_FILE ] ; then
echo "0" > $LAST_RUN_DATE_FILE
fi
# because somehow /usr/local/bin might not be on the path
PATH=$PATH:/usr/local/bin:/usr/local/sbin
CURR_EPOCH=$(date +%s)
LAST_RUN_EPOCH=$(cat $LAST_RUN_DATE_FILE)
TIME_DIFFERENCE_IN_SEC=$(expr $CURR_EPOCH - $LAST_RUN_EPOCH)
files=$(git diff --cached --name-only | grep '\.jsx\?$')
# Prevent ESLint help message if no files matched
if [[ $files = "" ]] ; then
exit 0
fi
failed=0
for file in ${files}; do
git show :$file | eslint $file
if [[ $? != 0 ]] ; then
failed=1
fi
done;
if [[ $failed != 0 ]] ; then
echo "💩💩💩 ESLint failed."
if [ "$TIME_DIFFERENCE_IN_SEC" -ge $PRESET_TIME_INTERVAL ]; then
echo "🚫🚫🚫 git commit denied!"
echo "Attempt to commit again within $PRESET_TIME_INTERVAL seconds and the commit will succeed.";
echo "... and please ensure that there are no syntax errors if you do so.";
date +%s > $LAST_RUN_DATE_FILE
exit $failed
else
echo "Current commit attempt is within $PRESET_TIME_INTERVAL seconds of last failed attempt.";
echo "😡😡😡 git commit reluctantly allowed.";
echo "0" > $LAST_RUN_DATE_FILE
fi
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment