1 #!/bin/bash 2 # 3 # Inspired by https://github.com/antiagainst/SPIRV-Tools/commit/c4f1bf8ddf7764b7c11fed1ce18ceb1d36b2eaf6 4 # 5 # Script to determine if source code in a diff is properly formatted. On 6 # GitHub, a commit range is provided which corresponds to the commit range of 7 # 1) commits associated with a pull request, or 8 # 2) commits on a branch which are not also part of main, or 9 # 3) commits since last push to main. 10 # 11 # Exits with non 0 exit code if formatting is needed. 12 # 13 # This script assumes to be invoked at the project root directory. 14 15 COMMIT_RANGE="${1}" 16 17 if [ -z "${COMMIT_RANGE}" ]; then 18 >&2 echo "Empty commit range, missing parameter" 19 exit 1 20 fi 21 22 >&2 echo "Commit range $COMMIT_RANGE" 23 24 FILES_TO_CHECK="$(git diff --name-only "$COMMIT_RANGE" | grep -e '\.c$' -e '\.h$' || true)" 25 CFV="${CLANG_FORMAT_VERSION:-10}" 26 27 if [ -z "${FILES_TO_CHECK}" ]; then 28 >&2 echo "No source code to check for formatting" 29 exit 0 30 fi 31 32 FORMAT_DIFF=$(git diff -U0 ${COMMIT_RANGE} -- ${FILES_TO_CHECK} | clang-format-diff$CFV -p1) 33 34 if [ -z "${FORMAT_DIFF}" ]; then 35 >&2 echo "All source code in the diff is properly formatted" 36 exit 0 37 else 38 >&2 echo -e "Found formatting errors\n" 39 echo "${FORMAT_DIFF}" 40 >&2 echo -e "\nYou can save the diff above and apply it with 'git apply -p0 my_diff'" 41 exit 1 42 fi 43