Steve Pulec home

Why You Need a Git Pre-Commit Hook and Why Most Are Wrong

This post is republished from the Yipit Django Blog

03 Mar 2012 – New York

A pre-commit hook is a piece of code that runs before every commit and determines whether or not the commit should be accepted. Think of it as the gatekeeper to your codebase.

Want to ensure you didn’t accidentally leave any PDBs in your code? Pre-commit hook. Want to make sure your javascript is JSHint approved? Pre-commit hook. Want to guarantee clean, readable PEP8 -compliant code? Pre-commit hook. Want to pipe all of the comments in your codebase through Strunk & White? Please don’t.

The pre-commit hook is just an executable file that runs before every commit. If it exits with zero status, the commit is accepted. If it exits with a non-zero status, the commit is rejected. (Note: A pre-commit hook can be bypassed by passing the `—no-verify` argument.)

Along with the pre-commit hook there are numerous other git hooks that are available: post-commit, post-merge, pre-receive, and others that can be found here.

Why Most Pre-Commit Hooks are Wrong
Be wary of the above’s example as the majority of pre-commit hooks you’ll see on the web are wrong. Most test against whatever files are currently on disk, not what is in the staging
area (the files actually being committed).

We avoid this in our hook by stashing all changes that are not part of the staging area before running our checks and then popping the changes afterwards. This is very important because a file could be fine on disk while the changes that are being committed are wrong.

The code below is the pre-commit hook we use at Yipit. Our hook is simply a set of checks to be run against any files that have been modified in this commit. Each check can be configured to include/exclude particular types of files. It is designed for a Django environment, but should be adaptable to other environments with minor changes. Note that you need git 1.7.7+

To use this hook or a hook that you create yourself, simply copy the file to .git/hooks/pre-commit inside of your project and make sure that it is executable or add in to your git repo and setup a symlink.

Steve Pulec is a Developer at Yipit.

Fork me on GitHub