Garrett Murphey

Ruby & JavaScript Developer

Grunt Pre-Commit Hook for Release Tasks

Posted on December 22, 2012

I’m always forgetting to run release tasks when committing to Git, and then I’m forced to either rewrite history and merge commits or roll back and re-commit. It’s a big time sink. Thankfully, I’ve been playing with Grunt tasks and Git pre-commit hooks and found a way to not only save time and my sanity, but take release tasks out of my manual workflow entirely. This hook will stash any work that’s not staged, run the release task, stage any files updated by the task and restore any stashed files.

In the pre-commit hook (.git/hooks/pre-commit):

#!/bin/sh
# stash unstaged changes, run release task, stage release updates and restore stashed files

NAME=$(git branch | grep '*' | sed 's/* //')

# don't run on rebase
if [ $NAME != '(no branch)' ]
then
  git stash -q --keep-index
  grunt release

  RETVAL=$?

  if [ $RETVAL -ne 0 ]
  then
    exit 1
  fi

  git add .
  git stash pop -q
fi

And in your Grunt config:

grunt.registerTask('release', ['lint', 'qunit', 'concat', 'min']);

Never commit linting errors or failing tests again, and you won’t worry about run build tasks from now on.