How to automatically append text to a git commit message

In our company, we are using a ticketing system that has Git integration. When commiting, you can reference the ticket with „refs #{Ticket-ID}“ and the ticket system automatically shows the commits that are conherent to the ticket. This is pretty simple to execute, but not everyone in the company uses it, because it gets forgotten most of the time, so I decided to write a script that automatically appends the text to a commit message, without anyone having to worry about it.

In our case, when creating feature branch we have a naming convention, that is defined as following feature/{Ticket-ID}_{Ticket-Name} which allows us to quickly find feature branches on a remote.

Now lets head to the script:

BRANCH=`git branch | grep '^\*' | cut -b3-`

echo "$1"
if [[ $BRANCH =~ $re ]];
echo "refs #"$BASH_REMATCH >> "$1";

Let me explain the script. This first two lines are simply getting the current name of the branch and defining a regex for finding the Ticket ID. The rest of the script simply checks whether the current branch name matches the regex, and if it does, adds „refs #{Ticket-ID}“ to the commit message. Otherwise, the original commit message will be used.

If you want to use this script, you have to navigate to your .git folder. Now create (if not exists) a hook folder and the folder/file

mkdir hooks && cd hooks && touch prepare-commit-msg && chmod a+x prepare-commit-msg && nano prepare-commit-msg

If you don’t have nano or don’t want to use it, forget the part after the last two ampersands and open the file how you like. Then copy the code from above into your that file, save it, and test it with a new commit. In my case it looks like this.

Screenshot 2015-07-22 16.50.16 Kopie

As you can see, I just added `test` as a commit message, however, the prepare-commit-msg hook automatically added refs #{Ticket-ID} to the message. Happy coding!

It's only fair to share...Share on FacebookTweet about this on TwitterShare on RedditEmail this to someoneShare on Tumblr

2 thoughts on “How to automatically append text to a git commit message

Leave a Comment

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert.