-
-
Save Boerde/3f4329b218bae02323ebabeab6975ae2 to your computer and use it in GitHub Desktop.
Git post-commit hook to check C/C++ source file format using astyle (Artistic Style) + automatic creation of a commit with a fix
This file contains 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 | |
# 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 | |
} | |
OPTIONS="--style=k&r --brackets=linux --indent-preprocessor --break-blocks --pad-oper --pad-header --unpad-paren --align-pointer=name --convert-tabs" | |
astyle_commit=0 | |
RETURN=0 | |
ASTYLE=$(which astyle) | |
exec < /dev/tty | |
if [ $? -ne 0 ]; then | |
echo "[!] astyle not installed. Unable to check source file format policy." >&2 | |
exit 1 | |
fi | |
stashed=$(have_uncommitted) | |
# get all changed files in last commit | |
FILES=$(git diff --name-only HEAD~1 | grep -E "\.(c|cpp|h)$") | |
# clear stash when we used him | |
if [ $stashed -eq 1 ]; then | |
git stash pop | |
fi | |
for FILE in $FILES; do | |
$ASTYLE $OPTIONS < $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) | |
$ASTYLE $OPTIONS $FILE | |
git add -u | |
if [ $astyle_commit -eq 0 ]; then | |
astyle_commit=1 | |
git commit -m "cleanup with astyle" | |
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 | |
fi | |
RETURN=0 | |
fi | |
fi | |
done | |
if [ $RETURN -eq 1 ]; then | |
echo "" >&2 | |
echo "Make sure you have run astyle with the following options:" >&2 | |
echo "astyle $OPTIONS" >&2 | |
fi | |
exit $RETURN |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment