clang-format_precommit_hook 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. #!/bin/sh
  2. #
  3. # This pre-commit hook checks if any versions of clang-format
  4. # are installed, and if so, uses the installed version to format
  5. # the staged changes.
  6. #
  7. # To install, copy this script to `.git/hooks/pre-commit`:
  8. # cd .git/hooks && ln -s ../../tools/clang-format_precommit_hook pre-commit
  9. # and make sure that `clang-format` is installed on your system
  10. maj_min=1
  11. maj_max=8
  12. base=clang-format
  13. format=""
  14. # Redirect output to stderr.
  15. exec 1>&2
  16. # check if clang-format is installed
  17. type "$base" >/dev/null 2>&1 && format="$base"
  18. # if not, check all possible versions
  19. # (i.e. clang-format-<$maj_min-$maj_max>-<0-9>)
  20. if [ -z "$format" ]
  21. then
  22. for j in `seq $maj_max -1 $maj_min`
  23. do
  24. for i in `seq 0 9`
  25. do
  26. type "$base-$j.$i" >/dev/null 2>&1 && format="$base-$j.$i" && break
  27. done
  28. [ -z "$format" ] || break
  29. done
  30. fi
  31. # no versions of clang-format are installed
  32. if [ -z "$format" ]
  33. then
  34. echo "$base is not installed. Pre-commit hook will not be executed."
  35. exit 0
  36. fi
  37. if git rev-parse --verify HEAD >/dev/null 2>&1
  38. then
  39. against=HEAD
  40. else
  41. # Initial commit: diff against an empty tree object
  42. against=4b825dc642cb6eb9a060e54bf8d69288fbee4904
  43. fi
  44. # do the formatting
  45. for file in `git diff-index --cached --name-only $against`
  46. do
  47. case "$file" in
  48. *.h | *.hpp | *.c | *.cpp )
  49. "$format" -i "$file"
  50. ;;
  51. *)
  52. # do nothing with file
  53. ;;
  54. esac
  55. done