Git Commit Message Hook to Add Jira Ticket Number


It is a common practice to prepend ticket numbers to commit messages. To automate this I use a git hook. If the branch name contains a ticket number then the hook will prefix the message with the ticket number.

The commit message "add csv export functionality" becomes "ABC-1234 add csv export functionality".

1. Create a directory to hold the global hooks:

1
mkdir -p ~/.git-templates/hooks

2. Create the hook

Create the file inside the hooks directory

1
vim ~/.git-templates/hooks/prepare-commit-msg

and paste the script in it. I’m using vim here, feel free to use your favorite editor.

1
2
3
4
5
6
7
8
9
#!/bin/bash
FILE=$1
MESSAGE=$(cat $FILE)
TICKET=$(git rev-parse --abbrev-ref HEAD | grep -Eo '^(\w+/)?(\w+[-_])?[0-9]+' | grep -Eo '(\w+[-])?[0-9]+' | tr "[:lower:]" "[:upper:]")
if [[ $TICKET == "" || "$MESSAGE" == "$TICKET"* ]];then
  exit 0;
fi

echo "$TICKET $MESSAGE" > $FILE

4. Make sure the hook is executable.

1
chmod a+x ~/.git-templates/hooks/prepare-commit-msg

5. Configure git’s global template directory:

1
git config --global init.templatedir '~/.git-templates'

6. Re-initialize git in each existing repo you’d like to use this hook in:

1
git init

Leave a comment