lint-clang-format.sh 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. #!/usr/bin/env bash
  2. set -e
  3. script_path=$(cd -P -- "$(dirname -- "$0")" && pwd -P)
  4. cd "${script_path}/.." || exit 1
  5. if [ "$#" -eq "1" ]; then
  6. files=()
  7. while IFS= read -r file; do
  8. files+=("$file")
  9. done < <(
  10. git ls-files -- \
  11. '*.cpp' \
  12. '*.h' \
  13. '*.mm' \
  14. ':!:Base'
  15. )
  16. else
  17. files=()
  18. for file in "${@:2}"; do
  19. if [[ "${file}" == *".cpp" || "${file}" == *".h" || "${file}" == *".mm" ]]; then
  20. files+=("${file}")
  21. fi
  22. done
  23. fi
  24. if (( ${#files[@]} )); then
  25. TOOLCHAIN_DIR=Toolchain/Local/clang/bin
  26. CLANG_FORMAT=false
  27. if command -v clang-format-19 >/dev/null 2>&1 ; then
  28. CLANG_FORMAT=clang-format-19
  29. elif command -v brew >/dev/null 2>&1 && command -v "$(brew --prefix llvm@19)"/bin/clang-format >/dev/null 2>&1 ; then
  30. CLANG_FORMAT="$(brew --prefix llvm@19)"/bin/clang-format
  31. elif command -v $TOOLCHAIN_DIR/clang-format >/dev/null 2>&1 && $TOOLCHAIN_DIR/clang-format --version | grep -qF ' 19.' ; then
  32. CLANG_FORMAT=$TOOLCHAIN_DIR/clang-format
  33. elif command -v clang-format >/dev/null 2>&1 ; then
  34. CLANG_FORMAT=clang-format
  35. if ! "${CLANG_FORMAT}" --version | awk '{ if (substr($NF, 1, index($NF, ".") - 1) != 19) exit 1; }'; then
  36. echo "You are using '$("${CLANG_FORMAT}" --version)', which appears to not be clang-format 19."
  37. echo "It is very likely that the resulting changes are not what you wanted."
  38. fi
  39. else
  40. echo "clang-format-19 is not available, but C or C++ files need linting! Either skip this script, or install clang-format-19."
  41. echo "(If you install a package 'clang-format', please make sure it's version 19.)"
  42. exit 1
  43. fi
  44. if [ "$#" -gt "0" ] && [ "--overwrite-inplace" = "$1" ] ; then
  45. true # The only way to run this script.
  46. else
  47. # Note that this branch also covers --help, -h, -help, -?, etc.
  48. echo "USAGE: $0 --overwrite-inplace"
  49. echo "The argument is necessary to make you aware that this *will* overwrite your local files."
  50. exit 1
  51. fi
  52. echo "Using ${CLANG_FORMAT}"
  53. "${CLANG_FORMAT}" -style=file -i "${files[@]}"
  54. echo "Maybe some files have changed. Sorry, but clang-format doesn't indicate what happened."
  55. else
  56. echo "No .cpp, .h or .mm files to check."
  57. fi