Find Git branch name in post-update hook [duplicate]
Asked Answered
C

1

38

I'm executing a programme to alert CruiseControl each time an update is sent to our remote repository. I'm using a Git post-update hook for this.

It would be great if I could find out which branch had been committed so I could use that to inform CruiseControl which branch to build. Is there any way to access the branch name within a post-update hook?

Coulter answered 7/9, 2011 at 9:25 Comment(0)
F
51

The first parameter to the post-update hook is the branch reference in full - for instance I see 'refs/heads/master' for a push to 'origin master'. So an example hook script that just prints the branch modified is:

#!/bin/sh
branch=$(git rev-parse --symbolic --abbrev-ref $1)
echo Update pushed to branch $branch
exec git update-server-info

To illustrate, when the above is placed into your remote repository hooks/post-update file the following is printed when performing a push:

% git push origin master
Counting objects: 5, done
Writing objects: 100% (3/3), 247 bytes, done.
Total 3 (delta 0), reused 0 (delta 0)
Unpacking objects: 100% (3/3), done.
remote: Update pushed to branch master
To /tmp/xx/a
    e02d9cd..ab14a08  master -> master

The new line beginning 'remote:' was output by our hook script.

Fifty answered 7/9, 2011 at 10:21 Comment(10)
Thanks, Patthoyts. Using the above code, I'm getting "remote: hooks/post-update: line 8: branch: command not found". anchCoulter
I provided an extended sample. You need the #!/bin/sh line at the start still. Also, when you do set a variable in a shell script use $ to access the valueFifty
Wayhey! That's done it. Thanks very much patthoyts.Coulter
Just curious: why --symbolic and --abbrev-ref? It seems to work fine without the --symbolic on the few instances I've tried.Rotorua
For those environments where $1 isn't populated, see pauljz's answer here: #7352051Mudlark
Note that that link is to a post-receive hook and this answer was for a post-update hook. They handle the inputs differently. Post-update hooks get command line arguments while post-receive hooks get provided with arguments on stdin.Fifty
Thanks for this! One thing I didn't understand: Why are you running exec git update-server-info as the last statement in the post-update hook? Is this because the repository is accessible via HTTP?Wightman
@Leif: Yes. And because that command was already in the hook script. The update-server-info was just for the HTTP access and I think for gitweb as well.Fifty
@patthoyts: Aha, okay, I see. Thanks for confirming my assumption :)Wightman
Since I found this while looking for git docs because this is the first result on google, I'll just leave a link to the docs which specify how all hooks are invoked here: git-scm.com/docs/githooksStereography

© 2022 - 2024 — McMap. All rights reserved.