The Wonderful World of Pre-Commit
Automate some tasks to push high-quality code.
--
Some of us work in a certain standard of code development. Like automatically lint your code when hitting save. Some of us don’t even know what linting is. I belong to the former. Which group are you on?
Regardless of your choice of code standard, you have to try using pre-commit. It could solve you a lot of headaches before code reviews. Let’s talk about it.
What is Pre-Commit?
Pre-commit is a small piece of software that you install globally on your machine, and it serves you for all of your repositories. You define a set of actions for each repository that should run automatically before your git commit action.
If the actions fail for whatever reason, your commit action will not go through.
How to Install Pre-Commit?
Pre-commit is a system-specific installation. Below you’ll find how to install it for the major development operating systems:
macOS
brew install pre-commit
Windows / Linux (using Python 3.x)
pip install pre-commit
Once you have installed Pre-Commit, you’re ready to config a repository. Let’s do that now.
How to Configure Pre-Commit Actions?
Inside your repository, you need to add a new file called .pre-commit-config.yaml
. That file will host the actions that you want to happen before your commit commands go through.
Here’s an example file:
repos: - repo: local hooks: - id: linting name: linting-black entry: bash -c 'make lint' language: system types_or: ["non-executable", "python"]
After you have created this file in the root of your repository (assuming you have created the Makefile that defines the make lint action), your code will go through lint checking every time you commit changes. You could also define the command to directly go through lint fixing. It’s like adding automatic lint fixes upon saving only for commits and your entire repo instead of the file you’re working on.