Git Hooks- Automatically checking out a repository after pushing to it

I’ve been experimenting with file-based blogging software (namely Blosxom) lately, and I wanted to automatically transfer my university notes from my computer to my server. I also wanted to add some versioning for backup, so the obvious thing to do was to use Git.

Git Hooks are pretty easy to use. When creating a repository with git init, a folder hooks/ is automatically created within your .git/ directory, which contains sample/skeleton scripts for all available hooks. To enable a hook, you just set its executable bit using chmod +x hook-file.

For checking out my repository after pushing, I used the post-receive hook, so I added the following to the .git/hooks/post-receive file:

pwd = Dir.pwd
%x[echo "GIT_DIR = #{pwd} git checkout -f" 1>&2]
%x[GIT_DIR="#{pwd}" git checkout -f]

What the above Ruby code does is simple. It first stores the current working directory, which for a called hooks always seems to be the .git/ folder of the repository. Then it changes to the parent folder (the actual, checked out repository), and executes a git checkout -f there. Note that with the -f option will overwrite all modification in your repository, so be careful with that.

The GIT_DIR variable needs to be set, because git does not seem to automatically recognize the .git/ folder when called within a hook, which is probably due to some environment variable being or not being set. If someone knows the exact reason, feel free to drop a comment :)

More on Git hooks can be found here.