Git pre-push hooks

前端 未结 7 1306
慢半拍i
慢半拍i 2020-11-28 02:47

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.

7条回答
  •  孤街浪徒
    2020-11-28 03:29

    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 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 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.

提交回复
热议问题