A few days ago, I wrote a post on how you can reject commits that violate PEP8 using git’s pre-receive hooks. This is evaluated on the server, which, in the end, led to many commits that were just fixing PEP8/syntax errors. Wouldn’t it be much better if you checked for errors before you pushed, so you could fix them right there? It would indeed.
To do this, we can use flake8 and git’s pre-commit hooks (I’m assuming you already have flake8 installed, from the previous post). A pre-commit hook (locally) is much easier than a pre-receive hook (on the remote server), because it will reject the commit outright, so you can just go back and correct the files before committing.
To enable this, just create the file
.git/hooks/pre-commit under your repo (in your
.git folder) and enter the following lines:
#!/bin/sh flake8 .
Afterwards, make the file executable:
chmod +x .git/hooks/pre-commit
and you’re done! It will run every time before you commit, and prevent you from committing if the code has any errors.
I hope you found this tip useful!