Tips&Tricks - Adding a prefix to git commits automatically

This time I decided to write something, which is not Azure related, yet some people should find it interesting. To make a long story short - when working in a team using a git repository, we often agree on different kind of conventions, which help in keeping it clean and allow for easy integration with other tools(like issue trackers). The downside of such agreement is mainly a need to remember all structures and prefixes. In this post I show you how automate at least part of it - it's not something brand new, still I tried to present something elegant and easy to use.

git hooks

git has many cool features and hooks are one of them. If you haven't heards about them -  those are simple scripts written in shell(though you can use other languages like Python also), which are executed at the specific moment while working with your repository(like opening a commit message window). To make hooks working, they have to have a specific filename and must be stored in `.git/hooks` directory of your repository.

To start working with git hooks the easiest way is to initialize a dummy repository:

/
$ git init

and then go to `.git/hooks` repository and copy full content of the directory. When you open any file, you should see an example of a hook with some comments. Take your time and read them carefully since most of them provide some useful information.

Modifying a commit message

This time we'd like to modify a commit message. There are a few hooks, which could help here, but I decided to go for prepare-commit-message. I won't go into details here why this particular hooks has been chosen by me - commit-msg would fit here also. Personally I found it the most semantically correct for my purposes.

To modify a commit message you could use following shell script:

/
BRANCH=`git branch | grep '^\*' | cut -d '/' -f 2`
TASK=`echo $BRANCH | cut -d '-' -f 1,2`

echo -e "[$TASK] \n$(cat $1)" > $1

This script fetches a branch name, splits it and extracts two values from an array(which in my case are the project identifier and a task number). Let's say you have following branch name:

/
feature/TIMP-1-this-is-my-project-one

if you go to your git client and create a commit with a message This is my message!, you'll get following result:

/
[TIMP-1] This is my message!

How cool is that?

Enabling git hooks

All right, actually I lied a little - having only a script won't make, that a hook works. What you have to do is the following:

  • make sure a hook has a correct name(without .sample extension)
  • lies in .git/hooks directory

Using a script from an example your .git folder should contain following file:

  • .git
    • hooks
      • prepare-commit-msg

Now it should work flawlessly.

Summary

git hooks are great way to automate many things related to your daily work with a git repository. I strongly encourage you to dive deeper into this topic and automate as many things as you can.