Skip to content

Instantly share code, notes, and snippets.

@damian
Created November 18, 2011 16:02
Show Gist options
  • Save damian/1376854 to your computer and use it in GitHub Desktop.
Save damian/1376854 to your computer and use it in GitHub Desktop.
Git pre-commit hook
#!/bin/sh
# A JavaScript focussed git pre-commit hook
#
# It ensures that any files containing console.log() or alert() calls aren't able to be committed.
# It also ensures that all JavaScript passes JSHint(which is assumed to be installed). A static code analysis tool which detects errors and potential issues from smelly JS - see http://www.jshint.com/ for more details
#
# Written by Damian Nicholson - @damian
if git rev-parse --verify HEAD >/dev/null 2>&1
then
against=HEAD
else
# Initial commit: diff against an empty tree object
against=4b825dc642cb6eb9a060e54bf8d69288fbee4904
fi
# Setting up error counters
SYNTAX_ERROR_COUNT=0
NAUGHTY_JS_COUNT=0
# Find all javascript files in the diff
for FILE in `git diff-index --name-only ${against} -- | grep "\.js"`; do
# Prevent any console.log() or alerts from being committed
naughty_stuff=`grep -inR "console\.\|alert(" ${FILE}`
# TODO: Find a better way to determine the count of naughty js left in
naughty_stuff_length=`echo ${#naughty_stuff}`
naughty_stuff_count=`echo ${naughty_stuff} | wc -l`
if [ ${naughty_stuff_length} -ne 0 -a ${naughty_stuff_count} -ne 0 ]; then
NAUGHTY_JS_COUNT=`expr $NAUGHTY_JS_COUNT + 1`
echo "$FILE: line $naughty_stuff"
fi
# Run the jshint tool against it
lint=`jshint ${FILE}`
# If jshint returns a none empty string print out the error and increment
# the error count
if [ ${#lint} -ne 0 ]; then
echo ${lint}
SYNTAX_ERROR_COUNT=`expr $SYNTAX_ERROR_COUNT + 1`
fi
done
echo "\n"
if [ ${SYNTAX_ERROR_COUNT} -ne 0 ]; then
echo "$SYNTAX_ERROR_COUNT syntax errors."
fi
if [ ${NAUGHTY_JS_COUNT} -ne 0 ]; then
echo "$NAUGHTY_JS_COUNT instances of console.log() or alert() found."
fi
# If any error count isn't zero - no dice
if [ ${NAUGHTY_JS_COUNT} -ne 0 ] || [ ${SYNTAX_ERROR_COUNT} -ne 0 ]; then
exit 1;
fi
exit 0;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment