My Git Hooks, Part 1 - I Need a Hook

February 03, 2014

This is part one of my N-part (come on, I’m not planning this), slightly-too-elaborate git pre-commit hook story.

For reference, my git commit hooks repo is here, help yourself and follow along!

Origin

A while ago I noticed that every few months I (or my colleagues) repeated the same mistakes when committing code. Even our strict code review regimen (ah, those were the days! Don’t get me started…) wouldn’t prevent them. Most were either…

  • The kind of thing that was too easy to gloss over during a code review (“Oh, that? Yeah, that’s just debugging code. I’ll rip that out before I commit. Here, let me make a note of that…”), or
  • Version skew issues. For example, we were deploying to a Ruby 1.87 environment, but most of us used 1.9 locally, so things like JSON hash syntax and Hash#flatten kept slipping in.

I got tired of repeating them, so I decided to write some git hooks to stop it.

I Am a Ruby Developer, Right?

At the time I was focused on Ruby on Rails, so I decided to write them in Ruby. After all, a hook (especially a pre-commit hook) is just a script that lives in a predefined location and:

  1. (Optionally) examines the commit and any other information that it feels is necessary,
  2. (Optionally) prints any necessary diagnostics or other messages, and
  3. Returns a value, either 0 for success or non-zero for failure.

Well, a Ruby script can do all of that. Run some git code to look at the files (and lines) being changed, test some criteria (simple regexps at first; they got more complicated later), print any error messages, and return either 0 or 1? Easy-peasy!

Looking around a bit I found Henrik Nyh’s Ruby-based (and Ruby-centric) git pre-commit hooks on GitHub, and I was on my way.

Next

Next time I’ll get into some of the technical details of writing a git-commit hook, and a description of the basic implementation. Later I’ll go into more advanced topics, my distribution method, and per-project customization. Eventually I’ll get into incorporating this into a multi-project ecosystem.

Tags: git
comments powered by Disqus