How to use tools such as pre-commit
and husky
to ensure your commit message follow a certain patter.
This brings benefits such as semantic versioning and changelog generation.
Let’s dive into it.
The challenge
I wanted to get commitlint running with husky and found a blog post explaining it, however I wanted it in short way.
The solution
Here comes the wrap-up and also an example using pre-commit.
husky
I found automatic and recommended steps in their instruction. So here comes the condensed version with the commands
Nodejs with yarn
For a nodejs project with yarn
as package manager you can use the following commands
npx husky-init && yarn
echo -n "module.exports = { extends: ['@commitlint/config-conventional'] };" >> .commitlintrc.js
yarn add --dev @commitlint/{cli,config-conventional}
npx husky add .husky/commit-msg 'npx commitlint --edit $1'
Then on every git commit
your message is linted.
projen
For projen this becomes a bit different. Here are the lines which
have to be added in the .projenrc.ts
import { awscdk } from 'projen';
const project = new awscdk.AwsCdkConstructLibrary({
// other properties
devDeps: [ /* Build dependencies for this module. */
'@commitlint/cli',
'@commitlint/config-conventional',
'husky',
],
});
project.package.setScript('prepare', 'husky install');
project.synth();
then run the following commands
# as we need to add the
echo -n "module.exports = { extends: ['@commitlint/config-conventional'] };" >> .commitlintrc.js
# to actually install the dependencies and the git hook
npm run projen
and you’d see the following output
$ husky install
husky - Git hooks installed
pre-commit
However if you are doing a general non-nodejs project, e.g. python
or golang
, then pre-commit is
the general tool which operates with python under the hood.
These are the steps for install:
# install the tool
brew install pre-commit
# define the config
cat << EOF > .pre-commit-config.yaml
repos:
- repo: https://github.com/commitizen-tools/commitizen
rev: v2.42.0
hooks:
- id: commitizen
EOF
# install the hook
pre-commit install --hook-type commit-msg
# run the checks manually
pre-commit run -a
Then on every git commit
your message is linted as well
Conclusion
I outlined in a short way the steps to add commit message lint with either husky
or pre-commit
and also in projen.
Me personally, I prefer having conventions on commit message, as they keep the focus small on each commit, as it
has to fit in one of the categories and furthermore we are able o use tools such as
- https://github.com/caarlos0/svu
- https://github.com/git-chglog/git-chglog
- https://github.com/goreleaser/chglog
- https://github.com/goreleaser/goreleaser
which generate the CHANGELOG
base on the commit messages back to the last tag.
Like what you read? You can hire me, or drop me a message to see which services 💻 may help you 👇