If your team uses Jira and follows a branch naming convention like PROJ-123-my-feature, you can automate prepending the issue key to every commit message with a simple git hook.

Setup

1. Create the hooks directory

mkdir -p ~/.git_template/hooks

2. Create the prepare-commit-msg hook

Create ~/.git_template/hooks/prepare-commit-msg with the following content:

#!/bin/bash

# Get the current branch name
BRANCH_NAME=$(git symbolic-ref --short HEAD)

# Extract the Jira issue key (e.g., PROJ-123) from the branch name
ISSUE_KEY=$(echo "$BRANCH_NAME" | grep -oE '[A-Z]{2,}-[0-9]+')

# If we found a key and it's not already in the commit message, prepend it
if [ -n "$ISSUE_KEY" ]; then
  COMMIT_MSG=$(cat "$1")
  if [[ "$COMMIT_MSG" != *"$ISSUE_KEY"* ]]; then
    echo "$ISSUE_KEY: $COMMIT_MSG" > "$1"
  fi
fi

3. Make it executable

chmod +x ~/.git_template/hooks/prepare-commit-msg

4. Configure git to use the template

Add this to your ~/.gitconfig:

[init]
  templatedir = ~/.git_template

How it works

The hook fires before the commit message editor opens. It extracts any pattern matching [A-Z]{2,}-[0-9]+ from the branch name and prepends it to your message. So if you’re on branch PROJ-123-add-login and commit with message “Add login form”, the final message becomes:

PROJ-123: Add login form

The hook is automatically copied into every new repository you git init. For existing repositories, just run git init again in the project directory to copy the template hooks.

Credit: Jonathan Doklovic