Search code examples
gitremote-servergithooks

Git post-receive hook fails to checkout, fatal: You are on a branch yet to be born


On my server, in /home/user/git/domain.com.git/, I ran git init --bare, then created post-receive file in hooks dir & chmod +x hooks/post-receive. I used ls -la to verify it is executable.

My post-receive file:

mkdir /home/USER/pub/domain.com
GIT_WORK_TREE=/home/USER/pub/domain.com git checkout -f
GIT_WORK_TREE=/home/USER/pub/domain.com git reset --hard

I execute git push remotename branchname from local and get the error:

remote: fatal: You are on a branch yet to be born

It also shows:

To ssh://domain.com/~/git/domain.com.git
   oldcommithash..newhash  branchname -> branchname

I know the post-receive hook is running because my mkdir gives me a directory already exists error, which is to be expected and causes no problems on my other sites using this setup.

I also have this problem with git push remotename HEAD which is what I want to use, ultimately, for simpler scripting.


Solution

  • My latest hooks/post-receive script, which will update /home/user/PATH with the most recent push.

    #!/bin/bash
    
    user=REMOTE_USER_NAME
    path=pub/domain.com
    
    # Loop over all pushed branches
    c=0;
    while read oldrev newrev refname
    do
        # track count of branches
        c=$((c + 1))
        branch=$(git rev-parse --symbolic --abbrev-ref "$refname")
    done
    # If more than one branch was pushed, give an error & return
    if [[ $c -gt 1 ]];then
        echo ""
        echo "Multiple branches were pushed. Cannot update remote site."
        echo ""
        return;
    fi
    # Make the directory. Gives an error if it exists, but who cares?
    mkdir "/home/${user}/${path}"
    
    # Checkout the pushed branch & reset --hard
    GIT_WORK_TREE="/home/${user}/${path}" git checkout -f "${branch}"
    GIT_WORK_TREE="/home/${user}/${path}" git reset --hard
    

    References