precommit.clang-format.sh 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. #!/usr/bin/env bash
  2. # This is a pre-commit hook for use with either mercurial or git.
  3. #
  4. # Install this by running the script with an argument of "install".
  5. #
  6. # All that does is add the following lines to .hg/hgrc:
  7. #
  8. # [hook]
  9. # pretxncommit.clang-format = [ ! -x ./coreconf/precommit.clang-format.sh ] || ./coreconf/precommit.clang-format.sh
  10. #
  11. # Or installs a symlink to .git/hooks/precommit:
  12. # $ ln -s ../../coreconf/precommit.clang-format.sh .git/hooks/pre-commit
  13. hash clang-format || exit 1
  14. [ "$(hg root 2>/dev/null)" = "$PWD" ] && hg=1 || hg=0
  15. [ "$(git rev-parse --show-toplevel 2>/dev/null)" = "$PWD" ] && git=1 || git=0
  16. if [ "$1" = "install" ]; then
  17. if [ "$hg" -eq 1 ]; then
  18. hgrc="$(hg root)"/.hg/hgrc
  19. if ! grep -q '^pretxncommit.clang-format' "$hgrc"; then
  20. echo '[hooks]' >> "$hgrc"
  21. echo 'pretxncommit.clang-format = [ ! -x ./coreconf/precommit.clang-format.sh ] || ./coreconf/precommit.clang-format.sh' >> "$hgrc"
  22. echo "Installed mercurial pretxncommit hook"
  23. exit
  24. fi
  25. fi
  26. if [ "$git" -eq 1 ]; then
  27. hook="$(git rev-parse --show-toplevel)"/.git/hooks/pre-commit
  28. if [ ! -e "$hook" ]; then
  29. ln -s ../../coreconf/precommit.clang-format.sh "$hook"
  30. echo "Installed git pre-commit hook"
  31. exit
  32. fi
  33. fi
  34. echo "Hook already installed, or not in NSS repo"
  35. exit 2
  36. fi
  37. err=0
  38. files=()
  39. if [ "$hg" -eq 1 ]; then
  40. files=($(hg status -m -a --rev tip^:tip | cut -f 2 -d ' ' -))
  41. fi
  42. if [ "$git" -eq 1 ]; then
  43. files=($(git status --porcelain | sed '/^[MACU]/{s/..//;p;};/^R/{s/^.* -> //;p;};d'))
  44. fi
  45. tmp=$(mktemp)
  46. trap 'rm -f "$tmp"' ERR EXIT
  47. for f in "${files[@]}"; do
  48. ext="${f##*.}"
  49. if [ "$ext" = "c" -o "$ext" = "h" -o "$ext" = "cc" ]; then
  50. [ "$hg" -eq 1 ] && hg cat -r tip "$f" > "$tmp"
  51. [ "$git" -eq 1 ] && git show :"$f" > "$tmp"
  52. if ! cat "$tmp" | clang-format -assume-filename="$f" | \
  53. diff -q "$tmp" - >/dev/null; then
  54. [ "$err" -eq 0 ] && echo "Formatting errors found in:" 1>&2
  55. echo " $f" 1>&2
  56. err=1
  57. fi
  58. fi
  59. done
  60. exit "$err"