Skip to content

Instantly share code, notes, and snippets.

@romuald
Last active September 3, 2024 13:43
Show Gist options
  • Save romuald/c8eaf549cc320503b5e6f00d281ed6ae to your computer and use it in GitHub Desktop.
Save romuald/c8eaf549cc320503b5e6f00d281ed6ae to your computer and use it in GitHub Desktop.
git hook to check python syntax before committing Raw
#!/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
@KsmBl
Copy link

KsmBl commented Sep 3, 2024

thanks, works perfectly :3

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment