#!/bin/bash

# This is the git pre-commit hook.    It is executed when you run "git commit",
# and it looks at all the python files in a git repository.   If any of them have
# a "test" function, it executes it.
# 
# If the test method fails, the commit is aborted.

PYTHONPATH=".:lib:$PYTHONPATH"
export PYTHONPATH

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

for f in $(git diff-index --name-only $against)
do
    q=$(basename "$f" .py)
    if egrep '^def[[:space:]]{1,}test\(' "$f"
    then
      echo "Testing module ${f}.test"
      if ! python -c "import $q; $q.test()"
      then
        echo "Fail on ${f}.test"
        exit 1
      fi
    fi
    if egrep '^def[[:space:]]{1,}_test\(' "$f"
    then
      echo "Testing module ${f}._test"
      if ! python -c "import $q; $q._test()"
      then
        echo "Fail on ${f}._test"
        exit 1
      fi
    fi
done
