Automatically Prefix JIRA Issue ID to Git Commit Messages using Git Hooks
Red Headphone
Posted on February 23, 2024
In software development teams, efficient communication and tracking are paramount. Integrating JIRA, a popular issue tracking tool, with Git commits streamlines this process. In this guide, we'll walk through automating the prefixing of JIRA issue IDs to Git commit messages, ensuring clarity and traceability in your project history.
Step 1: Creating the Prepare Commit Message Hook
To automate the prefixing process, we'll utilize Git hooks, specifically the prepare-commit-msg hook. This hook is triggered before a commit message is finalized. Follow these steps:
- Create the Hook File: Navigate to your project's
.git/hooks
directory and create a new file namedprepare-commit-msg
. - Make the File Executable: Ensure the file is executable by running
chmod +x .git/hooks/prepare-commit-msg
in your terminal. - Paste the Python Script: Inside
prepare-commit-msg
, paste the following Python script:
#!/usr/bin/env python3
import sys
import re
from subprocess import check_output
commit_msg_filepath = sys.argv[1]
branch = check_output(
["git", "symbolic-ref", "--short", "HEAD"]
).strip().decode()
regex = "[A-Z]{2,7}-[0-9]{1,5}"
if branch.count("-") >= 2:
if re.match(regex, branch):
with open(commit_msg_filepath, "r+") as fh:
commit_msg = fh.read()
fh.seek(0, 0)
fh.write("#%s %s" % (branch, commit_msg))
This script fetches the current branch name, checks if it follows the pattern of a JIRA issue ID, and prefixes the commit message accordingly.
Step 2: Testing the Integration
With the hook in place, every commit made on a branch named after a JIRA issue (eg. TEMP-9999
) will automatically have the issue ID prefixed to the commit message.
Conclusion
By automating the prefixing of JIRA issue IDs to Git commit messages, teams can ensure consistency and improve traceability in their project history. This integration enhances collaboration and facilitates smoother project management workflows, so you can focus on writing code.
Posted on February 23, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.