utf8_check.py 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """PostToolUse hook (GLOBAL): 写源码后校验文件为合法 UTF-8。
  4. 对齐 Rules §8:本环境 PHP 默认 UTF-8,Windows 下误用 GBK 保存会静默损坏中文。
  5. 仅对文本类源文件生效。非阻断:发现非 UTF-8 时 exit 1(warning 回显 AI)。
  6. 其他故障静默 exit 0。
  7. """
  8. import sys
  9. import os
  10. import json
  11. TEXT_EXT = {".php", ".html", ".htm", ".js", ".css", ".json", ".py", ".md",
  12. ".txt", ".xml", ".sql", ".conf", ".ini", ".cfg"}
  13. def main():
  14. try:
  15. raw = sys.stdin.read()
  16. if not raw.strip():
  17. return 0
  18. data = json.loads(raw)
  19. except Exception:
  20. return 0
  21. tool_input = data.get("tool_input", {}) or {}
  22. path = (
  23. tool_input.get("filePath")
  24. or tool_input.get("file_path")
  25. or tool_input.get("path")
  26. or ""
  27. )
  28. if not path:
  29. return 0
  30. path = os.path.abspath(path)
  31. if os.path.splitext(path)[1].lower() not in TEXT_EXT:
  32. return 0
  33. if not os.path.isfile(path):
  34. return 0
  35. try:
  36. with open(path, "rb") as f:
  37. data_bytes = f.read()
  38. except Exception:
  39. return 0
  40. try:
  41. data_bytes.decode("utf-8")
  42. except UnicodeDecodeError:
  43. print("[UTF8-WARN] 文件不是合法 UTF-8 编码(可能是 GBK 损坏),请转 UTF-8 保存(Rules §8)")
  44. return 1
  45. return 0
  46. if __name__ == "__main__":
  47. sys.exit(main())