Jon Atkinson

Jon Atkinson

Conventional Commits Git Hook

I was looking for a way to enforce the Conventional Commits pattern for my own commit messages. A lot of the solutions I found were wildly overcomplicated; I don't need to install a commit linting framework with a hundred JS dependencies, I just want to apply a regex to a commit message.

This was fairly straightforward. First, create a global hooks folder, and enable it.

$ mkdir $HOME/.git_hooks
$ git config --global core.hooksPath ~/.git_hooks

Now, create the script file:

$ touch $HOME/.git_hooks/commit-msg
$ chmod +x $HOME/.git_hooks/commit-msg

The contents of that script:

#!/bin/bash

commit_msg_file=$1
commit_msg=$(cat $commit_msg_file)

# Define the pattern for conventional commit messages
pattern="^(build|chore|ci|docs|feat|fix|perf|refactor|revert|style|test)(\(.+\))?: .+"

if [[ ! ${commit_msg} =~ $pattern ]]; then
echo "ERROR: The commit message does not follow the conventional commit format."
echo "Valid types: build, chore, ci, docs, feat, fix, perf, refactor, revert, style, test"
echo "Format: type(scope): subject"
exit 1
fi

# If commit message matches the pattern, continue with the commit
exit 0

The code is also available from this gist, so if you prefer, install it like this:

$ curl https://gist.githubusercontent.com/jonatkinson/9243328de14e17e1e4200b9a1ca97d72/raw/3e342f140f5df8d6ec273253a071c431a90d6a89/commit-msg > $HOME/.git_hooks/commit-msg