Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Git: how to check out the currently pushed branch in the pre-push hook?

Tags:

git

githooks

In my project I have a pre-push git hook that runs unit tests on every push.

But when I try to push changes from one branch while staying at another one, the unit tests will be run for the active branch, not for the currently pushed one.

For example, if I try to push changes from my new_feature branch while my working directory reflects the structure of the develop branch, the pre-push hook will run the unit tests for the develop branch, not for the new_feature.

The basic idea to get rid of this is to make a checkout of the currently pushed branch in the pre-push hook. But I have no idea how to get information about currently pushed branch inside the hook: this information is not contained in the hook arguments.

like image 463
Dmitry Sapelnikov Avatar asked Nov 18 '13 10:11

Dmitry Sapelnikov


1 Answers

From the manual of githooks:

Information about what is to be pushed is provided on the hook's standard input
with lines of the form:

   <local ref> SP <local sha1> SP <remote ref> SP <remote sha1> LF

For instance, if the command git push origin master:foreign were run the hook would
receive a line like the following:

   refs/heads/master 67890 refs/heads/foreign 12345

although the full, 40-character SHA-1s would be supplied.

in which is exactly the branch you are pushing. With it you can checkout and test in that working tree.

Here is a sample hook-script:

#!/bin/sh

z40=0000000000000000000000000000000000000000

IFS=' '
while read local_ref local_sha remote_ref remote_sha
do
    current_sha1=$(git rev-parse HEAD)
    current_branch=$(git rev-parse --abbrev-ref HEAD)
    if [ "$local_sha" != $z40 ] && [ "$local_sha" != "$current_sha1" ]; then
        git checkout $local_sha

        # do unit testing...

        git checkout $current_branch
    fi
done

exit 0
like image 182
dyng Avatar answered Sep 23 '22 14:09

dyng