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:


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

# 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 > $HOME/.git_hooks/commit-msg