Git Tip: Auto update working tree via post-receive hook

Posted by Felix Geisendörfer, on Dec 26, 2008 - in Tools

Oh, this one took me a while to figure out. Lets say you want to setup a git repository on your server that whenever you push into it updates its working tree. Why? Well, because this can be a very convenient workflow for a small project where you want to be able to quickly push changes out without any fancy deploy mechanism.

My first attempt was to do this on the server:

chmod +x .git/hooks/post-receive

And then put this into the post-receive hook file itself:

#!/bin/sh
cd ..
git reset --hard

However, this would always give me an error like this when trying to push:

$ git push
Counting objects: 5, done.
Compressing objects: 100% (2/2), done.
Writing objects: 100% (3/3), 372 bytes, done.
Total 3 (delta 0), reused 0 (delta 0)
To machine:/repo/path
   122a0cc..747f3d8  master -> master
fatal: Not a git repository: '.'
error: hooks/post-receive exited with error code 128

The solution? It turns out the post-receive hook starts out with the GIT_DIR environment variable set to the repo/.git folder, so no matter what path you 'cd' into it will always try to run any following git commands there. Fixing this is simply a matter of unsetting the GIT_DIR:

#!/bin/sh
unset GIT_DIR
cd ..
git reset --hard

Voila, a quick and dirty-git repository that updates its own working tree upon push!

-- Felix Geisendörfer aka the_undefined

Another issue you might want to watch out for: Depending on the user doing the push and the permission / ownership settings on the working tree you may have to become a little more tricky using a sudo -u command and an entry in your sudoers file.

Print this Post | Digg This | Stumble It | Delicious

Older blog posts

« Previous
1 | 2 | 3 | 4 | 5 | 6 | 7 | 8