Auto post-commit PEP8 correction


It’s always an hateful job to correct PEP8 warnings manually.

$ flake8 billy --ignore=E501,W293
billy/tests/integration/test_basic.py:401:45: W291 trailing whitespace
billy/models/processors/balanced_payments.py:116:44: W291 trailing whitespace
billy/models/processors/balanced_payments.py:133:30: W291 trailing whitespace

I bet you don’t like this either. Today I cannot take it anymore. I was wondering, why I should do this thing machine should do? So I seek solutions on the Internet, and I found an article looks helpful - Syntax+pep8 checking before committing in git. The basic idea is to add a pre-commit hook script to git for checking PEP8 syntax before commit. By doing that, you cannot commit code with PEP8 warnings anymore, when you do, you see errors like this

$ git commit
billy/tests/integration/test_basic.py:401:45: W291 trailing whitespace
billy/models/processors/balanced_payments.py:116:44: W291 trailing whitespace
billy/models/processors/balanced_payments.py:133:30: W291 trailing whitespace

Which is great, but still, you need to correct these syntax issues manually. I thought there must be something can do these boring job for you. And yes, I found autopep8. I can use autopep8 in pre-commit hook to correct PEP8 issues for me. However, I don’t think it is a good idea to let code formatting tool modifies your code silently when committing. I want to know what is modified by the tool. So here comes another solution, I use post-commit hook instead to compare the latest commit with previous commit:

#!/bin/sh
FILES=$(git diff HEAD^ HEAD --name-only --diff-filter=ACM | grep -e '\.py$')

for f in $FILES
do
    # auto pep8 correction
    autopep8 --in-place --ignore=E309,E501,W293 $f
done

All you need to do is install autopep8

pip install autopep8

and put the post-commit script at .git/hooks/post-commit. In this way, once I do a commit, it will correct PEP8 issues for me. I can review what is modified there, and make another PEP8 correction commit. With this, you can eventually enjoy coding rather than wasting time in removing trailing whitespace everywhere :D

Also check out my new book here 👇:

Rough Road - a zero to master software engineer guide book

You know you want to be a topnotch software engineer, but you know it's never easy to get there. From time to time, you feel lost and don't know what to do. This is what you are looking for, a guide from ground up to top level based on twenty years intensive programming experience.

Time limited offer expires on Sep 31 2019, original price $11.99, now only $4.99 via the link below:

Buy it now

Recent articles:

Elliptic Curve Cryptography Explained
Ninja Speed Vim-like Debugging with Ergonomic Keyboard and Trackpad
How I learn programming by building an MMORPG from the ground up 7 times