uncrustify-wrapper.sh 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. #!/bin/sh
  2. set -eu
  3. # Convert leading spaces to tabs.
  4. fix_indentation_char () {
  5. unexpand --tabs=4 --first-only
  6. }
  7. # Add newline before namespace's closing bracket.
  8. add_newline_before_namespace_closing_bracket () {
  9. awk ' \
  10. /} \/[\/\*] namespace/ { \
  11. print '\n'; \
  12. } \
  13. { \
  14. print $0; \
  15. } \
  16. '
  17. }
  18. # Fix the indentation of ; character when it is alone on a line.
  19. fix_semicolon_indentation () {
  20. awk '
  21. { \
  22. if ($0 ~ /[\t];$/) { \
  23. output_str = ""; \
  24. last_indent_level = gsub(/\t/, "", last_line); \
  25. \
  26. for (ii = 0; ii < last_indent_level; ++ii) \
  27. output_str = output_str "\t"; \
  28. output_str = output_str ";"; \
  29. \
  30. print output_str; \
  31. } else { \
  32. print $0 \
  33. } \
  34. } \
  35. { \
  36. last_line = $0; \
  37. } \
  38. '
  39. }
  40. if [ "${OSTYPE-}" = "linux-gnu" ]; then
  41. OS="linux"
  42. elif [ "${OSTYPE-}" = "msys" ]; then
  43. OS="windows"
  44. else
  45. OS="linux"
  46. fi
  47. UNCRUSTIFY_INTERNAL=./scripts/uncrustify/bin/"${OS}"/uncrustify
  48. if [ -n "$2" ]; then
  49. # Do uncrustify.
  50. echo "$2"
  51. TEMPFILE_UNCRUSTIFY=$(mktemp)
  52. if ! ${UNCRUSTIFY-$UNCRUSTIFY_INTERNAL} -q -c "$1" -f "$2" > "$TEMPFILE_UNCRUSTIFY"; then
  53. echo "Failed to format '$2'"
  54. exit 1
  55. else
  56. TEMPFILE_AWK=$(mktemp)
  57. fix_indentation_char < "$TEMPFILE_UNCRUSTIFY" \
  58. | add_newline_before_namespace_closing_bracket \
  59. | fix_semicolon_indentation \
  60. > "$TEMPFILE_AWK"
  61. rm "$TEMPFILE_UNCRUSTIFY"
  62. # Only overwrite if there are differences.
  63. if ! cmp -s "$2" "$TEMPFILE_AWK"; then
  64. mv "$TEMPFILE_AWK" "$2"
  65. else
  66. rm "$TEMPFILE_AWK"
  67. fi
  68. fi
  69. fi