flake8, only on diff and exclude
Asked Answered
B

4

13

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?

Bornholm answered 30/10, 2014 at 14:54 Comment(1)
flake8 can do essentially everything for you: flake8.pycqa.org/en/latest/user/using-hooks.htmlSelfoperating
C
15

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.

Colt answered 24/5, 2016 at 14:16 Comment(0)
G
4

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.

Gratt answered 24/3, 2017 at 17:6 Comment(0)
E
1

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

Eavesdrop answered 7/9, 2019 at 21:50 Comment(1)
usage: flake8 [options] file file ... flake8: error: unrecognized arguments: --install-hook ; check the refHabitual
P
1

If you are planning to use flake8 as a pre-commit hook, this article walks you through how to write a glue script that filters the analysis result for findings that are only on the lines modified.

Prosy answered 23/10, 2023 at 16:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.