Preventing commits on a Git production branch

Posted on Monday, July 9th, 2012 at 09:00, under tech. Tags: ,

This post has been originally written for the Headshift Labs blog and is posted here with permission.

~

A fairly common Git workflow – and the one we tend to use at Dachis Group in London – makes use of 3 remote branches: master for development, staging and production to deploy to the staging and production servers.

We talked about this workflow in a previous post. The gist of it is: changes are always committed to the master branch. When it’s time for a deploy, they are merged into the deployment branch (let’s say staging), pushed and delivered to the server using Capistrano.

When using this workflow, commits should always happen on the master branch. However, swinging from branch to branch can sometimes fool even the best of us into thinking we are committing to master when we are actually still on staging.

To put an end to this mild annoyance, I’ve put together a simple Git hook. It’s supposed to work on pre-commit (that is, it runs before you even write your commit message). All it does is make the commit command fail if the current branch is either staging or production.

You can see the code and usage documentation in this gist: Git hook to prevent commits on a staging/production branch

As an aside, it’s worth noting that sometimes you do need to commit to a deployment branch: hotfixes are a case where solving an issue quickly trumps having a spotless process. In these situations, the hook can be skipped by using the Git --no-verify option.