DavidWaldo
DavidWaldo

Reputation: 735

Git post-recieve hook

I need help with writing a git post-receive hook.

I need the hook to call external .exe file and pass in parameters.

This is my hook so far:

#!/bin/sh

call_external()
{
     # --- Arguments
     oldrev=$(git rev-parse $1)
     newrev=$(git rev-parse $2)
     refname="$3"

     DIR="$(cd "$(dirname "$0")" && pwd)"

     $DIR/post-receive.d/External.exe
 }

 # --- Main loop


while read oldrev newrev refname
do
    call_external  $oldrev $newrev $refname 
done

It works just fine, except I need to pass some parameters to that exe, and I do not know how to get them from Git.

Thanks to 'phd' heres the update: I need these parameters per every commit in the push

I have no idea how to get this info from GIT.

Edit(2021-04-22) Thanks to 'phd' I was able to put together

#!/bin/sh
call_external()
{
    # --- Arguments
    oldrev=$(git rev-parse $1)
    newrev=$(git rev-parse $2)
    refname="$3"
    
    if [ $(git rev-parse --is-bare-repository) = true ]
    then
        REPOSITORY_BASENAME=$(basename "$PWD") 
    else
        REPOSITORY_BASENAME=$(basename $(readlink -nf "$PWD"/..))
    fi
    
    DIR="$(cd "$(dirname "$0")" && pwd)"
    BRANCH=$refname

    git rev-list "$oldrev..$newrev"|
    while read hash 
    do
    
        COMMIT_HASH=$hash
        AUTHOR_NAME=$(git show --format="%an" -s)
        AUTHOR_EMAIL=$(git show --format="%ae" -s)
        COMMIT_MESSAGE=$(git show --format="%B" -s)
    
        $($DIR/post-receive.d/External.exe "$BRANCH" "$AUTHOR_NAME" "$AUTHOR_EMAIL" "$COMMIT_MESSAGE" "$COMMIT_HASH" "$REPOSITORY_BASENAME")
        
    done
}

 # --- Main loop
while read oldrev newrev refname
do
    call_external  $oldrev $newrev $refname 
done

Upvotes: 1

Views: 158

Answers (1)

phd
phd

Reputation: 94483

I need these parameters per every commit in the push

Commit hash

Run the following loop:

git rev-list oldrev..newrev | while read hash; do echo $hash; done

Inside the loop $hash is the hash of one commit.

Author/Email

That's git show --format="%an" -s and git show --format="%ae" -s. %an means "author's name", %ae — "author's email". See the list of placeholders at https://git-scm.com/docs/git-show#_pretty_formats

Commit description

git show --format="%B" -s. That's "full body of the commit message". Can be split into %s and %b.

Branch name

You don't need it in a loop, you always have it. The post-receive hook is called when updating a reference, the reference is the branch. refname in your script.

Let's me combine all this into one loop:

git rev-list oldrev..newrev |
while read hash; do
    echo Commit hash: $hash
    echo Author name: git show --format="%an" -s
    echo Author email: git show --format="%ae" -s
    echo Commit message: git show --format="%B" -s
done

Upvotes: 2

Related Questions