lint-clang-format.sh 2.5 KB

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