Git commit hook to enforce JIRA issue number in commit messages

Has anyone set up a git commit hook that checks for a JIRA issue number in the commit message? I’m not familiar with linking JIRA and git commit hooks, so any guidance would be great. A working example would be even better!

I’ve implemented something similar at my workplace and found it to be a real game-changer for our workflow. We developed a pre-commit hook using Python, which offered more flexibility than a bash script. Our solution involved writing a script that checks the commit messages against our JIRA pattern, even going as far as integrating the ‘jira’ Python library to validate issue numbers against our instance. We also built in the ability to bypass the check for certain commit types like merges. The real improvement came when we combined this with a custom commit template that prompts developers to add the JIRA number from the very start. Documenting the process in our README also proved invaluable during onboarding.

I’ve implemented this at my company. We use a Python script for our pre-commit hook, which offers more flexibility than bash. Here’s a simplified version:

import re
import sys

commit_msg_file = sys.argv[1]
with open(commit_msg_file, 'r') as f:
    commit_msg = f.read()

if not re.search(r'PROJ-\d+', commit_msg):
    print('Error: Commit message must include JIRA issue number (e.g., PROJ-123)')
    sys.exit(1)

Save this as .git/hooks/commit-msg and make it executable. It checks for PROJ-XXX pattern in your commit messages. You can adjust the regex to match your JIRA project key. This approach allows for more complex logic if needed, like checking multiple JIRA projects or integrating with JIRA’s API to validate issue numbers.

yep, i’ve done this before. here’s a quick bash script for ur pre-commit hook:

#!/bin/bash
if ! grep -qE 'PROJ-[0-9]+' "$1"; then
  echo "Commit msg needs JIRA number (e.g. PROJ-123)"
  exit 1
fi

just put it in .git/hooks/pre-commit and make it executable. it’ll check for PROJ-XXX in ur commits.