DEV Community

Matthew Dailey
Matthew Dailey

Posted on

Easily enforce git branch naming conventions

In many software development projects there is often some kind of branch naming conventions the developers follow. What if not all developers follow the naming rules? This has been a recurring problem at my work. I came up with a solution that was the easiest to implement.

I created a githooks script that will run right before the git push command. For the script to automatically run, a new .githooks folder needs to be created in the Git repository's root folder. Git needs to know it exists so run git config core.hooksPath .githooks while in the repository root folder. The script needs to be named pre-push with no file extension.

My githooks script is set up so if the git branch being pushed doesn't start with certain words and contains more than 10 characters, an error message is thrown and the push doesn't occur.

Here is the script and GitHub Gist link.

#!/usr/bin/env bash
LC_ALL=C

local_branch="$(git rev-parse --abbrev-ref HEAD)"

valid_branch_regex="^(task|master|develop|qa|tb|bug|story)[a-z0-9._-]{2,10}$"

message="This branch violates the branch naming rules. Please rename your branch."

if [[ ! $local_branch =~ $valid_branch_regex ]]
then
    echo "$message"
    exit 1
fi

exit 0
Enter fullscreen mode Exit fullscreen mode

Top comments (0)