Humans are terrible at repetitive tasks. We forget to run linters. We forget to check for trailing whitespace. We forget to run the test suite before pushing.
Computers, on the other hand, love repetition. This is where Git Hooks come in.
Introduction
Git Hooks are scripts that Git executes before or after events such as: commit, push, and receive. They allow you to “hook” into the Git workflow and stop bad things from happening.
The most useful one for daily development is the pre-commit hook.
What is a pre-commit hook?
This script runs every time you type git commit. If the script exits with an error (non-zero status), the commit is aborted.
It’s the perfect place to put comprehensive checks:
- “Does the code compile?”
- “Are there any lingering
print()statements?” - “Does the formatting match the team style?”
Setting it up (The Easy Way)
You can write bash scripts in .git/hooks/, but that’s hard to share with a team. I recommend using the pre-commit framework.
- Install it:
pip install pre-commit - Add a config file
.pre-commit-config.yamlto your repo:
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.4.0
hooks:
- id: trailing-whitespace
- id: end-of-file-fixer
- id: check-yaml
- Install the git hook scripts:
pre-commit install
Now, whenever you commit, these little robots will run. If you left trailing whitespace, they will fix it for you and stop the commit so you can stage the clean version.
Why use hooks?
It shifts the feedback loop left. Instead of waiting 10 minutes for your CI/CD pipeline to fail on GitHub, you find out instantly on your own machine.
It saves time, embarrassment, and keeps the main codebase pristine.
Conclusion
Automation is the key to maintaining high standards without mental fatigue. Set up a pre-commit hook today, and let the robot butler handle the boring stuff while you focus on solving interesting problems.
Did you like this post? Please let me know if you have any comments or suggestions.
Git posts that might be interesting for you