check-newlines-at-eof.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. #!/usr/bin/env python3
  2. import os
  3. import re
  4. import subprocess
  5. import sys
  6. RE_RELEVANT_FILE_EXTENSION = re.compile('\\.(cpp|h|mm|swift|gml|html|js|css|sh|py|json|txt|cmake|gn|gni)$')
  7. def should_check_file(filename):
  8. if not RE_RELEVANT_FILE_EXTENSION.search(filename):
  9. return False
  10. if filename.startswith('Tests/LibWeb/Layout/'):
  11. return False
  12. if filename.startswith('Tests/LibWeb/Ref/'):
  13. return False
  14. if filename.startswith('Tests/LibWeb/Text/'):
  15. return False
  16. if filename.startswith('Meta/CMake/vcpkg/overlay-ports/'):
  17. return False
  18. if filename.endswith('.txt'):
  19. return 'CMake' in filename
  20. return True
  21. def find_files_here_or_argv():
  22. if len(sys.argv) > 1:
  23. raw_list = sys.argv[1:]
  24. else:
  25. process = subprocess.run(["git", "ls-files"], check=True, capture_output=True)
  26. raw_list = process.stdout.decode().strip('\n').split('\n')
  27. return filter(should_check_file, raw_list)
  28. def run():
  29. """Check files checked in to git for trailing newlines at end of file."""
  30. no_newline_at_eof_errors = []
  31. blank_lines_at_eof_errors = []
  32. did_fail = False
  33. for filename in find_files_here_or_argv():
  34. with open(filename, "r") as f:
  35. f.seek(0, os.SEEK_END)
  36. f.seek(f.tell() - 1, os.SEEK_SET)
  37. if f.read(1) != '\n':
  38. did_fail = True
  39. no_newline_at_eof_errors.append(filename)
  40. continue
  41. while True:
  42. f.seek(f.tell() - 2, os.SEEK_SET)
  43. char = f.read(1)
  44. if not char.isspace():
  45. break
  46. if char == '\n':
  47. did_fail = True
  48. blank_lines_at_eof_errors.append(filename)
  49. break
  50. if no_newline_at_eof_errors:
  51. print("Files with no newline at the end:", " ".join(no_newline_at_eof_errors))
  52. if blank_lines_at_eof_errors:
  53. print("Files that have blank lines at the end:", " ".join(blank_lines_at_eof_errors))
  54. if did_fail:
  55. sys.exit(1)
  56. if __name__ == '__main__':
  57. os.chdir(os.path.dirname(__file__) + "/..")
  58. run()