Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

flake8, only on diff and exclude

Tags:

git

pep8

flake8

I'm trying to run flake8 in a pre-commit hook on only the changed files in my git diff, while also excluding files in my config file.

files=$(git diff --cached --name-only --diff-filter=ACM);
if flake8 --config=/path/to/config/flake8-hook.ini $files; then
    exit 1;
fi

I'm essentially wanting to do:

flake8 --exclude=/foo/ /foo/stuff.py

And then have flake8 skip the file that I passed in because it is in the exclude variable.

I'm also wanting it to exclude files that are not .py files. For example:

flake8 example.js

Right now as I'm testing, neither of these work. Anyone have any ideas?

like image 480
bzmw Avatar asked Oct 30 '14 14:10

bzmw


3 Answers

If you want to use flake8 to check files before commit, simply use

flake8 --install-hook git

ref: https://flake8.pycqa.org/en/latest/user/using-hooks.html

like image 175
Egor Panfilov Avatar answered Nov 06 '22 09:11

Egor Panfilov


If what you're after is running flake8 on both uncommitted and staged python files with changes, this one-liner will do the trick:

flake8 $(git status -s | grep -E '\.py$' | cut -c 4-)

git status lists the changed files, grep for python, get rid of the M / S bit at the beginning with cut.

To make it into a pre-commit hook, you need to add the shell hashbang:

#!/bin/sh flake8 $(git status -s | grep -E '\.py$' | cut -c 4-)

Save it as .git/hooks/pre-commit, chmod +x.

like image 25
Kip Avatar answered Nov 06 '22 10:11

Kip


There are two parts to your questions:

1. Running flake8 in a pre-commit hook on only the changed files in my git > diff

For running flake8 on only diff files (which have been staged), I modify the .git/hooks/pre-commit script to as follow:

#!/bin/sh
export PATH=/usr/local/bin:$PATH  
export files=$(git diff --staged --name-only HEAD)  
echo $files  
if [ $files != "" ]  
then  
    flake8 $files  
fi

I am using the export PATH=/usr/local/bin:$PATH as I generally commit from sourceTree, which does not pick up the path where flake8 resides

The --staged option allows only the files in staging area to be picked up

For the second, part:

2. excluding files in my config file

You can create a .flake8 file in you repository root that can take care of this. My .flake8 file looks like this:

[flake8]  
ignore = E501  
exclude =  
        .git,  
        docs/*,  
        tests/*,  
        build/*  
max-complexity = 16

Hope this helps.

like image 1
sid_pro_quo Avatar answered Nov 06 '22 09:11

sid_pro_quo