Preventing Bad Commit Messages with Git Hooks

I always forget to write good git commit messages, it's just not something I've ever been able to prioritise in my mind. Today I setup a tool that will forcibly stop me from doing that: a git message hook.

Preventing Bad Commit Messages with Git Hooks

An easy solution to a simple problem: when I write a new commit message, if it doesn't have a ticket reference it will be declined. Here's how I did it.

First up, you need to create a template directory for your git hooks.

mkdir -p ~/.git_templates/hooks/

Once you've created your directory create the file commit-msg in your hooks directory. The contents of the file should be as follows:

#!/bin/bash

COMMIT_MESSAGE="$1"

if ! grep -qE "^TIK-\d{1,10}:" "$COMMIT_MESSAGE";then
    echo "Your commit message must contain a valid ticket reference."
    exit 1
fi

Finally, we just need to set our git config and make the file executable.

git config --global init.templatedir "~/.git_templates"
chmod a+x ~/.git_templates/hooks/commit-msg

If you want to test it, open up an existing git repository and run git init which should install your hook from the templates directory. All new repos that you clone or init will have the template hooks as well. If you want a full example to test, try this:

# Open a new shell or source your ~/.zshrc or ~/.bashrc

$ mkdir git-commit-testing
$ cd git-commit-testing/  
$ git init
Initialized empty Git repository in /tmp/git-commit-testing/.git/
$ touch test.txt
$ git add test.txt 
$ git commit -m "This is a test."
Your commit message must contain a valid ticket reference.
$ git commit -m "ENG-9654: This is a test."
[master (root-commit) 6de3047] TIK-9654: This is a test.
 1 file changed, 0 insertions(+), 0 deletions(-)
 create mode 100644 test.txt

That's it! Now you're on the path to better commit messages. If you'd like to contact me, feel free to send me a message on Twitter @stophammotime.