Skip to content

Instantly share code, notes, and snippets.

@Boerde
Last active October 25, 2016 10:49
Show Gist options
  • Save Boerde/42905be6e985f24847bfc4b8b65d45bf to your computer and use it in GitHub Desktop.
Save Boerde/42905be6e985f24847bfc4b8b65d45bf to your computer and use it in GitHub Desktop.
#!/bin/bash
# original gist was from https://gist.github.com/kblomqvist/bb59e781ce3e0006b644
# Installation:
# cd my_gitproject
# wget -O pre-commit.sh http://tinyurl.com/mkovs45
# ln -s ../../pre-commit.sh .git/hooks/pre-commit
# chmod +x pre-commit.sh
function have_uncommitted()
{
lines=$(git diff --name-only | wc -l)
if [ 0 -ne $lines ]; then
git stash > /dev/null
echo 1
else
echo 0
fi
}
commit=0
RETURN=0
OPTIONS="--aggressive --in-place"
PEP=$(which autopep8)
exec < /dev/tty
if [ $? -ne 0 ]; then
echo "[!] autopep8 not installed. Unable to check source file format policy." >&2
exit 1
fi
echo "Checking files for coding style" >&2
stashed=$(have_uncommitted)
FILES=$(git diff --name-only HEAD~1 | grep -E "\.(py)$")
ROOTDIR=$(git rev-parse --show-toplevel)
# clear stash when we used him
if [ $stashed -eq 1 ]; then
git stash pop > /dev/null
fi
for FILE in $FILES; do
# convert to absolute path
FILE="$ROOTDIR/$FILE"
$PEP --aggressive $FILE | cmp -s $FILE -
if [ $? -ne 0 ]; then
echo "[!] $FILE does not respect the agreed coding style." >&2
RETURN=1
# wait for user input to auto clean file
echo "Should it be cleaned? [y/n] (All other changes will be stashed)"
read clean_file
if [[ $clean_file == "y" ]]; then
echo "cleaning file $FILE"
stashed=$(have_uncommitted)
$PEP $OPTIONS $FILE
git add -u
if [ $commit -eq 0 ]; then
commit=1
git commit -m "cleanup with autopep8"
else
#there is already a commit with cleanup so use the same one
git commit --amend
fi
## replay changes
# pop all changes which were staged before
if [ $stashed -eq 1 ]; then
git stash pop > /dev/null
fi
RETURN=0
fi
fi
done
if [ $RETURN -eq 1 ]; then
echo "" >&2
echo "Make sure you have run pep with the following options:" >&2
echo "autopep8 $OPTIONS" >&2
fi
exit $RETURN
@Boerde
Copy link
Author

Boerde commented Oct 25, 2016

Git post-commit hook for checking files with autopep8
only files commited are getting checked.

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