Writing a git post-receive hook to deal with a specific branch

Here's my current hook in a bare repo that lives in the company's server: git push origin master This hooks pushes to Assembla. What i need is to push only one branch (master, ideally) when someone pushes changes to that branch on our server, and ignore pushes to other branches. Is it possible to select the branch from a bare repo and push only that branch to Assembla?


Solution 1:

A post-receive hook gets its arguments from stdin, in the form:

<oldrev> <newrev> <refname>

Since these arguments are coming from stdin, not from a command line argument, you need to use read instead of $1 $2 $3.

The post-receive hook can receive multiple branches at once (for example if someone does a git push --all), so we also need to wrap the read in a while loop.

A working snippet looks something like this:

#!/bin/bash
while read oldrev newrev refname
do
    branch=$(git rev-parse --symbolic --abbrev-ref $refname)
    if [ "master" = "$branch" ]; then
        # Do something
    fi
done

Solution 2:

The last parameter that a post-receive hook gets on stdin is what ref was changed, so we can use that to check if that value was "refs/heads/master." A bit of ruby similar to what I use in a post-receive hook:

STDIN.each do |line|
    (old_rev, new_rev, ref_name) = line.split
    if ref_name =~ /master/
         # do your push
    end
end

Note that it gets a line for each ref that was pushed, so if you pushed more than just master, it will still work.

Solution 3:

Stefan's answer didn't 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"