Skip to content

Instantly share code, notes, and snippets.

@vpatel95
Last active November 14, 2024 20:50
Show Gist options
  • Save vpatel95/6fb415df55bcac56d40eaa6c66eaa76d to your computer and use it in GitHub Desktop.
Save vpatel95/6fb415df55bcac56d40eaa6c66eaa76d to your computer and use it in GitHub Desktop.
Pre-commit hook for C/C++ code format enforcement using clang-format
#!/bin/bash
# Print an introduction line in cyan
printf "\033[0;36mPre-commit hook is linting your changes for C/CPP code...\033[0m \n"
# Grab feed of staged cppfiles
cppfiles=$(git diff --name-only --cached --diff-filter=ACMRT | \
grep ".*\.\(c\|cc\|cpp\|h\|hh\|hpp\)$" )
numfiles=$( printf '%s' "$cppfiles" | grep -c '^' )
exitstatus=0
if [ $numfiles -eq 0 ]
then
printf "\033[0;35mNo C/CPP files staged. Nothing to check.\033[0m\n"
exit $exitstatus
fi
# Iterate over the filenames to discover the longest
longest=0
for i in $cppfiles
do
if [ ${#i} -gt $longest ]
then
longest=${#i}
fi
done
# Iterate over the staged filenames
for i in $cppfiles
do
# Print file name eg: "Checking: text.txt"
printf "\033[0;35mChecking:\033[0m %s " "$i"
# Print some padding spaces so the failed/success statuses line up
padding=$(expr $longest - ${#i})
for ((n=0;n<$padding;n++))
do
printf " "
done
git clang-format --diffstat $i | grep "file.*changed" >/dev/null
if [ $? -ne 1 ]; then
printf "\033[0;31m[FAILED]\n"
exitstatus=1
else
printf "\033[0;32m[PASSED]\n"
fi
# Reset print color back to default for the next iteration
printf "\033[0m"
done
exit $exitstatus
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment