check-style.sh 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. #!/bin/bash
  2. #
  3. # Script to check include/test code for common pybind11 code style errors.
  4. #
  5. # This script currently checks for
  6. #
  7. # 1. use of tabs instead of spaces
  8. # 2. MSDOS-style CRLF endings
  9. # 3. trailing spaces
  10. # 4. missing space between keyword and parenthesis, e.g.: for(, if(, while(
  11. # 5. Missing space between right parenthesis and brace, e.g. 'for (...){'
  12. # 6. opening brace on its own line. It should always be on the same line as the
  13. # if/while/for/do statement.
  14. #
  15. # Invoke as: tools/check-style.sh
  16. #
  17. check_style_errors=0
  18. IFS=$'\n'
  19. found="$( GREP_COLORS='mt=41' GREP_COLOR='41' grep $'\t' include tests/*.{cpp,py,h} docs/*.rst -rn --color=always )"
  20. if [ -n "$found" ]; then
  21. # The mt=41 sets a red background for matched tabs:
  22. echo -e '\033[31;01mError: found tab characters in the following files:\033[0m'
  23. check_style_errors=1
  24. echo "$found" | sed -e 's/^/ /'
  25. fi
  26. found="$( grep -IUlr $'\r' include tests/*.{cpp,py,h} docs/*.rst --color=always )"
  27. if [ -n "$found" ]; then
  28. echo -e '\033[31;01mError: found CRLF characters in the following files:\033[0m'
  29. check_style_errors=1
  30. echo "$found" | sed -e 's/^/ /'
  31. fi
  32. found="$(GREP_COLORS='mt=41' GREP_COLOR='41' grep '[[:blank:]]\+$' include tests/*.{cpp,py,h} docs/*.rst -rn --color=always )"
  33. if [ -n "$found" ]; then
  34. # The mt=41 sets a red background for matched trailing spaces
  35. echo -e '\033[31;01mError: found trailing spaces in the following files:\033[0m'
  36. check_style_errors=1
  37. echo "$found" | sed -e 's/^/ /'
  38. fi
  39. found="$(grep '\<\(if\|for\|while\|catch\)(\|){' include tests/*.{cpp,h} -rn --color=always)"
  40. if [ -n "$found" ]; then
  41. echo -e '\033[31;01mError: found the following coding style problems:\033[0m'
  42. check_style_errors=1
  43. echo "$found" | sed -e 's/^/ /'
  44. fi
  45. found="$(awk '
  46. function prefix(filename, lineno) {
  47. return " \033[35m" filename "\033[36m:\033[32m" lineno "\033[36m:\033[0m"
  48. }
  49. function mark(pattern, string) { sub(pattern, "\033[01;31m&\033[0m", string); return string }
  50. last && /^\s*{/ {
  51. print prefix(FILENAME, FNR-1) mark("\\)\\s*$", last)
  52. print prefix(FILENAME, FNR) mark("^\\s*{", $0)
  53. last=""
  54. }
  55. { last = /(if|for|while|catch|switch)\s*\(.*\)\s*$/ ? $0 : "" }
  56. ' $(find include -type f) tests/*.{cpp,h} docs/*.rst)"
  57. if [ -n "$found" ]; then
  58. check_style_errors=1
  59. echo -e '\033[31;01mError: braces should occur on the same line as the if/while/.. statement. Found issues in the following files:\033[0m'
  60. echo "$found"
  61. fi
  62. exit $check_style_errors