check_code_format.sh 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. #!/bin/bash
  2. # Copyright (c) 2017 Google Inc.
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. # This script determines if the source code in a Pull Request is properly formatted.
  15. # Exits with non 0 exit code if formatting is needed.
  16. # Assumptions:
  17. # - git and python3 are on the path
  18. # - Runs from the project root diretory.
  19. # - 'clang-format' is on the path, or env var CLANG_FORMAT points to it.
  20. # - 'clang-format-diff.py' is in the utils directory, or env var
  21. # points to it.CLANG_FORMAT_DIFF
  22. BASE_BRANCH=${1:-main}
  23. CLANG_FORMAT=${CLANG_FORMAT:-clang-format}
  24. if [ ! -f "$CLANG_FORMAT" ]; then
  25. echo missing clang-format: set CLANG_FORMAT or put clang-format in the PATH
  26. exit 1
  27. fi
  28. # Find clang-format-diff.py from an environment variable, or use a default
  29. CLANG_FORMAT_DIFF=${CLANG_FORMAT_DIFF:-./utils/clang-format-diff.py}
  30. if [ ! -f "$CLANG_FORMAT_DIFF" ]; then
  31. echo missing clang-format-diffy.py: set CLANG_FORMAT_DIFF or put it in ./utils/clang-format-diff.py
  32. exit 1
  33. fi
  34. echo "Comparing "$(git rev-parse HEAD)" against $BASE_BRANCH"
  35. FILES_TO_CHECK=$(git diff --name-only ${BASE_BRANCH} | grep -E ".*\.(cpp|cc|c\+\+|cxx|c|h|hpp)$")
  36. if [ -z "${FILES_TO_CHECK}" ]; then
  37. echo "No source code to check for formatting."
  38. exit 0
  39. fi
  40. FORMAT_DIFF=$(git diff -U0 ${BASE_BRANCH} -- ${FILES_TO_CHECK} | python3 "${CLANG_FORMAT_DIFF}" -p1 -style=file -binary "$CLANG_FORMAT")
  41. if [ -z "${FORMAT_DIFF}" ]; then
  42. echo "All source code in PR properly formatted."
  43. exit 0
  44. else
  45. echo "Found formatting errors!"
  46. echo "${FORMAT_DIFF}"
  47. exit 1
  48. fi