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?
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
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.
There are two parts to your questions:
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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With