file_format.sh 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. #!/usr/bin/env bash
  2. # This script ensures proper POSIX text file formatting and a few other things.
  3. set -uo pipefail
  4. IFS=$'\n\t'
  5. # Loops through all text files tracked by Git.
  6. git grep -zIl '' |
  7. while IFS= read -rd '' f; do
  8. # Exclude some types of files.
  9. if [[ "$f" == *"csproj" ]]; then
  10. continue
  11. elif [[ "$f" == *"hdr" ]]; then
  12. continue
  13. fi
  14. # Ensure that files are UTF-8 formatted.
  15. recode UTF-8 "$f" 2> /dev/null
  16. # Ensure that files have LF line endings and do not contain a BOM.
  17. dos2unix "$f" 2> /dev/null
  18. # Remove trailing space characters and ensures that files end
  19. # with newline characters. -l option handles newlines conveniently.
  20. perl -i -ple 's/\s*$//g' "$f"
  21. # Remove the character sequence "== true" if it has a leading space.
  22. perl -i -pe 's/\x20== true//g' "$f"
  23. # We don't want to change lines around braces in godot/tscn files.
  24. if [[ "$f" == *"godot" ]]; then
  25. continue
  26. elif [[ "$f" == *"tscn" ]]; then
  27. continue
  28. fi
  29. # Disallow empty lines after the opening brace.
  30. sed -z -i 's/\x7B\x0A\x0A/\x7B\x0A/g' "$f"
  31. # Disallow some empty lines before the closing brace.
  32. sed -z -i 's/\x0A\x0A\x7D/\x0A\x7D/g' "$f"
  33. done
  34. git diff > patch.patch
  35. FILESIZE="$(stat -c%s patch.patch)"
  36. MAXSIZE=5
  37. # If no patch has been generated all is OK, clean up, and exit.
  38. if (( FILESIZE < MAXSIZE )); then
  39. printf "Files in this commit comply with the formatting rules.\n"
  40. rm -f patch.patch
  41. exit 0
  42. fi
  43. # A patch has been created, notify the user, clean up, and exit.
  44. printf "\n*** The following differences were found between the code "
  45. printf "and the formatting rules:\n\n"
  46. cat patch.patch
  47. printf "\n*** Aborting, please fix your commit(s) with 'git commit --amend' or 'git rebase -i <hash>'\n"
  48. rm -f patch.patch
  49. exit 1