How to get my branch name from a pre-receive hook?

Viewed 3076

I am working with GitHub enterprise and I don't have permissions to upload new pre-receive hooks to our repo.

I tried to test my hook as a pre-push hook and it was working like a charm, but when I sent my hook to our admin he said: "The GitHub pre-receive-hook script is different with git pre-receive-hook script. The git symbolic-ref --short HEAD may not work as your expected"

So I need to find a way to replace this command:

current_branch=$(git symbolic-ref --short HEAD) || exit 1

To a command that will save my current branch inside "current_branch" parameter?

How do I do that without the ability to test it?

2 Answers

Actually, when using the stdin you can get the CURRENT_BRANCH from the 1st argument "$refname" :

while read oldrev newrev refname; do
    echo "$refname : $oldrev ~ $newrev"
done

If you want to chop and clean it using sed you can just add this:

while read oldrev newrev refname; do
    echo "$refname : $oldrev ~ $newrev"
    current_branch=$refname
    short_current_branch="$(echo $current_branch | sed 's/refs\/heads\///g')"
done

And you will get just the name of the branch inside a parameter (short_current_branch)

enter image description here

A pre-receive hook is a hook running in a different Git. Your current branch in your Git is irrelevant, and in a pre-receive hook, their Git's current branch is irrelevant too. Whatever your actual task is, using "the current branch" is going to be wrong.

(Their Git's current branch may be relevant in a post-receive hook, if that hook's job is to deploy updates to the current branch. However, note that receiving Gits are generally configured as "bare" repositories.)

Related