Skip to content

Instantly share code, notes, and snippets.

@msiemens
Last active February 26, 2017 02:33
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save msiemens/6278378 to your computer and use it in GitHub Desktop.
Save msiemens/6278378 to your computer and use it in GitHub Desktop.
My git pre-commit hook
#!/bin/bash
# Git pre-commit hook
#####################
#
# - check for whitespace problems (trailing spaces, ...)
# - check for lines with 'FIXME'
# - running tests
# - running code style check (pep8) on modified files
# - designed for Windows, for Linux replace `> NUL` with `> /dev/null`
########################################################################
# Check, if any changes have been made
changes_count=$(git diff --cached | wc -l)
if [ "$changes_count" -ne "0" ]; then
########################################################################
# Check for whitespace errors
git diff --cached --check # Check for whitespace errors
code=$?
if [ "$code" -ne "0" ]; then
echo
echo "Your changes introduced whitespace errors!"
exit $code
fi;
########################################################################
# Check for 'FIXME' lines
todo_lines=$(git diff --cached | grep ^+ | grep -v pre-commit | grep FIXME | sed 's_^+\s*__g')
if [ "$todo_lines" != "" ]; then
echo "You probably didn't want to commit these lines:"
echo -e "$todo_lines"
exit 1
fi
########################################################################
# Run tests
old_stash=$(git rev-parse -q --verify refs/stash)
git stash save -q --keep-index
new_stash=$(git rev-parse -q --verify refs/stash)
if [ "$old_stash" != "$new_stash" ]; then
# Python 2
echo "Running tests... (Python 2)"
py.test --color yes
code=$?
if [ "$code" -eq "0" ]; then
echo
echo
echo "All tests passed. Continuing..."
echo
else
echo
echo
echo "Please (re)check tests!"
fi;
if [ "$code" -ne "0" ]; then
git stash pop -q
exit $code
fi;
# Python 3
echo "Running tests... (Python 3)"
py.test-3.4 --color yes
code=$?
if [ "$code" -eq "0" ]; then
echo
echo
echo "All tests passed. Continuing..."
echo
else
echo
echo
echo "Please (re)check tests!"
fi;
if [ "$code" -ne "0" ]; then
git stash pop -q
exit $code
fi;
else
echo "No changes to test"
exit 0
fi
########################################################################
# Run code style check
echo "Running code style check..."
modified_files=$(git diff --cached --name-status | grep -v ^D | awk '$1 $2 { print $2}' | grep -e .py$)
if [ -n "$modified_files" ]; then
pep8 -r $modified_files
fi
git stash pop -q
if [ "$?" -eq "0" ]; then
echo
echo
echo "Code style is okay. Continuing..."
else
echo
echo
echo "Please consider cleaning up your code!"
sleep 5
fi;
fi;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment