Add Jira Issue Number to Git Commit Message

Add Jira Issue Number to Git Commit Message

Recently, I have been working on a project with the Atlassian toolchain which includes: Jira (Issue Tracking), Stash (git), Bamboo (Continous Integration – build and deploy) and Confluence (Wiki).

In Stash using the Yet Another Commit Checker plugin can ensure that every git commit messages pushed to the server has a valid Jira issue number. Configuring the plugin is simple, in this example the project uses the prefix ‘DS’, issue numbers will look like: DS-123, DS-145, DS-432.

Yet Another Commit Checker

Now the responsibility is on the developer to make sure he adds that commit number. This can be tedious so I decided to try to automate it.

First, I added a simple script to reject commits that do not have the correct issue number. Below is this first effort in .git/hooks/commit-msg. For more info on how git’s pre-commit hooks work see Customizing Git – Git Hooks

#!/bin/sh
#
# This example tests that the commit message contains DS, exit 1 will fail the commit.
test "" != "$(grep '\[DS-[0-9]\+\]' "$1")" || {
  echo >&2 "ERROR: Commit message is missing Jira issue number."
  exit 1
}

This worked for a month until I was tired of typing in the issue number at all. In Jira and Stash, the branch names are standardized when you create the branch directly from the Jira ticket. For example, a feature for issue DS-215 would have branch name like feature/DS-215-cors. Fortunately, I work a smart co-worker and he wrote me 2 nice shell functions to strip the issue number out of the branch name. I revised my .git/hooks/commit-msg to look like this:

#!/bin/sh

# Add git branch if relevant
parse_git_branch() {
  git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/(\1)/'
}

# Extact tracker abbreviation and ticket number (e.g. DS-123)
parse_git_tracker_and_ticket() {
  parse_git_branch | grep -e '[A-Z]\+-[0-9]\+' -o
}

MESSAGE="$(cat $1)"
TICKET=`parse_git_tracker_and_ticket`

if [ -n "$TICKET" ]
then
   echo "New commit message: [$TICKET] $MESSAGE"
   echo "[$TICKET] $MESSAGE" > $1
fi