Photo by Gabriel Heinzer on Unsplash
Git Hooks and Proper commits
Make a good commit and set a standard
A commit message is a brief description of the changes made in a commit. It is used to explain the purpose of the changes and to provide context for future reference. A good commit message should be concise, informative, and easy to understand. It should also follow a consistent format to make it easier to read and search through commit logs.
In Git, you can enforce a specific commit message format using a
commit-msg hook
This hook script is used to prepare the commit log message. To enable this hook, you need to rename this file to prepare-commit-msg in
.git/hooks/
directory.
Here is an example of a commit message format that starts with the fix: #2345
and ends with the message page reloads prevented
:
fix: #2345 page reloads prevented
You can enforce this format by adding the following code to your commit-msg hook script:
This script checks if the commit message starts with one of the following types: fix
, feat
, docs
, style
, refactor
, perf
, test
, or chore
. It also checks if the commit message contains a ticket number in the format #2345
. Finally, it checks if the commit message is less than 50 characters long. If any of these conditions are not met, the script aborts the commit.
It all works fine in your local machine and enforces you to do the same, but how we can ensure other developers follow?
Use Husky to enforce the conventional commits across all developers in the projects,
Install Husky in the project
npx husky-init && npm install
Add the pre-commit hook to the Husky
npx husky add .husky/commit-msg
Add the commit message validator code in the file
Start committing and changes will be visible
Conventional Commit Examples:
The whole article with code can be found at Github Repo for Code Commit