A Use For Git's Post-Commit Hook


[Authored by Sam]

I love git and I love to be lazy, so lately I’ve been playing with git hooks.

Git’s default pre-commit hook is really handy, but today I’m in more of a post-commit kind of mood.  Like all git’s hooks it comes with an example script.

This one isn’t particularly useful.  It evaluates Nothing and returns a successful exit code.  Big deal.

Git’s default post-commit hook.

#!/bin/sh
#
# An example hook script that is called after a successful
# commit is made.
#
# To enable this hook, make this file executable.

: Nothing

 

Enabling this git hook is as easy as making the file executable.

chmod a+x .git/hooks/post-commit

But that doesn’t change the fact that it does nothing.

I’m also a big fan of rtags.  It lets you jump directly to where a method is defined with one keystroke.  Sometimes though I forget to reindex my tag file for a while and I get the dreaded “tag not found” message.  Then I have to spend 30 seconds running the reindex command.  Fear no more, git hooks to the rescue.

A post-commit script for reindexing rtags.

#!/bin/bash
#
# git post-commit hook
#
# reindex rtags in the background after a successful commit
# remove --vi switch for emacs style tagfile
#
# To enable this hook, make this file executable.

echo "reindexing rtags"
rtags --vi -qR > /dev/null &

So that was fun.  Now my rtags file is always up to date with my last commit.

But you may be saying, “What do I care about rtags?  I use TextMate and rtags only works with cool-kids editors like vi and emacs.”  Well, I have one more post-commit trick up my sleave.  Say after each commit you want to run your tests, unobtrusively in the background, and have Growl (you’re on OS X right?) warn you if you’ve checked in code with failing tests.

Run your tests after you commit and notify you unobtrusively using OS X growlnotify.

#!/bin/bash
#
# git post-commit hook
# run tests after a commit and let me know if I checked
# in failing code before I break the build for everybody
#
# requires growlnotify
#
if rake > /dev/null 2>&1
then
  growlnotify -m 'All tests passed'
else
  growlnotify -sm 'Oops! Looks like you committed with failing tests.'
fi &

Anyone with any git hook gems, feel free to comment.