file_format.py 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. import sys
  4. if len(sys.argv) < 2:
  5. print("Invalid usage of file_format.py, it should be called with a path to one or multiple files.")
  6. sys.exit(1)
  7. BOM = b"\xef\xbb\xbf"
  8. changed = []
  9. invalid = []
  10. for file in sys.argv[1:]:
  11. try:
  12. with open(file, "rt", encoding="utf-8") as f:
  13. original = f.read()
  14. except UnicodeDecodeError:
  15. invalid.append(file)
  16. continue
  17. if original == "":
  18. continue
  19. EOL = "\r\n" if file.endswith((".csproj", ".sln", ".bat")) or file.startswith("misc/msvs") else "\n"
  20. WANTS_BOM = file.endswith((".csproj", ".sln"))
  21. revamp = EOL.join([line.rstrip("\n\r\t ") for line in original.splitlines(True)]).rstrip(EOL) + EOL
  22. new_raw = revamp.encode(encoding="utf-8")
  23. if not WANTS_BOM and new_raw.startswith(BOM):
  24. new_raw = new_raw[len(BOM) :]
  25. elif WANTS_BOM and not new_raw.startswith(BOM):
  26. new_raw = BOM + new_raw
  27. with open(file, "rb") as f:
  28. old_raw = f.read()
  29. if old_raw != new_raw:
  30. changed.append(file)
  31. with open(file, "wb") as f:
  32. f.write(new_raw)
  33. if changed:
  34. for file in changed:
  35. print(f"FIXED: {file}")
  36. if invalid:
  37. for file in invalid:
  38. print(f"REQUIRES MANUAL CHANGES: {file}")
  39. sys.exit(1)