‹‹ All posts

Pre-push hook to save yourself from breaking build

25 of February, 2014

In order to minimize risk of accidentally breaking build
As a developer
I want code style checks and automated tests to be run each time I push code into repository.

As far as I know pre-push hook is available in git since version 1.8.2. It lives in .git/hooks/pre-push and will run every time you push code:

$ git push
✔ PHPSpec
✔ Behat
Counting objects: 5, done.
Delta compression using up to 3 threads.
Compressing objects: 100% (5/5), done.
Writing objects: 100% (5/5), 562 bytes | 0 bytes/s, done.
Total 5 (delta 4), reused 0 (delta 0)
To [email protected]:company/project.git
   642d074..aa8daff  develop -> develop

If script exits with error state then git command is aborted. Here is example script which would run php code style fixer, phpspec and behat on vagrant virtual machine:


runViaVagrant() {
    vagrant ssh -c "cd /mnt/project && $2 > /dev/null"
    if [ $? -ne 0 ]
        echo " ✘ $1 has failed - push aborted"
        exit 1
        echo " ✔ $1"

# go to project root
cd ./$(git rev-parse --show-cdup)/

# run scripts
runViaVagrant 'PHPCS' './bin/php-cs-fixer fix --quiet --dry-run src'
runViaVagrant 'PHPSpec' './bin/phpspec run --quiet'
runViaVagrant 'Behat' './bin/behat'

# success
exit 0

In this example I used sample vagrant box for php projects (available from my github repository).

comments powered by Disqus