Skip to content

Instantly share code, notes, and snippets.

@arnauldvm
Last active October 7, 2018 20:56
Show Gist options
  • Save arnauldvm/1df04a27cf98ddf9c22e8b7f2c3e745e to your computer and use it in GitHub Desktop.
Save arnauldvm/1df04a27cf98ddf9c22e8b7f2c3e745e 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
temp_dir=''
function tear_down {
[ -d "$temp_dir" ] && rm -rf "$temp_dir"
}
trap tear_down EXIT
git diff --cached --name-only --diff-filter=d $against | egrep '\.py$' | while read file; do
[ -z "$temp_dir" ] && {
temp_dir=$(mktemp -d)
[ -f setup.cfg ] && cp setup.cfg "$temp_dir"
}
temp_template="$temp_dir/$(basename "$file")"
temp_template=${temp_template%.py}.XXXX.py
temp_file=$(mktemp "$temp_template")
git show :"$file" > "$temp_file"
python -m py_compile "$temp_file"
compile_status=$?
if [ $compile_status -ne 0 ]; then
echo ">>>> compilation failed for '$file' [stat=$compile_status]" >>/dev/stderr
exit $compile_status
fi
temp_comp="${temp_file%.py}.pyc"
[ -f "$temp_comp" ] && rm "$temp_comp"
#pycodestyle --count "$temp_file" --first --format="$file"'@%(row)d,%(col)d: [%(code)s] %(text)s'
# pycodestyle -qq --count "$temp_file" 2>> /dev/null
pycodestyle -qq --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 "'$file'"'
exit "$pep8_status"
fi
rm "$temp_file"
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment