Git pre-push hooks Git pre-push hooks git git

Git pre-push hooks


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-pushCMD="ssh vagrant@192.168.33.10 -i ~/.vagrant.d/insecure_private_key 'cd /vagrant/tests; /vagrant/vendor/bin/phpunit'"protected_branch='master'# Check if we actually have commits to pushcommits=`git log @{u}..`if [ -z "$commits" ]; then    exit 0ficurrent_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    fifiexit 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.