Tuesday, November 22, 2011

How to use git hooks to enforce relating commits to issues on github

Recently my team has been trying to take advantage of some of the issue and planning features github offers.  We've been using github's issue tracking for a while and we really like how easy it is to tie commits to issues.  We thought we could provide more visibility to the rest of our company and have smaller, more direct commits if we were more disciplined about tying commits to issues at commit time.

This is really easy to do using git hooks.  Simply create a file named commit-msg in repo\.git\hooks and paste in the following code:

#!/bin/sh
if git-rev-parse --verify HEAD >/dev/null 2>&1; then
    against=HEAD
else
    against=4b825dc642cb6eb9a060e54bf8d69288fbee4904
fi
if grep -i 'gh-[0-9]\+' $1 > /dev/null 2>&1; then
  exit 0
else
  echo COMMIT REJECTED BY "commit-msg" HOOK:
  echo Commit log must close or mention a github issue \(use "closes GH-9999" or "mentions gh-9999"\)
  exit 1
fi

That will just make sure that gh-### appears in the commit message somewhere.  If you need to commit something and it doesn't make sense to tie it to an issue, just add the --no-verify flag to the commit line.  It's been working really well for us so far.