Git has a very nice set of example hooks that you can find just by creating a new repo. The following is an easy way to see them all:
[code language=”shell”]
mkdir myrepo
cd myrepo
git init
ls .git/hooks/
[/code]
If you do that you will end up with a list something like this:
[code language=”text”]
applypatch-msg.sample post-commit.sample post-update.sample pre-commit.sample pre-rebase.sample
commit-msg.sample post-receive.sample pre-applypatch.sample prepare-commit-msg.sample update.sample
[/code]
I recently did this thinking I would create a pre-receive hook. Since there isn’t a sample for pre-receive I went to the git hooks reference to see if there was anything special I needed to know. I didn’t pay any attention to the fact that git will send something in on STDIN when it runs the hook and as it turns out that is important. In some instances if you don’t read STDIN you will get an error message like the following when you try to push and the hook gets used:
[code language=”text”]
fatal: The remote end hung up unexpectedly
error: error in sideband demultiplexer
error: died of signal 13
[/code]
The fix for this is to make sure you read STDIN when creating pre-receive and post-receive hooks. The following example shell script will show the commit information for each new revision id when you push and the hook is executed:
[code language=”shell”]
#!/bin/sh
while read oldrev newrev refname
do
# Do something with $oldrev $newrev $refname
git show –no-color –root -s –pretty=medium $newrev
done
[/code]
The key part in the above is the “while read” that reads STDIN. So whatever language you write your hook in just make sure you read everything from STDIN before completing the script.