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,

  1. Install Husky in the project

    npx husky-init && npm install

  2. Add the pre-commit hook to the Husky

    npx husky add .husky/commit-msg

  3. Add the commit message validator code in the file

    Code-commit

  4. Start committing and changes will be visible

Conventional Commit Examples:

conventional commit

The whole article with code can be found at Github Repo for Code Commit

References:

  1. How to Write Better Git Commit Messages – A Step-By-Step Guide (freecodecamp.org)

  2. https://github.com/conventional-changelog/commitlint

  3. https://gist.github.com/joshbuchea/6f47e86d2510bce28f8e7f42ae84c716

  4. https://github.com/senbagaraman04/learning-angular-github/tree/commit-demo