Git Hook commit -msg Use Case

Introduction

git the open source version control tool is the most widely used software for source code management.

In this article, we will see, how we can prevent the wrong format of commits. And how can we manage the format of commit message, which can be easy to read and point to a ticket/feature/fix, whenever developer wants to make a commit.

Pre-requisites

Developer should have knowledge of git.

To allow this way of approach, we can use the git hook feature.

Git hook is nothing but which will have some scripted files in .git/hooks/ folder. Which will trigger/execute automatically when there is a particular event happening in git. Which script has to trigger will be addressed by an action that is performed while using git.

For example in our case,

A script has to execute to validate the commit message. i.e. in another way.

When a developer commits a message, the commit-msg file will execute

commit-msg file is addressed by git version control itself. Whenever there is commit happens, the scripts which are written inside will get executed.

To do that,

Below is the sample script which we can add to file commit-msg, which will be located at place .git/hooks/commit-msg

#!/bin/bash

bug_regex_commit_format='(^T[0-9]{3,5}[:])|^Feature:'
error_msg="Commit not allowed, message should have Ticket number or Feature while committing code"

if ! grep -iqE "$bug_regex_commit_format" "$1"; then
    echo "$error_msg" >&2
    echo "Below are sample commits"
    echo " T12345: message"
    echo " Feature: message"
    exit 1
else
    echo "Commit is successful"
fi

Below is the output of the script when I tried to commit a code,

From hooks, if the file is not triggered based on our requirement we discussed, execute below command from source code path,

chmod +x .git/hooks/commit-msg

Summary

In this article, we learned about, how to validate the commit message before committing the code. In the next article see different use cases of git hooks.


Similar Articles