Question

I am trying to set up a pre-commit hook to test my project before any commit goes through, but I can't find how to make sure that only HEAD (with patches from the current commit) are tested and not the current working_tree (which in most cases is dirty for me).

Solutions found:

Found this link and ended up doing the following.

http://newartisans.com/2009/02/building-a-better-pre-commit-hook-for-git/

# Checkout a copy of the current index into MIRROR
git checkout-index --prefix=$TMPDIR/ -af

# Remove files from MIRROR which are no longer present in the index
git diff-index --cached --name-only --diff-filter=D -z HEAD | \
   (cd $TMPDIR && xargs -0 rm -f --)
Was it helpful?

Solution

Going to depend on what you are actually verifying and testing. So if you are trying to see if some content is not being in the files checked in you have to do git diff --cached and not git diffso that you will get the appropriate changes. Similarly, you will have to see what commands you are using and so on.

For the unit test thing, I can suggest something like this ( there will be other ways too):

Write a post-commit ( not a pre-commit) hook like so:

#!/bin/sh
git stash
#run unit tests
#if tests fail
git stash pop --index
git reset --soft HEAD~1 
exit 0   # if tests pass

Alternative using pre-commit would be to checkout the index into a separate directory, run the tests from there. Have a look at git checkout-index. I haven't used it in this way, so cannot comment further on it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top