From 5742622ead07cbe0bc3e7dd71e2d30890e4626a4 Mon Sep 17 00:00:00 2001 From: Codex Agent Date: Tue, 13 Oct 2026 18:24:10 +0800 Subject: [PATCH] =?UTF-8?q?=E6=8A=8A=20BOM=20=E5=9D=91=E5=81=9A=E6=88=90?= =?UTF-8?q?=E8=87=AA=E5=8A=A8=E9=98=B2=E7=BA=BF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 10-04 记过的坑 6, 10-13 又踩了一次: 编辑 .ps1 会丢 BOM, Windows PowerShell 5.1 随即按 GBK 解析中文, 报出一堆行号对不上的语法错。而且用 pwsh 7 做"语法检查" 能正确处理无 BOM 的 UTF-8, 会给出假的 ✅ —— 必须做字节级检查。 新增 tests/test_ps1_bom.py: 字节级校验 scripts/*.ps1 都以 EF BB BF 开头, 并检查带 BOM 读出来不含替换符(编码未损坏)。 这个测试本身也验证过"能失败": 故意去掉 install_logon_task.ps1 的 BOM 后, 它准确报出文件名与前 3 字节, 并提示用 utf-8-sig 写回。 (只验证"能通过"的测试等于没测。) --- tests/test_ps1_bom.py | 53 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 tests/test_ps1_bom.py diff --git a/tests/test_ps1_bom.py b/tests/test_ps1_bom.py new file mode 100644 index 0000000..758088b --- /dev/null +++ b/tests/test_ps1_bom.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +"""PowerShell 脚本必须带 UTF-8 BOM。 + +背景(10-04 坑 6, 10-13 又踩了一次): +`scripts/*.ps1` 里有中文注释和中文提示串。文件没有 BOM 时, Windows PowerShell +5.1 会按**系统 ANSI 代码页(GBK)** 解析, 中文被拆成乱码字节, 于是报出一堆 +"行号对不上"的语法错, 而且报的行号会指到别的语句上, 极难定位。 + +更坑的是: 用 pwsh 7 / PowerShell Core 做的"语法检查"能正确处理无 BOM 的 UTF-8, +会给出假的 ✅。所以必须用字节级检查, 不能靠解析器。 + +编辑器(包括各种自动改写工具)保存时常把 BOM 丢掉, 所以这里做成测试而不是一次性修复。 +""" +import os +import sys +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +SCRIPTS = ROOT / 'scripts' +BOM = b'\xef\xbb\xbf' + + +class Ps1BomTest(unittest.TestCase): + + def files(self): + return sorted(SCRIPTS.glob('*.ps1')) + + def test_there_are_ps1_files_to_check(self): + # 防止 glob 路径写错导致这个测试空转(空列表会让下面全部通过) + self.assertTrue(self.files(), '没找到 scripts/*.ps1, 测试本身失效了') + + def test_every_ps1_starts_with_utf8_bom(self): + bad = [] + for p in self.files(): + head = p.read_bytes()[:3] + if head != BOM: + bad.append('%s (前 3 字节: %s)' % (p.name, head.hex(' ').upper())) + self.assertFalse( + bad, + '这些 .ps1 缺 UTF-8 BOM, Windows PowerShell 5.1 会按 GBK 解析中文而报错:\n ' + + '\n '.join(bad) + + '\n修复: 读成 UTF-8 后以 utf-8-sig 写回。') + + def test_no_ps1_contains_gbk_decodable_mojibake(self): + """带 BOM 的文件读出来不应有乱码替换符。""" + for p in self.files(): + text = p.read_text(encoding='utf-8-sig') + self.assertNotIn('\ufffd', text, '%s 含替换符, 可能编码已损坏' % p.name) + + +if __name__ == '__main__': + unittest.main()