Cheap Bug Protection With pre-commit’s Regex Hooks

You aren’t allowed to write that!

Update (2021-01-07): My new book Boost Your Django DX has an extended tutorial on setting up 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.


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ˆ since the SVG specification requires an HTTP URL reference:

- repo: local
  - 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>

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
  - id: no-novalidate
    name: check no novalidate
    description: Enforce that no HTML forms have 'novalidate' set
    entry: 'novalidate'
    language: pygrep
    types: [html]


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.


If your Django project’s long test runs bore you, I wrote a book that can help.

Subscribe via RSS, Twitter, Mastodon, or email:

One summary email a week, no spam, I pinky promise.

Related posts:

Tags: ,