Laziness and doing things the right way to avoid future work go hand-in-hand with developers. I create aliases, scripts, macros, and keyboard shortcuts to improve my efficiency, but what about readability freaks? I LOVE readable code and so should you. Readable code is like the new transformers chick waiting at your house, EXCELLENT! With Python, you have the nifty styling guide called PEP8 to help ease your mind.
A styling guide is about consistency. It’s about providing good quality code. But there are times when you don’t need it. Hence the quote:
A Foolish Consistency is the Hobgoblin of Little Mind
For instance, lines that are longer than 60 characters don’t really matter too much anymore. With more developers starting to use widescreens it’s becoming a non-issue. Enough banter, lets see how we can automate PEP8 checks on modified python files with git and fabric.
Installing Fabric
pip install fabric
Setting up the Fab file
Fabric requires a fabfile.py. This file tells fabric where all it’s tasks are located. The contents of the fabfile.py should like like:
import os
import sys
from fabric.api import *
from fabric.colors import *
def pep8_modified(path, pep8_args=None):
"""
Run pep8 on the output of the git status command
"""
# hide these status outputs in fabric
hides = ['running', 'status', 'warnings', 'stderr', 'stdout']
# git cmd to list modified files with scriptable output
git_command = 'git status --porcelain'
if os.path.isdir(path):
with hide(*hides):
with cd(path):
file_list = local(git_command, capture=True)
files = file_list.split('\n')
# no files
if files[0] == '':
puts(yellow('No files have been modified'))
sys.exit(-1)
# we have files
for f in files:
modified_file = f.split()[1]
extension = os.path.splitext(modified_file)[1]
# we want only python files
if extension == '.py':
file_path = os.path.join(path, modified_file)
if pep8_args: # output with arguments
output = local('pep8 %s %s' % (
pep8_args,
file_path
))
else:
output = local(
'pep8 %s' % file_path,
capture=True
)
puts(output)
else:
puts(red('Path %s does not exist' % path))
Setting up the shell alias
We need to allow this fabric task/command to run on any git repository in the system. This is set up by integrating the fabric command with a bash shell alias. I’m going to assume a virtual environment in the next code snippet.
Add the following code to your .bashrc or .profile which should be in your home folder:
run_pep8_modified() {
current_dir=$PWD
fabric_cmd="/path/to/virtualenv/bin/fab"
fab_file="/path/to/fabfile.py"
if [ -n "$1" ]
then
$fabric_cmd -f $fab_file -w pep8_modified:$current_dir,pep8_args="$1"
else
$fabric_cmd -f $fab_file -w pep8_modified:$current_dir
fi
}
alias pep8_modified=run_pep8_modified
Got all that?
Now you should be able to type in ‘pep8_modified‘ in the shell while in a git repository to have it automatically run pep8 on each file. If you have any troubles, comment or DM me on twitter
