#!/bin/bash # Note: This script is intended to be run from the root of the repository. # # This script checks the format of the code and cmake files. # In many cases it will automatically fix the issues and abort the commit. echo "+ Checking code format..." # paths to check and re-format sources="src unittests" formatter="clang-format -i" version=$($formatter --version | grep -o '[0-9\.]*') if [[ "17.0.0" > "$version" ]]; then cat < /dev/null; then cat < style grep_code '#include ".*"' | xargs sed -i '' -E 's|#include "(.*)"|#include <\1>|g' # make local includes to be "..." style main_src_dirs=$(find ./src -maxdepth 1 -type d -exec basename {} \; | tr '\n' '|' | sed 's/|$//' | sed 's/|/\\|/g') grep_code "#include <\($main_src_dirs\)/.*>" | xargs sed -i '' -E "s|#include <(($main_src_dirs)/.*)>|#include \"\1\"|g" else # make all includes to be <...> style grep_code '#include ".*"' | xargs sed -i -E 's|#include "(.*)"|#include <\1>|g' # make local includes to be "..." style main_src_dirs=$(find ./src -type d -maxdepth 1 -exec basename {} \; | paste -sd '|' | sed 's/|/\\|/g') grep_code "#include <\($main_src_dirs\)/.*>" | xargs sed -i -E "s|#include <(($main_src_dirs)/.*)>|#include \"\1\"|g" fi cmake_dirs=$(echo CMake $sources) cmake_files=$(find $cmake_dirs -type f \( -name "CMakeLists.txt" -o -name "*.cmake" \)) cmake_files=$(echo $cmake_files ./CMakeLists.txt) first=$(git diff $sources $cmake_files) find $sources -type f \( -name '*.cpp' -o -name '*.hpp' -o -name '*.ipp' \) -print0 | xargs -0 $formatter cmake-format -i $cmake_files second=$(git diff $sources $cmake_files) changes=$(diff <(echo "$first") <(echo "$second") | wc -l | sed -e 's/^[[:space:]]*//') if [ "$changes" != "0" ]; then cat <<\EOF WARNING ----------------------------------------------------------------------------- Automatically re-formatted code with 'clang-format' - commit was aborted. Please manually add any updated files and commit again. ----------------------------------------------------------------------------- EOF exit 1 fi