Last active
September 3, 2024 13:43
-
-
Save romuald/c8eaf549cc320503b5e6f00d281ed6ae to your computer and use it in GitHub Desktop.
git hook to check python syntax before committing Raw
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# This script check that the .py files that | |
# you're about to commit are syntactically valid | |
# Might want to check with a specific python binary | |
PYTHON=python | |
exit_status=0 | |
for file in $(git diff --cached --name-only --diff-filter=ACM | grep -e '\.py$') | |
do | |
# If the file differs from the index, we need to check out | |
# the index in a different physical file | |
# (syntax check won't work correctly on stdin for packages) | |
work_status=$(git status --porcelain "$file" | cut -b 2) | |
if [ "$work_status" != " " ]; then | |
git show :"$file" > "$file.pycommit" | |
$PYTHON -m py_compile "$file.pycommit" | |
compile_status=$? | |
rm "$file.pycommit" | |
else | |
# otherwise simply check the file as-is | |
$PYTHON -m py_compile "$file" | |
compile_status=$? | |
fi | |
if [ $compile_status -ne 0 ]; then | |
exit_status=1 | |
fi | |
# contiue with other files to display all problems in the first attempt | |
done | |
exit $exit_status |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
thanks, works perfectly :3