How to lint your commit messages

Photo by Yancy Min on Unsplash

How to lint your commit messages

You just learned about Conventional Commits specification and its benefits, and would like to adopt it. Change is difficult, how do you make sure you never go rogue again? The answer to that is simple, using commitlint to lint your commit messages.

What is commitlint?

Commitlint is a tool that lints your commit messages and helps your team adhere to a commit convention. By supporting npm-installed configurations it makes sharing of commit conventions easy.

Setup commitlint

To get started, create an empty project:

# Create a new directory
mkdir using-commitlint
# Open the directory
cd using-commitlint
# Create a git repository
git init
# Create a package.json (use default configuration)
npm init

Now install as a dev dependency commitlint and a config for it, in our case it is config-conventional.

npm install --save-dev @commitlint/cli @commitlint/config-conventional

To configure commitlint to use conventional commits config, create a file named commitlint.config.js and inside it add:

module.exports = {
    extends: ["@commitlint/config-conventional"]
};

To run commitlint before the code is committed and block the commit in case of lint errors we'll need to use git hooks, to make that easy we'll install husky, a git hooks helper:

# Install husky
npm install --save-dev husky
# Activate hooks
npx husky install

The last step is to register a hook:

npx husky add .husky/commit-msg  'npx --no -- commitlint --edit ${1}'

To test try to create a commit with a message that violates the conventional commits specification:

git commit -m "this message is in clear violation of the specification" #fail
#⧗   input: this message is in clear violation of the specification
#✖   subject may not be empty [subject-empty]
#✖   type may not be empty [type-empty]
#
#✖   found 2 problems, 0 warnings
#ⓘ   Get help: https://github.com/conventional-changelog/commitlint/#what-is-commitlint
#
#husky - commit-msg hook exited with code 1 (error)

And if you try a valid message it should pass:

git commit -m "feat(my-scope): the description goes right here" #success

Additional resources

[commitlint CI setup] - Here we configured a local setup of commitlint, to enforce commit conventions with confidence you should lint on your CI server.

[commitlint prompt] - If your are having a tough time to remember the structure of the convention that you chose, use a prompt to help with authoring a commit.

[Conventional commits specification] - Learn more about conventional commits specification.

[commitlint configs] - Explore other commitlint configurations available on npm