Improve code quality with git hooks, part #2

Vincent B.
May 4, 2018 · 2 min read
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

Meilleurs Agents Engineering

Meilleurs Agents Engineering Teams (Product, Web & Data…)

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store