Improve code quality with git hooks, part #2

Vincent B.
Meilleurs Agents Engineering
2 min readMay 4, 2018
Coast guard focusing men in sea

In our previous article, we have seen how to automate basics actions with a simple hook. We’re now diving into a more complex use-case of hooks: the pre-commit we use at MeilleursAgents

Goal

JavaScript in 2018 is a set of frameworks, tools and best practices. It can be hard to remember each rules on a daily basis. For example, we use yarn for our dependencies, prettier in conjonction of eslint for JavaScript code style.

All these tools rely on configuration files or have an option that can directly modify files. Running them before committing is a good practice, enforcing their execution while you commit is a safeguard.

Detecting changes in committed files

git has plenty of features for detecting files change, especially the diff one. The comparison of diff outputs between the begin and the end of script gives a clear indication if the hook has changed files.

Ensuring dependencies lock is correct

When we update our package.json, we ensure that our dependencies lock (e.g. yarn.lock or package-lock.json) is in sync, in order to have reproductible build and fixed versions of dependencies. When writing hooks, keep in mind that team members may have missing or different tools. For example, sed behaves differently on macOS and Linux, yarn is not always installed or in $PATH, especially for GUI Git Client.

We run all commands with the --silent option to have a clean output while committing.

Ensuring JavaScript code style

When we update JavaScript files, we ensure that they respect format and rules described in configuration. Running these tools on the whole codebase can be long and slows down your workflow. So we have a specific entry in our package.json that only formats or lints given files, ensuring fast run and fixing only modified files, not unrelated ones.

We save and check return codes for having a fail fast approach.

All-in-one

--

--