Search code examples
gitgithooksgit-post-receive

Git hooks, post-receive loop through commit


Using git hooks on the server side, is it possible to loop through the new commit messages that were sent from the client to the server everytime someone pushes to the remote repository?

I need to extract information from each message,

hash,date,commit author,branch

I cant find any good documentation on git hooks figure it out. I've read through git post-receive hook that grabs commit messages and posts back to URL

and I don't understand a simple line of code


Solution

  • As is explained in the githooks man page, the post-receive hook gets a line for each ref, containing

    <old-value> SP <new-value> SP <ref-name> LF

    where <old-value> is the old object name stored in the ref, <new-value> is the new object name to be stored in the ref and <ref-name> is the full name of the ref.

    So, if you put this in .git/hooks/post-receive:

    #!/bin/sh
    while read oldvalue newvalue refname
    do
       git log -1 --format='%H,%cd,%an' $newvalue
       git branch --contains $newvalue | cut -d' ' -f2
    done
    

    The while statement makes it loop over each line, reading the three fields from the line into the variables $oldvalue, $newvalue and $refname

    The git log line will output hash,date,commit author to standard out.

    The git branch line will try to output the branch. (Alternatively you could use echo $refname, which will output in the format refs/heads/master)