Cheap Bug Protection With pre-commit’s Regex Hooks2021-01-26
For all my linting needs these days I use the pre-commit framework. It has integrations with every tool I want to use, and uses Git’s hooks to prevent non-passing code from ever being committed.
On top of its many integrations, pre-commit makes it easy to add your own checks.
The simplest tool here is the
pygrep “language”, which allows you to provide a Python regex that, if matched, fails a file.
Thus you can ban certain constructs from ever being added to your codebase.
Here are a couple of
pygrep examples that I’ve already come up with whilst working on DB Buddy.
I want to ensure DB Buddy is secure, so it’s always served over HTTPS.
I also want to ensure I never link users out to insecure HTTP URL’s.
Therefore I added a hook to prevent any use of
http://, with one exception for wwwˆ.w3.org since the SVG specification requires an HTTP URL reference:
When testing an HTML form on my development server, I often want to check that my server-side validation is functioning.
So I might turn off the client-side validation on the form with the
But I don’t want to commit this, since the client-side validation is useful for users. I prevent this with a simple regex for ‘novalidate’ in all HTML files:
I hope these examples help you find ways to use pre-commit to improve your code quality. For more examples check out the pre-commit/pygrep-hooks repo.
Want better tests? Check out my book Speed Up Your Django Tests which teaches you to write faster, more accurate tests.
One summary email a week, no spam, I pinky promise.
- How to Mock the Current Date and Time in Python
- How to Mock Environment Variables in pytest
- A Guide to Python Lambda Functions
© 2021 All rights reserved.