check-newlines-at-eof.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. #!/usr/bin/env python3
  2. import os
  3. import subprocess
  4. import sys
  5. def run():
  6. """Check files checked in to git for trailing newlines at end of file."""
  7. files = subprocess.run(
  8. [
  9. "git", "ls-files", "--",
  10. "*.cpp",
  11. "*.h",
  12. "*.gml",
  13. "*.html",
  14. "*.js",
  15. "*.css",
  16. "*.sh",
  17. "*.py",
  18. "*.json",
  19. "CMake*.txt",
  20. "**/CMake*.txt",
  21. ":!:Kernel/FileSystem/ext2_fs.h",
  22. ':!:Userland/DevTools/HackStudio/LanguageServers/Cpp/Tests/*',
  23. ':!:Userland/Libraries/LibCpp/Tests/parser/*',
  24. ':!:Userland/Libraries/LibCpp/Tests/preprocessor/*'
  25. ],
  26. check=True,
  27. capture_output=True
  28. ).stdout.decode().strip('\n').split('\n')
  29. no_newline_at_eof_errors = []
  30. blank_lines_at_eof_errors = []
  31. did_fail = False
  32. for filename in files:
  33. with open(filename, "r") as f:
  34. f.seek(0, os.SEEK_END)
  35. f.seek(f.tell() - 1, os.SEEK_SET)
  36. if f.read(1) != '\n':
  37. did_fail = True
  38. no_newline_at_eof_errors.append(filename)
  39. continue
  40. while True:
  41. f.seek(f.tell() - 2, os.SEEK_SET)
  42. char = f.read(1)
  43. if not char.isspace():
  44. break
  45. if char == '\n':
  46. did_fail = True
  47. blank_lines_at_eof_errors.append(filename)
  48. break
  49. if no_newline_at_eof_errors:
  50. print("Files with no newline at the end:", " ".join(no_newline_at_eof_errors))
  51. if blank_lines_at_eof_errors:
  52. print("Files that have blank lines at the end:", " ".join(blank_lines_at_eof_errors))
  53. if did_fail:
  54. sys.exit(1)
  55. if __name__ == '__main__':
  56. os.chdir(os.path.dirname(__file__) + "/..")
  57. run()