Adding Ticket Numbers To Git Commit Messages

Jan 28, 2014   #git 

We are using Redmine for tracking our programming tasks in my current project. Like most other ticketing systems, it has the ability to link commits in your source code repositories to a ticket when the commit message refers the ticket number.

Changes foo to bar because of baz. refs #1234

I became tired of adding the ticket number manually to each commit message. Fortunately, git can add the number by itself with the help of a little hook and a naming convention for your feature branches.

Your feature branch name should include the ticket number like so: ticket-1234-awesome-feature

Now create the file .git/hooks/commit-msg in your local repository with the following content:

#!/bin/sh ticket=$(git symbolic-ref HEAD | awk -F- '/ticket-/ {print $2}') if [ -n "$ticket" ]; then echo "\nrefs #$ticket" >> $1 fi

This extracts the ticket number from the branch name. The ticket number is then appended to your commit message on each commit when git executes the hook.