Before starting on how we enforce Conventional Commit in Gitlab, it would be good to understand Conventional Commit. A simple definition is as below
A specification for adding human and machine readable meaning to commit messages. Conventional Commits are a way of standardizing the format of your commit messages.
It is described in detail at https://www.conventionalcommits.org/en/v1.0.0/.
One of the reasons why you would want to enforce Conventional commits is to make it easier to track changes to your code and help to automate tasks like generating release notes or change logs.
Now that we understand conventional commit specification and its advantages let's look at how to enforce conventional commit in GitLab.
- Logging into GitLab, click on the project where you want to enforce conventional commits.
- Click on Setting and then click on Repository
- You will be presented with a list of options like the one below. Click on the “Expand” button next to “Push Rules”
- You will be presented with the below options. In there, we are interested in the text box with the title “Require expression in commit messages”
- Add the below regular expression in the text box.
^(?P<type>build|chore|ci|docs|feat|fix|perf|refactor|revert|style|test|¯\\_\(ツ\)_/¯)(?P<scope>\(\w+\))?(?P<breaking>!)?(?P<subject>:\s.*)?|^(?P<merge>Merge \w+)|(Initial commit$)|(Notes added by \'git notes add\')
Note: The regular expression was from a stackoverflow discussion. We can use https://regex101.com/ to test the expression
- Click on the below button to save the changes
- Conventional commits should now be applicable to the project and reject commits that are not aligned with the regular expression.
Note: I had to move to an Ultimate plan for this setting to be visible.
Now that we have made the changes it would be good to see how we can test the change. I made some changes to the README.md file in my project and committed it with the below commit message.
“Adding more context to the README.md”
As expected when I push to change with the above commit message, it is rejected with the below message
I will correct the commit message using the below and change the message to “feat: Adding more context to the README.md”
git commit --amend
After amending the commit message, I was able to successfully push the changes to the project.
This is how we can set up or enforce the developers to follow conventional commit specifications.