Improve code quality with git hooks, part #2
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.
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.
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.