Skip to content

Instantly share code, notes, and snippets.

@LemonPi
Created January 18, 2018 17:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save LemonPi/61b8c9f33d86bbfe8d76236edbb1a692 to your computer and use it in GitHub Desktop.
Save LemonPi/61b8c9f33d86bbfe8d76236edbb1a692 to your computer and use it in GitHub Desktop.
pre-commit hook for checking source files are clang-formatted, giving command to format any unformatted files
#!/bin/bash
#
# Check that all source files follow a fixed format.
# Called by "git commit" with no arguments.
# Commit is blocked if any file does not follow format and outputs
# command to format them.
# Enable this by copying this file into .git/hooks/pre-commit
ROOT=$(git rev-parse --show-toplevel)
FORMATTER="clang-format"
files=$(git diff --cached --name-only -z | tr '\0' '\n')
formats_to_format="\.(cpp|hpp|c|h)$"
files_to_format=$(echo "$files" | grep -E $formats_to_format)
bad_files=""
for file in $files_to_format ; do
out=$($FORMATTER $file)
DIFF=$(diff <(echo "$out") $file)
if [ "$DIFF" != "" ]
then
bad_files="$bad_files \"$ROOT/$file\""
fi
done
if [ "$bad_files" != "" ]
then
echo "Some files are not formatted correctly; format with:
$FORMATTER -i $bad_files"
exit 1
fi
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment