# -*- coding: utf-8 -*- r'''给 .ps1 文件补回 UTF-8 BOM,并检查哪些文件缺 BOM。 为什么必须补: PowerShell 读 .ps1 时,**没有 BOM 就按系统代码页(中文 Windows = GBK)解**。 文件本身是 UTF-8,于是中文全变乱码,接着就是一堆 "Unexpected token" 语法错误 —— 脚本直接跑不了。 edit 工具会把 BOM 剥掉,所以每次用 edit 改完 .ps1 都要补一次。 (这个坑今天踩了两次。) 用法:python _build/fix_ps1_bom.py ''' from __future__ import annotations import sys from pathlib import Path ROOT = Path(r"C:\Users\shu\Desktop\deepseekagent\LanRemote") BOM = b"\xef\xbb\xbf" SKIP_DIRS = (".git", "dist_exe", "pyinstaller_work", "_build\\jc", "out_java", "build", "node_modules") def should_skip(path: Path) -> bool: text = str(path) return any(s in text for s in SKIP_DIRS) def main() -> int: fixed = [] already = [] no_bom = [] for path in sorted(ROOT.rglob("*.ps1")): if should_skip(path): continue raw = path.read_bytes() if raw.startswith(BOM): already.append(path) continue # 补 BOM path.write_bytes(BOM + raw) fixed.append(path) print(" 补了 BOM 的 .ps1(%d 个):" % len(fixed)) for path in fixed: print(" " + str(path.relative_to(ROOT))) if not fixed: print(" (无)") print() print(" 本来就有 BOM 的: %d 个" % len(already)) # 复核:所有 .ps1 都该有 BOM print() print(" 复核:") missing = [] for path in sorted(ROOT.rglob("*.ps1")): if should_skip(path): continue if not path.read_bytes().startswith(BOM): missing.append(path) if missing: print(" 还有 %d 个缺 BOM:" % len(missing)) for path in missing: print(" " + str(path.relative_to(ROOT))) return 1 print(" 所有 .ps1 都有 BOM ✓") # 顺手看看 .bat 是不是 GBK(另一种编码规则) print() print(" .bat 编码检查(应该是 GBK/ANSI):") for path in sorted(ROOT.rglob("*.bat")): if should_skip(path): continue raw = path.read_bytes() try: raw.decode("gbk") note = "GBK ✓" except UnicodeDecodeError: try: raw.decode("utf-8") note = "其实是 UTF-8(可能有问题,.bat 要用 GBK)" except UnicodeDecodeError: note = "两种都不是?" print(" %-42s %s" % (str(path.relative_to(ROOT)), note)) return 0 if __name__ == "__main__": sys.exit(main())