file_format.sh 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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 recode)" ]; then
  7. printf "Install 'dos2unix' and 'recode' 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" == *".out" ]]; then
  20. # GDScript integration testing files.
  21. continue
  22. elif [[ "$f" == *"patch" ]]; then
  23. continue
  24. elif [[ "$f" == *"pot" ]]; then
  25. continue
  26. elif [[ "$f" == *"po" ]]; then
  27. continue
  28. elif [[ "$f" == "thirdparty"* ]]; then
  29. continue
  30. elif [[ "$f" == "platform/android/java/lib/src/com/google"* ]]; then
  31. continue
  32. elif [[ "$f" == *"-so_wrap."* ]]; then
  33. continue
  34. fi
  35. # Ensure that files are UTF-8 formatted.
  36. recode UTF-8 "$f" 2> /dev/null
  37. # Ensure that files have LF line endings and do not contain a BOM.
  38. dos2unix "$f" 2> /dev/null
  39. # Remove trailing space characters and ensures that files end
  40. # with newline characters. -l option handles newlines conveniently.
  41. perl -i -ple 's/\s*$//g' "$f"
  42. done
  43. git diff --color > patch.patch
  44. # If no patch has been generated all is OK, clean up, and exit.
  45. if [ ! -s patch.patch ] ; then
  46. printf "Files in this commit comply with the formatting rules.\n"
  47. rm -f patch.patch
  48. exit 0
  49. fi
  50. # A patch has been created, notify the user, clean up, and exit.
  51. printf "\n*** The following differences were found between the code "
  52. printf "and the formatting rules:\n\n"
  53. cat patch.patch
  54. printf "\n*** Aborting, please fix your commit(s) with 'git commit --amend' or 'git rebase -i <hash>'\n"
  55. rm -f patch.patch
  56. exit 1