format.sh 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. #!/usr/bin/env bash
  2. set -uo pipefail
  3. IFS=$'\n\t'
  4. # Loops through all text files tracked by Git.
  5. git grep -zIl '' |
  6. while IFS= read -rd '' f; do
  7. # Exclude csproj and hdr files.
  8. if [[ "$f" == *"csproj" ]]; then
  9. continue
  10. elif [[ "$f" == *"hdr" ]]; then
  11. continue
  12. fi
  13. # Ensures that files are UTF-8 formatted.
  14. recode UTF-8 "$f" 2> /dev/null
  15. # Ensures that files have LF line endings.
  16. dos2unix "$f" 2> /dev/null
  17. # Ensures that files do not contain a BOM.
  18. sed -i '1s/^\xEF\xBB\xBF//' "$f"
  19. # Ensures that files end with newline characters.
  20. tail -c1 < "$f" | read -r _ || echo >> "$f";
  21. done
  22. git diff > patch.patch
  23. FILESIZE="$(stat -c%s patch.patch)"
  24. MAXSIZE=5
  25. # If no patch has been generated all is OK, clean up, and exit.
  26. if (( FILESIZE < MAXSIZE )); then
  27. printf "Files in this commit comply with the formatting rules.\n"
  28. rm -f patch.patch
  29. exit 0
  30. fi
  31. # A patch has been created, notify the user, clean up, and exit.
  32. printf "\n*** The following differences were found between the code "
  33. printf "and the formatting rules:\n\n"
  34. cat patch.patch
  35. printf "\n*** Aborting, please fix your commit(s) with 'git commit --amend' or 'git rebase -i <hash>'\n"
  36. rm -f patch.patch
  37. exit 1