17

I've got a post receive hook setup on the remote repo that tries to determine the branch name of the incoming push as follows:

$branch = `git rev-parse --abbrev-ref HEAD`

What i'm finding, though, is that no matter what branch I push from my $branch variable gets set with 'master'.

Any ideas?

jsleeuw
  • 283
  • 5
  • 13

5 Answers5

26

The post-receive hook gets the same data as the pre-receive and not as arguments, but from stdin. The following is sent for all refs:

oldRev (space) newRev (space) refName (Line feed)

You could parse out the ref name with this bash script:

while read oldrev newrev ref
do
    echo "$ref"
done
rtn
  • 127,556
  • 20
  • 111
  • 121
  • 3
    except beware if `post-receive` is receiving a `git push --tags` for example (and probably `git push origin my_tagname`) then the `ref` you'll be getting is `refs/tags/my_tagname` and *not* `refs/branch/my_branchname` – iainH Jul 12 '15 at 15:09
  • How can I switch to the previous commit, in **post-receive** hook? – Kiran Reddy Sep 04 '18 at 06:30
10

You could also do something like this using bash variable substitution:

read oldrev newrev ref

branchname=${ref#refs/heads/}

git checkout ${branchname}
Dave Augustus
  • 101
  • 1
  • 2
2

Magnus' solution didnt work for me, but this did:

#!/bin/bash

echo "determining branch"

if ! [ -t 0 ]; then
  read -a ref
fi

IFS='/' read -ra REF <<< "${ref[2]}"
branch="${REF[2]}"

if [ "master" == "$branch" ]; then
  echo 'master was pushed'
fi

if [ "staging" == "$branch" ]; then
  echo 'staging was pushed'
fi

echo "done"
Dean Rather
  • 31,756
  • 15
  • 66
  • 72
  • 1
    That's because you are looking for the word master, but what you received was refs/head/master. Using read you turned the string into an array delimited by '/'. Then you plucked out the value. – Cameron Lowell Palmer Sep 12 '12 at 13:35
  • Hi Can you help on how to add `and` condition in `if` like `if ["master" == "$branch" && "development"=="$branch"]`. How to use and condition in this if in hook. Advance thanks. – Foolish Jun 23 '15 at 17:48
2

Both these answers are correct, but I was having trouble getting stdin to the next common function post-receive-email. Here is what I ended up with:

read oldrev newrev ref
echo "$oldrev" "$newrev" "$ref" | . /usr/share/git-core/contrib/hooks/post-receive-email


if [ "refs/heads/qa" == "$ref" ]; then
  # Big Tuna YO!
  wget -q -O - --connect-timeout=2 http://127.0.0.1:3000/hooks/build/qa_now
fi
earlonrails
  • 4,966
  • 3
  • 32
  • 47
1

You need to read the arguments that are being passed to the script. That should have the branch name and new and old revisions and run for each branch pushed

Adam Dymitruk
  • 124,556
  • 26
  • 146
  • 141