Automatically add JIRA number to commit messages

Tom Dane
2 min readNov 21, 2020

--

Do you ever forget to add the JIRA number to your commit message? The following steps will do it automatically if your branch name includes the ticket, e.g. JIRA-1234.

Installation

  • Create a folder called ‘githooks’ somewhere in your repository. For example, in the root
  • In this folder, create a file called prepare-commit-msg (no extension)
  • In this file, copy the bash script below
  • Once you’ve saved the file, update your Makefile or similar to copy the githooks/prepare-commit-msg file into <project root>/.git/hooks/
  • Alternatively, if your app is not using husky or other libraries that depend on hooks, you can enable it per repo by navigating to the repo and typing `git config core.hooksPath ThePathToYourFolder`
  • Verify with `git config core.hooksPath`

Bash script

#!/bin/bash# Get the current branch name
BRANCH_NAME=$(git symbolic-ref --short HEAD)
# Get the JIRA number
JIRA=$(echo $BRANCH_NAME | grep -o -E '[0-9A-Z]+-[0-9]+')
#Check if this a normal commit, or an amend
IS_NORMAL_COMMIT=$(grep -c "$JIRA" $1)
# Prepend the JIRA number to the commit message
if [ -n "$JIRA" ] && [ "$IS_NORMAL_COMMIT" -eq 0 ]; then
sed -i.bak -e "1s/^/$JIRA /" $1
fi

Usage

  • Commit changes as normal. For example: `git commit -m “Add this new feature”`
  • This works for branches in the format “JIRA-1234-My-Branch” or “someText/JIRA-1234-My-Branch”.
  • If you commit to a branch that does not match this format (for example, “master”), the script will do nothing.

Known issues

  • If you are using WSL and Bash on Windows, you might receive the error: “$’ :\r’: command not found”. This is due to windows line endings. Here is a solution

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Tom Dane
Tom Dane

No responses yet

Write a response