Skip to content

Instantly share code, notes, and snippets.

@arnauldvm
Created September 13, 2018 09:04
Show Gist options
  • Save arnauldvm/63488835e1f210d25962e9e6a434979d to your computer and use it in GitHub Desktop.
Save arnauldvm/63488835e1f210d25962e9e6a434979d to your computer and use it in GitHub Desktop.
Git pre-commit hook for python code
#!/bin/sh
# requires py_compile and pycodestyle Python module
if git rev-parse --verify HEAD >/dev/null 2>&1
then
against=HEAD
else
# Initial commit: diff against an empty tree object
against=4b825dc642cb6eb9a060e54bf8d69288fbee4904
fi
PEP8_IGNORES='E126,E127,E501,E701'
git diff --cached --name-only --diff-filter=d $against | egrep '\.py$' | while read file; do
temp_file=$(mktemp --suffix=.py)
git show :"$file" > "$temp_file"
python -m py_compile "$temp_file"
compile_status=$?
if [ $compile_status -ne 0 ]; then
echo '>>>>' compîlation failed for '$file' [stat=$compile_status] >>/dev/stderr
rm "$temp_file"
exit $compile_status
fi
rm "${temp_file%.py}.pyc"
#pycodestyle --ignore="$PEP8_IGNORES" --count "$temp_file" --first --format="$file"'@%(row)d,%(col)d: [%(code)s] %(text)s'
# pycodestyle -qq --ignore="$PEP8_IGNORES" --count "$temp_file" 2>> /dev/null
pycodestyle -qq --ignore="$PEP8_IGNORES" --statistics "$temp_file" >> /dev/stderr
pep8_status=$?
if [ $pep8_status -ne 0 ]; then
echo '>>>>' PEP8 failures for '$file' [stat=$pep8_status] >>/dev/stderr
# pycodestyle -qq --ignore="$PEP8_IGNORES" --statistics "$temp_file" >> /dev/stderr
echo 'To see suggestions of fixes, run: autopep8 --verbose --diff --ignore="'$PEP8_IGNORES'" "'$file'"'
rm "$temp_file"
exit "$pep8_errors"
fi
rm "$temp_file"
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment