Cheap Bug Protection With pre-commit’s Regex Hooks
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.
HTTP URLs ---------s
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 URLs. 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:
- repo: local
hooks:
- id: no-http
name: check no http urls
description: Enforce that all referred to URL's are https
entry: 'http\://(?!www\.w3\.org/)'
language: pygrep
types: [file]
No ‘novalidate’
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 novalidate
attribute:
<form novalidate>
...
</form>
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:
- repo: local
hooks:
- id: no-novalidate
name: check no novalidate
description: Enforce that no HTML forms have 'novalidate' set
entry: 'novalidate'
language: pygrep
types: [html]
Fin
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.
—Adam
Learn more about pre-commit in my Git DX book.
One summary email a week, no spam, I pinky promise.
Related posts:
- How to Mock the Current Date and Time in Python
- How to Mock Environment Variables in pytest
- A Guide to Python Lambda Functions
Tags: pre-commit, python