Skip to content

Run Cppcheck only when source files change #258

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Mar 11, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 14 additions & 13 deletions scripts/pre-commit.hook
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ detect_cc_std() {
CPPCHECK_OPTS="-I. --enable=all --error-exitcode=1"
CPPCHECK_OPTS+=" $(detect_cc_std)"
CPPCHECK_OPTS+=" --force $(cppcheck_suppressions) $(cppcheck_build_unmatched)"
CPPCHECK_OPTS+=" --cppcheck-build-dir=.out ."
CPPCHECK_OPTS+=" --cppcheck-build-dir=.out"

set_colors

Expand Down Expand Up @@ -179,8 +179,8 @@ if [ "${#binary_files[@]}" -gt 0 ]; then
printf "${RED}[!]${NC} Binary data found.\n"
fi

FILES=$(git diff --cached --name-only --diff-filter=ACMR | grep -E "\.(c|cpp|h)$")
for FILE in $FILES; do
C_FILES=$(git diff --cached --name-only --diff-filter=ACMR | grep -E "\.(c|cpp|h|hpp)$")
for FILE in $C_FILES; do
nf=$(git checkout-index --temp $FILE | cut -f 1)
tempdir=$(mktemp -d) || exit 1
newfile=$(mktemp ${tempdir}/${nf}.XXXXXX) || exit 1
Expand Down Expand Up @@ -221,8 +221,7 @@ fi
root=$(git rev-parse --show-toplevel)
banned="([^f]gets\()|(sprintf\()|(strcpy\()"
status=0
for file in $(git diff --staged --name-only | grep -E "\.(c|cc|cpp|h|hh|hpp)\$")
do
for file in $C_FILES; do
filepath="${root}/${file}"
output=$(grep -nrE "${banned}" "${filepath}")
if [ ! -z "${output}" ]; then
Expand All @@ -242,7 +241,7 @@ if [ ! -f fmtscan ]; then
throw "Fail to build 'fmtscan' tools"
fi
fi
if git diff --cached --name-only | grep -qiE "\.(c|h|cpp|hpp)$"; then
if [ -n "$C_FILES" ]; then
echo "Running fmtscan..."
./fmtscan
if [ $? -ne 0 ]; then
Expand All @@ -251,13 +250,15 @@ if git diff --cached --name-only | grep -qiE "\.(c|h|cpp|hpp)$"; then
fi

# static analysis
echo "Running static analysis..."
$CPPCHECK $CPPCHECK_OPTS >/dev/null
if [ $? -ne 0 ]; then
RETURN=1
echo "" >&2
echo "Fail to pass static analysis." >&2
echo
if [ -n "$C_FILES" ]; then
echo "Running static analysis..."
$CPPCHECK $CPPCHECK_OPTS $C_FILES >/dev/null
if [ $? -ne 0 ]; then
RETURN=1
echo "" >&2
echo "Fail to pass static analysis." >&2
echo
fi
fi

# non-ASCII filenames are not allowed.
Expand Down