Conventional commit hooks are handy in a team environment where everyone must use a sensible commit message format to communicate and collaborate on a code base. The Conventional Commits specification is precisely defined for this purpose. It is a lightweight convention on top of commit messages. It provides an easy set of rules for creating an explicit commit history, which makes it easier to write automated tools on top.

In this post, I will introduce a tool called cc-cli — an easy cli and git-hook to help follow the Conventional Commits specification. 

Conventional Commit Hooks

cc-cli is a binary tool. It can be installed globally using the following cargo command:

> cargo install cc-cli

However, I prefer to install, cache and run such binary tools local to the repository. Therefore before I introduce cc-cli, let us look at another tool called cargo-run-bincargo-run-bin is a simple tool to build, cache, and run binaries scoped in Cargo.toml rather than installing globally. It acts similarly to npm run and gomodrun.

cargo-run-bin is the only tool that we need to install on the global level. Let’s install it:

> cargo install cargo-run-bin

cargo-run-bin creates a .bin directory and downloads, builds and caches the binaries in this directory. You can ignore this directory in the .gitignore.

Now let’s add cc-cli to cargo.toml:

> cargo add cc-cli --dev

The tool will be added as a dev dependency in the cargo.toml.

Now we can run this tool with the help of cargo-run-bin using the following command:

> cargo bin cc-cli -i

cargo-run-bin will download the crate, build it, cache it, and then run cc-cli as expected.

cc-cli -i will create a prepare-commit-msg hook in the .git/hooks directory. Here is what it looks like:

# cc-cli as a commit hook
exec < /dev/tty
cc-cli "$@"

However, it will fail as we run cc-cli via cargo-run-bin. Therefore update the last line as shown below:

cargo bin cc-cli "$@"

So far, so good. However, it will be local to my repository. That’s because we prefer to share these hooks among the team. By default, the hooks directory is $GIT_DIR/hooks, but that can be changed via the core.hooksPath configuration variable.

Let’s create a .git-hooks directory in the root directory and make it the hooks directory:

> git config core.hooksPath .git-hooks

The above will set the .git-hooks as the hooks directory for the repository.

Now move all the hooks files from the $GIT_DIR/hooks to .git-hooks directory and commit them in the git repo.

We are now all set to use conventional commit across the team.

About Author

Vimal Patel

Vimal believes in software engineering to control complexity, not create it. He designs and develops products that solve business problems effectively, keeping things simple and easy. He is a dedicated, disciplined results-driven leader. He has proven expertise in delivering solutions leveraging various technologies/tools. He is a DDD, TDD, Clean Coding and Design Pattern practitioner.