How To Prefix Your Commit Message With a Ticket Number Automatically

Practical use-case for the prepare-commit-msg git hook

Photo by Paulette Wooten on Unsplash

You don’t have to enter the ticket number manually for each commit!

Once the branch name contains that reference, you can set up the git hook to do it for you!

Git allows you to intercept the commit message using the prepare-commit-msg hook.

This hook is an executable file that Git calls right before the commit. It takes a single argument — the target filename that contains the commit message.

# GIT executes the prepare-commit-msg hook internally like: $ .git/hooks/prepare-commit-msg .git/COMMIT_EDITMSG

The task is to prepare a custom message based on the branch name and write it back to the .git/COMMIT_EDITMSG file.

Here’s an example implementation in bash:

#!/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

The TICKET variable contains an extracted ticket number in brackets, like:

myproj-123-some-feature → [MYPROJ-123]

→ feature/myproj-456-some-other-feature → [MYPROJ-456]

→ bugifx/myproj-789 → [MYPROJ-789]

→ 123_some_feature → [123]

OK, now copy the script and place it in your-repo/.git/hooks/prepare-commit-msg and make it an executable file using the chmod command: chmod +x your-repo/.git/hooks/prepare-commit-msg .

See it in action:

Ticket number auto-generated using inline commit.

Ticket number auto-generated in the text editor (commit without -m switch).

You may have noticed the condition:

if [[ $TICKET == "[]" || "$MESSAGE" == "$TICKET"* ]]

This is to guard against: