Search code examples
djangoregexpre-commit-hookpre-commitpre-commit.com

Exclude auto-generated files by Django within pre-commit-config.yaml using REGEX


Since the auto-generated Django files don't fulfill numerous pylint-requirements, my pre-commit checker fails: output pylint errors

The files look usually like so: example file

They seem to be located automatically in a sub-folder called "migrations": auto-generated django files in migration folder

Now, I tried to leverage the pre-commit exclude expressions with a proper REGEX. This one seemed to work on an online REGEX-tester: [\w-]+\d+[^\\]*.py

Here is the proof: proof of working regex

Now, putting this into my pylint pre-commit checker does unfortunately nothing: added exclude expression to pre-commit config YAML

I also tried to just exclude the "migrations" folder, but I could not find a working expression either. How can I make this work?


Solution

  • your regex you tested and the regex you used are different:

    # one you tested
    [\w-]+\d+[^\\]*.py
    # the one you tried
    ^[\w-]+\d+[^\\]*.py
    

    the ^ anchors to the beginning of the string which is not what you want (your files are specifically in a subdirectory and not at the root of the repository)

    additionally, slashes will always be forward slashes for pre-commit's file matching so you should instead exclude (and test against) forward slashes:

    [\w-]+\d+[^/]*.py
    

    a minor bug is you'd then match whatever1_py due to an un-escaped . (probably not a problem but here's an improvement):

    [\w-]+\d+[^/]*\.py
    

    you're also using a javascript regex tester -- while it doesn't matter for the features you're using here you probably want to use a python one as the patterns here are python regular expressions

    so try this:

    exclude: '[\w-]+\d+[^/]*\.py'
    

    disclaimer: I wrote pre-commit, though it matters less here since this is just a regex confusion