Add JIRA Ticket Numbers to Git Commits using git hooks
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 ticket (handles feature/PROJ-1234, PROJ-1234, etc)
TICKET=$(echo "$BRANCH_NAME" | grep -Eo '[A-Za-z]+-[0-9]+' | head -n 1 | tr '[:lower:]' '[:upper:]')
# Only modify if a ticket was found and it's not already in the commit message
if [[ -n "$TICKET" && "$MESSAGE" != "$TICKET"* ]]; then
echo "$TICKET$SEPARATOR$MESSAGE" > "$FILE"
fi
This shell script extracts the JIRA ticket number from your branch name and appends it to your commit message.