0

I'm experimenting with git hooks, and am trying to get the git server I am using to host my code to perform a build after every pushed commit. I have cloned a local (on the server) git repository from the server-repository I am hosting. Both the server-repository and the server's local instantiation of the repo are on the same machine, the server. I use this local instantiation to perform the build.

Currently I am using the post-update git hook to run the following script after each new push to the repository:

#!/bin/sh

#get the branch name that was pushed
branch=$(git rev-parse --symbolic --abbrev-ref $1)

echo performing a build on branch:   $branch

cd /path/to/server/local/repodir
git checkout -f $branch
git pull origin $branch

make

echo "Build Done"

I am able to run the git hook, and it actually builds everything fine. However, the git checkout and pull commands fail, and give the following exception:

fatal: not a git repository: '.'

I'm not sure why this is happening, as I cd into the git directory the command before. Running this same script in the terminal on the server runs fine and git performs the actions as it normally would. I have checked by typing in pwd and ls -la in the hook and the shell is in the correct folder and has a .git repository item in it, meaning git should have no problem executing in this folder.

Is there something particular about git hooks that is preventing git from checking-out and pulling these repos that were just pushed from another device? I wouldn't think so, but I can't understand why git can't seem to find the git repository, and seems to only be looking at '.'

What is the proper way to git checkout/pull inside of a git hook?

stillQuestioning
  • 105
  • 3
  • 10

1 Answers1

1

When you operate on a hook, certain environment variables, such as GIT_DIR and possibly GIT_WORK_TREE, are set in the repository so that the hook works properly. If you're working in a different repository, you need to unset those variables, because they will no longer reflect the proper repository.

So, for example, you could do this:

#!/bin/sh

#get the branch name that was pushed
branch=$(git rev-parse --symbolic --abbrev-ref $1)

echo performing a build on branch:   $branch

(
    unset $(env | sed -ne 's/^\(GIT_.*\)=.*/\1/p')
    cd /path/to/server/local/repodir
    git checkout -f $branch
    git pull origin $branch

    make
)

echo "Build Done"

Note the unset command and the subshell.

bk2204
  • 64,793
  • 6
  • 84
  • 100