header_guards.sh 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. #!/bin/bash
  2. if [ ! -f "SConstruct" ]; then
  3. echo "Warning: This script is intended to be run from the root of the Godot repository."
  4. echo "Some of the paths checks may not work as intended from a different folder."
  5. fi
  6. files_invalid_guard=""
  7. for file in $(find . -name "*.hpp" -print); do
  8. # Skip generated files.
  9. if [[ "$file" == "./gen/"* || "$file" == "./include/gen/"* ]]; then continue; fi
  10. # Skip the test project.
  11. if [[ "$file" == "./test/"* ]]; then continue; fi
  12. bname=$(basename $file .hpp)
  13. # NOTE: The "GODOT_CPP_" prefix is already used by the generated
  14. # bindings, so we can't use that. We'll use "GODOT_" instead.
  15. prefix="GODOT_"
  16. # ^^ is bash builtin for UPPERCASE.
  17. guard="${prefix}${bname^^}_HPP"
  18. # Replaces guards to use computed name.
  19. # We also add some \n to make sure there's a proper separation.
  20. sed -i $file -e "0,/ifndef/s/#ifndef.*/\n#ifndef $guard/"
  21. sed -i $file -e "0,/define/s/#define.*/#define $guard\n/"
  22. sed -i $file -e "$ s/#endif.*/\n#endif \/\/ $guard/"
  23. # Removes redundant \n added before, if they weren't needed.
  24. sed -i $file -e "/^$/N;/^\n$/D"
  25. # Check that first ifndef (should be header guard) is at the expected position.
  26. # If not it can mean we have some code before the guard that should be after.
  27. # "31" is the expected line with the copyright header.
  28. first_ifndef=$(grep -n -m 1 "ifndef" $file | sed 's/\([0-9]*\).*/\1/')
  29. if [[ "$first_ifndef" != "31" ]]; then
  30. files_invalid_guard+="$file\n"
  31. fi
  32. done
  33. if [[ ! -z "$files_invalid_guard" ]]; then
  34. echo -e "The following files were found to have potentially invalid header guard:\n"
  35. echo -e "$files_invalid_guard"
  36. fi
  37. diff=$(git diff --color)
  38. # If no diff has been generated all is OK, clean up, and exit.
  39. if [ -z "$diff" ] ; then
  40. printf "Files in this commit comply with the header guards formatting rules.\n"
  41. exit 0
  42. fi
  43. # A diff 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 header guards formatting rules:\n\n"
  46. echo "$diff"
  47. printf "\n*** Aborting, please fix your commit(s) with 'git commit --amend' or 'git rebase -i <hash>'\n"
  48. exit 1