Automatically add JIRA ticket ID to your commit messages

JIRA by Atlassian is one of the most popular product development tools out there. One of the great features it provides is tracking progress of given ticket via commits on Bitbucket. For example, if there is a JIRA Ticket BUG-5, all the commits and branches tagged with BUG-5 ([BUG-5] for the commits) will show up on the JIRA ticket status sidebar. To make it even easier, JIRA provides a simple create a branch button on the ticket, which creates a branch using the ticket id and the title of the ticket. As a result, the branch appears on the sidebar.

Having the ticket ID in the branch name is great, but we can take it even further by tagging our commits with the ticket ID. We can enter it into our git commit messages manually every time, or just automate it for us. To do that, we shall use git hooks. Git hooks are scripts which get triggered based on some git events (i.e. pre-commit). We will use the .prepare-commit-msg git hook, to append the ticket ID to our git message.

Simply add following to your .git/hooks/prepare-commit-msg file (create one if does not exists)

BRANCH=$(git rev-parse --abbrev-ref HEAD | grep -o '^[A-Za-z]*-[0-9]*')
grep -qs "^$BRANCH" "$1" || echo "[$BRANCH] $(cat $1)" > "$1"

The first line, simply gets us the ticket id, and the second line prepends the ID to our git message. Note, I am assuming JIRA default behaviour for ticket ID and branch generation.

That is it. You can find out more about git hooks here.

- Doniyor Ulmasov