Skip to content

Instantly share code, notes, and snippets.

@kblomqvist
Last active September 9, 2022 13:04
Show Gist options
  • Save kblomqvist/bb59e781ce3e0006b644 to your computer and use it in GitHub Desktop.
Save kblomqvist/bb59e781ce3e0006b644 to your computer and use it in GitHub Desktop.
Git pre-commit hook to check C/C++ source file format using astyle (Artistic Style)
#!/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
OPTIONS="-A8 -t8 --lineend=linux"
RETURN=0
ASTYLE=$(which astyle)
if [ $? -ne 0 ]; then
echo "[!] astyle not installed. Unable to check source file format policy." >&2
exit 1
fi
FILES=`git diff --cached --name-only --diff-filter=ACMR | grep -E "\.(c|cpp|h)$"`
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
fi
done
if [ $RETURN -eq 1 ]; then
echo "" >&2
echo "Make sure you have run astyle with the following options:" >&2
echo $OPTIONS >&2
fi
exit $RETURN
@JensMunkHansen
Copy link

JensMunkHansen commented Jul 10, 2016

Hmm. I have inserted a line echo "$?" just before the line saying that a file does not respect coding style. I have a situation where $? is 0 but it fails.

I figured it out or tracked down the error astyle < input > output adds an extra newline at the end compared to the inplace call astyle -n input....

I fixed it this way.

# Support old version of astyle 2.04
less -f `which astyle` | grep 2.04
BUG=$?

FILES=`git diff --cached --name-only --diff-filter=ACMR | grep -E "\.(c|cpp|h|hpp)$"`
for FILE in $FILES; do
    if [ $BUG -ne 0 ]; then
        $ASTYLE $OPTIONS < $FILE | cmp -s $FILE -
    else
        $ASTYLE $OPTIONS < $FILE | head -c -1 | cmp -s $FILE -
    fi
    if [ $? -ne 0 ]; then
        echo "$?" >&2
        echo "[!] $FILE does not respect the agreed coding style." >&2
        RETURN=1
    fi
done

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