black_format.sh 1.0 KB

123456789101112131415161718192021222324252627
  1. #!/usr/bin/env bash
  2. # This script runs black on all Python files in the repo.
  3. set -uo pipefail
  4. # Apply black.
  5. echo -e "Formatting Python files..."
  6. PY_FILES=$(git ls-files -- '*SConstruct' '*SCsub' '*.py' ':!:.git/*' ':!:thirdparty/*')
  7. black -l 120 $PY_FILES
  8. diff=$(git diff --color)
  9. # If no diff has been generated all is OK, clean up, and exit.
  10. if [ -z "$diff" ] ; then
  11. printf "\e[1;32m*** Files in this commit comply with the black style rules.\e[0m\n"
  12. exit 0
  13. fi
  14. # A diff has been created, notify the user, clean up, and exit.
  15. printf "\n\e[1;33m*** The following changes must be made to comply with the formatting rules:\e[0m\n\n"
  16. # Perl commands replace trailing spaces with `·` and tabs with `<TAB>`.
  17. printf "$diff\n" | perl -pe 's/(.*[^ ])( +)(\e\[m)$/my $spaces="·" x length($2); sprintf("$1$spaces$3")/ge' | perl -pe 's/(.*[^\t])(\t+)(\e\[m)$/my $tabs="<TAB>" x length($2); sprintf("$1$tabs$3")/ge'
  18. printf "\n\e[1;91m*** Please fix your commit(s) with 'git commit --amend' or 'git rebase -i <hash>'\e[0m\n"
  19. exit 1