file_format.sh 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. #!/usr/bin/env bash
  2. # This script ensures proper POSIX text file formatting and a few other things.
  3. # This is supplementary to clang_format.sh and black_format.sh, but should be
  4. # run before them.
  5. # We need dos2unix and recode.
  6. if [ ! -x "$(command -v dos2unix)" -o ! -x "$(command -v isutf8)" ]; then
  7. printf "Install 'dos2unix' and 'isutf8' (from the moreutils package) to use this script.\n"
  8. fi
  9. set -uo pipefail
  10. IFS=$'\n\t'
  11. # Loops through all text files tracked by Git.
  12. git grep -zIl '' |
  13. while IFS= read -rd '' f; do
  14. # Exclude some types of files.
  15. if [[ "$f" == *"csproj" ]]; then
  16. continue
  17. elif [[ "$f" == *"sln" ]]; then
  18. continue
  19. elif [[ "$f" == *".bat" ]]; then
  20. continue
  21. elif [[ "$f" == *"patch" ]]; then
  22. continue
  23. elif [[ "$f" == *"pot" ]]; then
  24. continue
  25. elif [[ "$f" == *"po" ]]; then
  26. continue
  27. elif [[ "$f" == "thirdparty/"* ]]; then
  28. continue
  29. elif [[ "$f" == *"/thirdparty/"* ]]; then
  30. continue
  31. elif [[ "$f" == "platform/android/java/lib/src/com/google"* ]]; then
  32. continue
  33. elif [[ "$f" == *"-so_wrap."* ]]; then
  34. continue
  35. fi
  36. # Ensure that files are UTF-8 formatted.
  37. isutf8 "$f" >> utf8-validation.txt 2>&1
  38. # Ensure that files have LF line endings and do not contain a BOM.
  39. dos2unix "$f" 2> /dev/null
  40. # Remove trailing space characters and ensures that files end
  41. # with newline characters. -l option handles newlines conveniently.
  42. perl -i -ple 's/\s*$//g' "$f"
  43. # Remove the character sequence "== true" if it has a leading space.
  44. perl -i -pe 's/\x20== true//g' "$f"
  45. done
  46. git diff --color > patch.patch
  47. # If no UTF-8 violations were collected and no patch has been
  48. # generated all is OK, clean up, and exit.
  49. if [ ! -s utf8-validation.txt ] && [ ! -s patch.patch ] ; then
  50. printf "Files in this commit comply with the formatting rules.\n"
  51. rm -f patch.patch utf8-validation.txt
  52. exit 0
  53. fi
  54. # Violations detected, notify the user, clean up, and exit.
  55. if [ -s utf8-validation.txt ]
  56. then
  57. printf "\n*** The following files contain invalid UTF-8 character sequences:\n\n"
  58. cat utf8-validation.txt
  59. fi
  60. if [ -s patch.patch ]
  61. then
  62. printf "\n*** The following differences were found between the code "
  63. printf "and the formatting rules:\n\n"
  64. cat patch.patch
  65. fi
  66. rm -f utf8-validation.txt patch.patch
  67. printf "\n*** Aborting, please fix your commit(s) with 'git commit --amend' or 'git rebase -i <hash>'\n"
  68. exit 1