Enforcing Conventional Commit — Shift Left

Rajiv
3 min readApr 23, 2023

--

Problem Statement

In my previous article, I wrote about how we can enforce conventional commits in Gitlab. If you are interested in it the link to the article is https://medium.com/@iyerajiv/enforcing-conventional-commit-in-gitlab-8b30aab90a02.

The problem with having only the above approach is that

  1. The developer has to modify the commit message and push the code to version control.
  2. It results in more time to get things done.

Resolution

What if we can do this upfront, ideally on the developer’s machine?

In this article, I want to focus on a shift left approach to conventional commits i.e. enforce conventional commits on the developer’s machine.

Pros

By getting it closer to the developer’s machine, there are some advantages which I have listed below

  1. Quick feedback to the developer if they have not followed the conventional commit rules.
  2. No need to modify the commit message and then push it again to the version control.
  3. Saves time.
  4. An additional validation over and above the one present in Gitlab. (No harm in having checks at multiple places).

Steps to enforce conventional commit

Let's look at how we can do it locally i.e. within a developer’s machine.

  1. To do this we will be using the below Github project

Note: Make sure pre-commit is installed.

2. In your repo, create a .pre-commit-config.yaml file.

3. Add the below content to the file

repos:
- repo: https://github.com/compilerla/conventional-pre-commit
rev: v2.1.1
hooks:
- id: conventional-pre-commit
stages: [commit-msg]
args: [] # optional: list of Conventional Commits types to allow e.g. [feat, fix, ci, chore, test]

I replaced rev:<git sha or tag> with the value rev: v2.1.1. I fetched the value of the tag from the repository in step 1.

4. Install the pre-commit script

pre-commit install --hook-type commit-msg

5. Make a commit which is not aligned with the conventional commit specification.

I used the below commit message

git commit -m "A message without conventional commit specification followed"

I got the below error while committing the code

Error on the IDE while committing

6. Make a commit aligned with the conventional commit specification.

I used the below commit message

git commit -m "feat: JIRA-123: A message aligned with conventional commit specification"

I got the below message while committing the code.

Success on the IDE while committing

Conclusion

We can use a shift left approach for conventional commit specification by using the above steps and enabling it locally in the developer’s machine. Do note that this should be used alongside the conventional commit implementation within Gitlab (as described here) or other version control systems.

--

--