Git Hook To Validate The Branch Name

Introduction

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

In this article, we will see how we can prevent wrong format push of branch names.

Pre-requisites:

  • Developer should have knowledge of git.

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

Git hook is what will have some scripted files in .git/hooks/ folder. This will trigger/execute automatically when there is a particular event happening in git. What script must trigger will be addressed by an action which is performed while using git.

For example, in our case:

A script has to execute to validate the branch name, i.e., in another way. When a developer commits a message, a pre-commit file will execute to validate the branch name. Pre-commit files are addressed by git version control itself. When a git commit is triggered just before committing the message, the scripts which is written inside will get executed.

To do that, the sample script that we can add to file pre-commit, which will be located at place .git/hooks/pre-commit, is below:

#!/bin/bash

branch_name_format='(^T[0-9][-])|^develop|master'
error_msg="Push not allowed, branch name should starts with Txxx or develop"
BRANCH_NAME=$(git symbolic-ref --short HEAD)
echo "$BRANCH_NAME"
if [[ ! $BRANCH_NAME =~ $branch_name_format ]]; then
    echo "$error_msg" >&2
    echo "Below are sample branch names"
    echo "T123-<anything>"
    echo "develop.*"
    echo "master"
    exit 1
else
    echo "Push is successful"
fi

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

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

chmod +x .git/hooks/pre-commit

Summary

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


Similar Articles