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. For each repository you define a set of actions that should run automatically prior to 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 OS’s:
MacOS
brew install pre-commit
Windows / Linux (using Python 3.x)
pip install pre-commit
Once you 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 (and assuming you have created the Makefile that defines the make lint action), every time you commit changes, your code will go through lint checking. You could also define the command to directly go through lint fixing. It’s like adding automatic lint fixes upon save only for commits and your entire repo instead of the file you’re working on.
If you’re the type of developer who commits a lot during development and only pushes once in a while, you could also configure pre-commit to run its actions on push instead of commit and that would make sure your origin repo gets only fixed code. That would also mean that your pre-commit script could include tests and type checks, too. As those would be relevant to any PR relevant to your code.
Conclusion
Pre-commit could save you a lot of time on those pesky commands you want to do for each commit like checking linting and typing fixes. It’s flexible and allows you to configure it to adapt to your natural development process. And using it will allow you write high-quality code and reduce many comments during code reviews. What are your experiences using pre-commit? Do you have any questions? Let me know in the comments below!