Add JIRA Ticket Numbers to Git Commits using git hooks

X @urre

Why

At work we use JIRA and usually use a consistent branch naming system where all branches and commits should include the ticket name.

For example branches looks like this:

feature/dev/PROJ-1234-branch-name-example

and commits:

PROJ-1234 Fix tests

Setting up the Git Hook

Go to the git hooks directory inside your repo.

cd .git/hooks/

Create a file called prepare-commit-msg

touch .git/hooks/prepare-commit-msg

Make it executable.

chmod +x .git/hooks/prepare-commit-msg

Add the script

Open prepare-commit-msg in your editor and paste the following script:

#!/bin/bash

# Create .git/hooks/prepare-commit-msg
# Run before using: chmod +x prepare-commit-msg

# Example: If the branch is called ex feature/dev/PROJ-1234-branch-name-example or
# feature/PROJ-6789/PROJ-1234-another-branch-name-example
# then the commit will be "PROJ-1234 Your commit message"

FILE=$1
MESSAGE=$(cat "$FILE")
BRANCH_NAME=$(git rev-parse --abbrev-ref HEAD)
SEPARATOR=" "

# Extract the ticket number from the branch name
TICKET=$(echo "$BRANCH_NAME" | grep -Eo '(\w+/)?(\w+/)?(\w+[-_])?[0-9]+' | grep -Eo '(\w+[-])?[0-9]+' | tail -n 1 | tr "[:lower:]" "[:upper:]")

if [[ "$TICKET" == "[]" || "$MESSAGE" == "$TICKET"* ]]; then
    exit 0
fi

echo "$TICKET$SEPARATOR$MESSAGE" > "$FILE"

This shell script extracts the JIRA ticket number from your branch name and appends it to your commit message.

Enjoy!