file_format.sh 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  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. # 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. done
  22. diff=$(git diff --color)
  23. # If no patch has been generated all is OK, clean up, and exit.
  24. if [ -z "$diff" ] ; then
  25. printf "Files in this commit comply with the formatting rules.\n"
  26. rm -f patch.patch
  27. exit 0
  28. fi
  29. # A patch has been created, notify the user, clean up, and exit.
  30. printf "\n*** The following differences were found between the code "
  31. printf "and the formatting rules:\n\n"
  32. echo "$diff"
  33. printf "\n*** Aborting, please fix your commit(s) with 'git commit --amend' or 'git rebase -i <hash>'\n"
  34. exit 1