Clean Commits with Pre-Commit hooks
The Problem
You have all the ruff and so on configured, but you still have to remember to run them before committing. Or even worse, you remember, but your colleague doesn’t and you have to deal with their mess!
The Solution
Prevent committing code that doesn’t pass the user-defined checks!
pre-commit hooks
Pre-commit hooks are scripts that run before the commit is made. In tapyr, we use pre-commit to check code quality with ruff before the code is committed, but also we check for large files, trailing whitespaces, and other issues. This is a great way to catch issues before creating pull request. Pre-commit hooks automatically fix some issues, like formatting, so you don’t have to worry about it. You just have to agree to the changes and commit the adjusted code.
Pre-commit hooks are NOT python environment-aware. For tests and type checking we have CI checks.
How to use it
- After cloning the repository and installing the dependencies, run
pre-commit installto install the hooks. - Now, every time you commit, the hooks will run and check the code.
- It may happen that your code doesn’t pass the checks.
pre-commitwill try to make the necessary changes to fix the issues if possible (like formatting). - After the changes are made you have to stage the changes and commit them.
- You an also run
pre-commit run --allto run the checks manually.
In CI we always run pre-commit run --all to ensure that the code is clean. Sometimes the CI may not pass not because of our changes, but someone else’s. So before panicking and frustrating, read carefully the error message in CI pipeline.