file_format.py 1.3 KB

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