Jira ticket in Git commit message on OS X

  • by
Tools

Photo by Lachlan Donald on Unsplash

When working with Git and Jira (or any other issue tracker) sooner or later there comes a need to prefix git commit message with a ticket number. That way it’s faster to locate why a piece of code was written and it opens some opportunities for automation and tool integration.

What was I aiming for was that when I’m on a feature/TICKET-1234-name-of-the-branch branch then in each commit message I would have a prefix with ticket number and the rest of a message [TICKET-1234] Adds some super code. I know that git has hooks that allow for altering it’s behaviour and that one I’m looking for is commit-msg.

After some Googling I found a lot of answers … that did not work 😢 It turns out that tools installed on OS X differ from “normal” Linux ones and some other flags are needed to make them work. I will come clean I’m not a terminal guru and I didn’t wanted to became one over this. So after some fighting and trying and error here is a working combination for OS X:

#!/bin/bash

# get current branch
branchName=`git rev-parse --abbrev-ref HEAD`

# search jira issue id in a pattern such a "feature/ABC-123-description"
jiraId=$(echo $branchName | sed -nE 's,[a-z]+/([A-Z]+-[0-9]+)-.+,\1,p')

# only prepare commit message if pattern matched and jiraId was found

if [[ ! -z $jiraId ]]; then
    # $1 is the name of the file containing the commit message
    sed -i.bak -e "1s/^/[$jiraId] /" $1
fi

What you need to do is you have to add/edit project/.git/hooks/commit-msg and making sure that it’s exactable by running in terminal chmod +x commit-msg.

Test Drive

You can add a commit message using any GUI Git client:

or terminal:

Either way you will have a nice prefix commit message like so:

Take care and I wish you fast compiling code 😎

ps

You can download it from here: https://github.com/sloik/SloikPresentations/blob/master/TicketTagCommitMessage/commit-msg

Leave a Reply

Your email address will not be published. Required fields are marked *