DEV Community

Muhammad Refel Hidayatullah
Muhammad Refel Hidayatullah

Posted on

Code commit best practice with commitizen & pre-commit

In this opportunity, I will share about Git hooks, Commitizen, and ESLint for linting. Coincidentally, on this occasion, I will be using Angular projects.

Let's say we already have Angular projects. And then, you need to install several dependencies.

Step 1

npm i -D husky eslint @typescript-eslint/parser @typescript-eslint/eslint-plugin
Enter fullscreen mode Exit fullscreen mode

STEP 2
You need to setup husky in your project with run this command

npx husky install 
Enter fullscreen mode Exit fullscreen mode

That command will generate the .husky/pre-commit file. pre-commit file will look like this.

#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"

npm run test
Enter fullscreen mode Exit fullscreen mode

STEP 3
Setup commitizen for template commit message. This is a beautiful feature to organize commit messages, especially when working with a fairly large team. For setup commitizen you need to run this command:

npm i commitizen
Enter fullscreen mode Exit fullscreen mode

and add this on your package.json

"config": {
    "commitizen": {
      "path": "cz-conventional-changelog",
      "jiraOptional": true
    }
  }
Enter fullscreen mode Exit fullscreen mode

This isn't finished yet, you need to run the following script.

npx husky add .husky/prepare-commit-msg "exec < /dev/tty && git cz --hook || true"
Enter fullscreen mode Exit fullscreen mode

If successful, it will create a new file inside the .husky/prepare-commit-msg folder. You can test this by running the commit with empty message:

git commit -am ""

result
and choose one of the options. in this case i will choose feature

next, you need to fill scope of changes.
scope changes

next, you need to fill short description about changes

short desc

and then, they provide for longer description. For this input, it's optional, you can leave it empty.

long desc

And next, they ask whether there are any breaking changes or if there will be any other open issues. If you choose 'y', they will ask for your explanation.

Image description

commit message on gitlab will look like this:

sample gitlab

It appears tidy and easy to understand for documentation or your code reviewer.

Conclusion

This feature is very helpful for describing what you're doing with code changes and greatly assists code reviewers.
for Linter git hooks / pre commit will posted at next article.

Top comments (4)

Collapse
 
bdxygy profile image
bdxygy

Thank you for sharing, keep it up!

Collapse
 
siamsubekti profile image
siamsubekti

thank you, this helped me a lot!

Collapse
 
raisulkhairi profile image
raisul khairi

tutorkan bg ;)

Collapse
 
rayabanilolly profile image
Raya Bani Lolly

great article, thanks for sharing!