Auto Add Jira Ticket ID to Commit Messages

At work, we prefix all commit messages with the ID of the Jira ticket that we’re working on. For over a year I did this manually, dutifully adding [NOW-xxx] to the start of every Git message that I wrote.

Sometimes I forgot to add the Jira ticket ID, or I entered it wrong. This required me to rewrite history to fix my mistake.

After doing this one too many times I decided that there must be a better way.

Enter Git Hooks.

Git Hooks allow us to define scripts that should be run at given points during the Git lifecycle.

Originally I thought that I could use a Git hook to block any commit that didn’t contain a Jira ticket ID. But then I realised that all our branch names contain the Jira ticket ID (eg. feature/NOW-123-some-feature), so I could actually validate that the ticket ID that I’d typed in was the actual one for the task I was working on.

Then I realised that I could just make the Git hook automatically prepend the Jira ticket ID instead of having to type it manually.

So I wrote this shell script (I’m on a Mac) to run as the Git commit-msg Hook. It finds the current Git branch that you’re on, extracts the Jira ticket ID from the branch name (if there is one) and then prepends it to the commit message if the message doesn’t already contain it.

#!/bin/sh

COMMIT_MSG_FILE_PATH=$1
EXISTING_COMMIT_MSG=$(cat $1)
JIRA_ID=$(git rev-parse --abbrev-ref HEAD | grep -Eo "[A-Z0-9]{1,10}-?[A-Z0-9]+-\d+")

if [ ! -z "$JIRA_ID" ]; then
    # Only add the Jira ticket ID if it wasn't already supplied
    if [[ $EXISTING_COMMIT_MSG != *"$JIRA_ID"* ]]; then
        echo "[$JIRA_ID] $EXISTING_COMMIT_MSG" > $COMMIT_MSG_FILE_PATH
    fi
fi

To use this script, we need to add a folder in our home directory to use as the container for our custom Git hooks:

mkdir -p ~/global-git/hooks

Then we create a new file using the script above as ~/global-git/hooks/commit-msg (note the lack of a file extension) and make it executable:

chmod +x ~/global-git/hooks/commit-msg

Once this is done, we need to tell Git to use our custom Git hooks:

git config --global core.hooksPath ~/global-git/hooks

And we’re done!

Note that we can also use Git hooks for many other useful things. One commonly used hook is pre-commit which can be used to compile or run unit tests and block any code changes that fail to build from being committed.