zephyr_vnd7050aj/scripts/install_clang_format_hook.sh

63 lines
1.4 KiB
Bash
Executable File

#!/bin/bash
# Function to print error messages in red
print_error() {
echo -e "\033[0;31mError: $1\033[0m"
}
# Check if clang-format is available
if ! command -v clang-format &> /dev/null
then
print_error "clang-format is not installed or not in your PATH. Please install it to use this pre-commit hook."
exit 1
fi
# Define the pre-commit hook content
HOOK_CONTENT='''#!/bin/bash
# Function to print error messages in red
print_error() {
echo -e "\033[0;31mError: $1\033[0m"
}
# Check if clang-format is available
if ! command -v clang-format &> /dev/null
then
print_error "clang-format is not installed or not in your PATH. Cannot format files."
exit 1
fi
# Get all staged C/C++/Objective-C/C++ files
FILES_TO_FORMAT=$(git diff --cached --name-only --diff-filter=ACM | grep -E "\.(c|h|cpp|hpp|cc|hh|cxx|hxx|m|mm)$")
if [ -z "$FILES_TO_FORMAT" ]; then
exit 0
fi
for FILE in $FILES_TO_FORMAT
do
# Check if the file exists and is a regular file
if [ -f "$FILE" ]; then
# Format the file and check for changes
clang-format -style=file -i "$FILE"
if ! git diff --quiet "$FILE"; then
git add "$FILE"
echo "Formatted $FILE with clang-format."
fi
fi
done
exit 0
'''
# Install the pre-commit hook
HOOK_PATH=".git/hooks/pre-commit"
# Create the hooks directory if it doesn't exist
mkdir -p .git/hooks
echo "$HOOK_CONTENT" > "$HOOK_PATH"
chmod +x "$HOOK_PATH"
echo "Git pre-commit hook for clang-format installed successfully."