Git pre-push hooks

I would like to run a unit-tests before every git push and if tests fails, cancel the push, but I can't even find pre-push hook, there is pre-commit and pre-rebase only.


Git got the pre-push hook in the 1.8.2 release.

Sample pre-push script: https://github.com/git/git/blob/87c86dd14abe8db7d00b0df5661ef8cf147a72a3/templates/hooks--pre-push.sample

1.8.2 release notes talking about the new pre-push hook: https://github.com/git/git/blob/master/Documentation/RelNotes/1.8.2.txt


Git got the pre-push hook in the 1.8.2 release.

Pre-push hooks are what I needed along with pre-commit hooks. Apart from protecting a branch, they can also provide extra security combined with pre-commit hooks.

And for an example on how to use (taken and adopted and enhanced from this nice entry)

Simple example to login to vagrant, run tests and then push

#!/bin/bash
# Run the following command in the root of your project to install this pre-push hook:
# cp git-hooks/pre-push .git/hooks/pre-push; chmod 700 .git/hooks/pre-push

CMD="ssh [email protected] -i ~/.vagrant.d/insecure_private_key 'cd /vagrant/tests; /vagrant/vendor/bin/phpunit'"
protected_branch='master'

# Check if we actually have commits to push
commits=`git log @{u}..`
if [ -z "$commits" ]; then
    exit 0
fi

current_branch=$(git symbolic-ref HEAD | sed -e 's,.*/\(.*\),\1,')

if [[ $current_branch = $protected_branch ]]; then
    eval $CMD
    RESULT=$?
    if [ $RESULT -ne 0 ]; then
        echo "failed $CMD"
        exit 1
    fi
fi
exit 0

As you can see the example uses a protected branch, subject of the pre-push hook.


If you are using the command line, the easiest way to do this is to write a push script that runs your unit tests and, if they succeed, completes the push.

Edit

As of git 1.8.2 this answer is outdated. See manojlds's answer above.