Skip to content

armgit / peach

Public Imported from GitHub
0

Peach: Local-first video metadata scraper and media manager.

fix: lock every subprocess text pipe to UTF-8 and guard it with a test

Peach local maintenancec4f345c562dc
diff --git a/docs/HANDOFF.md b/docs/HANDOFF.md
index 255e20174..7d5ddad59 100644
--- a/docs/HANDOFF.md
+++ b/docs/HANDOFF.md
@@ -51,6 +51,7 @@
- 「全量 unittest discover 会挂起 / 会话输出消失」这条 2026-08-17 的结论已被证伪,成因另在别处。连跑三次全量 197 项均正常结束,通过时输出仅 6.9 KB。真实机制是 `tests/test_web_ui.py` 对整页做 `assertIn`:`self.page` 是约 189 KB 的 `index.html`,unittest 的失败消息会把整个容器原样打印,**一条断言失败就产出 195 KB 输出**,工具管道遇到超大输出会转存成文件,看起来就像输出消失。已改为有界的 `assertPageContains`/`assertPageLacks`,同样的失败现在是 861 字节。这不影响「唯一入口是 `& .\scripts\test.ps1`」的结论,但不要再把它归因于运行器竞态。
- Windows 上探测进程存活**绝不能用 `os.kill(pid, 0)`**。`signal.CTRL_C_EVENT == 0`,所以这个 Unix 经典写法实际调用 `GenerateConsoleCtrlEvent(CTRL_C_EVENT, ...)`:对控制台组内的 PID 会把 Ctrl+C 发给整个进程组(信号异步投递,`KeyboardInterrupt` 要到下一次控制台 I/O 才浮出,看起来像凭空报错);对非组长的活进程则报 WinError 87,而旧代码把 87 当作「进程已死」,活着的任务会被判定为已死、锁被后来者抢走。`PidFileLock._running` 已改用 `OpenProcess` + `GetExitCodeProcess`,`test_liveness_probe_never_signals_its_own_console` 守这条线。这个故障只在真实控制台里出现,重定向和无控制台环境永远不复现——不要因为工具管道跑得过就认为没问题。
- 含中文的 `.ps1` 必须带 UTF-8 BOM。没有 BOM 时 Windows PowerShell 5.1 按 ANSI(简中系统即 GBK)读文件,中文被解成乱码后引号配对错乱,脚本在解析期就失败并闪退;报错行还会落在纯 ASCII 的语句上(实测 `test.ps1` 报在第 18 行的 `Join-Path`,真正的坏行在别处),极难定位。pwsh 7 默认按 UTF-8 读无 BOM 文件,同一份字节实测 7.6.3 解析通过、5.1 报 2 处错误。所以**默认终端是 pwsh 7 也不能免疫**:双击 `.ps1` 或右键「使用 PowerShell 运行」走的是文件关联的 `powershell.exe`(5.1),解析失败后窗口立即关闭,连报错都来不及看。`test_powershell_scripts_with_chinese_carry_a_utf8_bom` 守这条线。
+- 上一条只写成知识没有强制机制,于是同类写法又长了回来。AST 审计发现 6 处仍是裸 `text=True`,其中 `src/peach/versioning.py` 是生产代码——它读 git 输出,而本仓库的提交信息就是中文的,拿 `282f8d9` 自己的标题即可复现 `stdout=None`。已全部锁定 UTF-8,并加 `tests/test_subprocess_encoding.py` 扫全仓强制。该守卫只认 `subprocess.*` 字面调用,包装器(如 `VersionManager._git` 走注入的 `self._execute`)看不见,那个盲点由同文件里一条显式断言补。
- 权限规则里的反斜杠必须双写。匹配器把 `\` 当转义字符,JSON 写 `"& .\\scripts\\test.ps1"` 解码成单反斜杠后 `\s`、`\t` 不再是字面反斜杠,规则匹配不上,非交互会话直接判拒、任务中断。正确写法是 JSON 里 `"& .\\\\scripts\\\\test.ps1"`;旁证是自动生成过的可用规则 `'R:\\\\media\\\\创作者'` 与 `\\(Get-ChildItem`,路径和括号一律双写。用正斜杠写的规则不受影响。改完要新开会话才生效——配置在会话启动时加载。
- `.claude/settings.local.json` 在 `.gitignore` 里,26 个 worktree 无一带有它,所以写在那里的允许规则只在主工作树生效——而项目规矩要求测试在 worktree 里跑。`& .\scripts\test.ps1` 的允许规则因此放在被跟踪的 `.claude/settings.json`,随代码进入每个 worktree。手工拼 venv 路径的命令(`python.exe -m unittest *` 等)刻意不上提到共享配置:那是 AGENTS.md 明令禁止的路径,共享化等于给违规开绿灯。
- 2026-08-17:PowerShell 工具会在调用中途被 session teardown 掐断,丢失的结果被错标成用户拒绝
diff --git a/scripts/agent_worktree.py b/scripts/agent_worktree.py
index ce337e99d..0f2aa15ad 100644
--- a/scripts/agent_worktree.py
+++ b/scripts/agent_worktree.py
@@ -15,7 +15,8 @@ def _git(repo: Path, *args: str, check: bool = True) -> subprocess.CompletedProc
command = [
"git", "-c", f"safe.directory={repo.as_posix()}", "-C", str(repo), *args,
]
- result = subprocess.run(command, text=True, capture_output=True, check=False)
+ result = subprocess.run(command, text=True, encoding="utf-8", errors="replace",
+ capture_output=True, check=False)
if check and result.returncode:
raise WorkspaceError((result.stderr or result.stdout).strip())
return result
diff --git a/scripts/creator_boards.py b/scripts/creator_boards.py
index 9e69abe74..920aab0eb 100644
--- a/scripts/creator_boards.py
+++ b/scripts/creator_boards.py
@@ -67,6 +67,8 @@ def cell_height(ffprobe: str, path: Path) -> int | None:
],
capture_output=True,
text=True,
+ encoding="utf-8",
+ errors="replace",
)
try:
width, height = (int(value) for value in result.stdout.strip().split(","))
@@ -127,6 +129,8 @@ def build_board(ffmpeg: str, ffprobe: str, paths: list[Path], destination: Path)
],
capture_output=True,
text=True,
+ encoding="utf-8",
+ errors="replace",
)
if result.returncode != 0:
print(" ffmpeg:", result.stderr.strip()[:160])
diff --git a/scripts/traffic_watch.py b/scripts/traffic_watch.py
index 29a3d6f1a..f1abaa2cf 100644
--- a/scripts/traffic_watch.py
+++ b/scripts/traffic_watch.py
@@ -141,6 +141,8 @@ def owned_python_jobs() -> list[tuple[str, str]]:
],
capture_output=True,
text=True,
+ encoding="utf-8",
+ errors="replace",
timeout=60,
)
jobs = []
diff --git a/src/peach/versioning.py b/src/peach/versioning.py
index 19b2102dc..3309e95fb 100644
--- a/src/peach/versioning.py
+++ b/src/peach/versioning.py
@@ -63,6 +63,8 @@ class VersionManager:
],
capture_output=True,
text=True,
+ encoding="utf-8",
+ errors="replace",
timeout=timeout,
check=False,
creationflags=creationflags,
diff --git a/tests/test_job_status.py b/tests/test_job_status.py
index 609ca51f3..9e2405e35 100644
--- a/tests/test_job_status.py
+++ b/tests/test_job_status.py
@@ -33,6 +33,8 @@ class JobStatusTests(unittest.TestCase):
cwd=SCRIPT.parents[1],
capture_output=True,
text=True,
+ encoding="utf-8",
+ errors="replace",
check=False,
)
self.assertEqual(result.returncode, 0, result.stderr)
diff --git a/tests/test_subprocess_encoding.py b/tests/test_subprocess_encoding.py
new file mode 100644
index 000000000..3425469fa
--- /dev/null
+++ b/tests/test_subprocess_encoding.py
@@ -0,0 +1,90 @@
+"""禁止 subprocess 文本模式不写 encoding。
+
+Windows 上 Python 的文本 I/O 不写 `encoding` 时按本机 ANSI 解码(简中系统是
+`cp936`/GBK)。子进程输出只要含中文,读取线程就抛 `UnicodeDecodeError`,而
+`subprocess.run` **本身不抛异常、返回码正常**,`stdout` 静默变成 `None`:
+
+ >>> subprocess.run(["git","log","-1","--format=%s","282f8d9"],
+ ... capture_output=True, text=True)
+ UnicodeDecodeError: 'gbk' codec can't decode byte 0xae in position 2
+ AttributeError: 'NoneType' object has no attribute 'strip'
+
+这个坑修过一次(`282f8d9`,改的正是 `tests/test_job_status.py`),但只覆盖了
+同文件里的一个调用,其余 5 处照旧——包括 `src/peach/versioning.py` 这段生产
+代码,它读 git 输出,而本仓库的提交信息就是中文的。
+
+HANDOFF 里记了这条知识却没有强制机制,于是同类写法又长了回来。按项目约定
+「必须每次成立的规则要由脚本、测试或 hook 强制」,这条测试就是那个机制。
+"""
+from __future__ import annotations
+
+import ast
+import unittest
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parents[1]
+SCANNED = ("src", "scripts", "tests")
+TEXT_FLAGS = ("text", "universal_newlines")
+
+
+def _subprocess_calls(tree: ast.AST):
+ """产出 (行号, 关键字字典),只看 subprocess 的进程启动调用。"""
+ for node in ast.walk(tree):
+ if not isinstance(node, ast.Call):
+ continue
+ name = ast.unparse(node.func)
+ if "subprocess" not in name:
+ continue
+ if not name.endswith((".run", ".Popen", ".check_output", ".call",
+ ".check_call")):
+ continue
+ yield node.lineno, {kw.arg: ast.unparse(kw.value)
+ for kw in node.keywords if kw.arg}
+
+
+def offenders() -> list[str]:
+ found = []
+ for folder in SCANNED:
+ for path in sorted((ROOT / folder).rglob("*.py")):
+ tree = ast.parse(path.read_text(encoding="utf-8"))
+ for line, keywords in _subprocess_calls(tree):
+ text_mode = any(keywords.get(flag) == "True" for flag in TEXT_FLAGS)
+ if text_mode and not keywords.get("encoding"):
+ found.append(f"{path.relative_to(ROOT).as_posix()}:{line}")
+ return found
+
+
+class SubprocessEncodingTests(unittest.TestCase):
+ def test_no_text_mode_subprocess_without_an_explicit_encoding(self):
+ found = offenders()
+ self.assertEqual(found, [], "这些调用会在中文输出上静默丢空 stdout:\n "
+ + "\n ".join(found))
+
+ def test_the_guard_actually_detects_the_pattern(self):
+ # 守卫自身必须可证伪,否则它可能只是恒真。
+ tree = ast.parse("import subprocess\n"
+ "subprocess.run(['git'], capture_output=True, text=True)\n")
+ calls = list(_subprocess_calls(tree))
+ self.assertEqual(len(calls), 1)
+ self.assertNotIn("encoding", calls[0][1])
+
+ def test_the_wrapper_blind_spot_is_covered_by_hand(self):
+ """守卫只认 `subprocess.*` 字面调用,包装器调用它看不见。
+
+ `VersionManager._git` 走的是注入的 `self._execute`,AST 里没有
+ `subprocess` 字样,所以这条守卫抓不到它——而它恰恰是暴露最大的一处:
+ 读 git 输出,本仓库的提交信息是中文的。盲点用一条显式断言补上。
+ """
+ source = (ROOT / "src" / "peach" / "versioning.py").read_text(encoding="utf-8")
+ self.assertIn('encoding="utf-8"', source)
+ self.assertIn('errors="replace"', source)
+
+ def test_the_guard_accepts_a_locked_encoding(self):
+ tree = ast.parse("import subprocess\n"
+ "subprocess.run(['git'], text=True, encoding='utf-8')\n")
+ _, keywords = next(iter(_subprocess_calls(tree)))
+ self.assertEqual(keywords.get("encoding"), "'utf-8'")
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/test_versioning.py b/tests/test_versioning.py
index c70cb7b8b..47406555c 100644
--- a/tests/test_versioning.py
+++ b/tests/test_versioning.py
@@ -11,7 +11,7 @@ from peach.versioning import VersionManager
def git(path: Path, *args: str) -> subprocess.CompletedProcess[str]:
return subprocess.run(
["git", "-c", f"safe.directory={path.as_posix()}", "-C", str(path), *args],
- capture_output=True, text=True, check=True,
+ capture_output=True, text=True, encoding="utf-8", errors="replace", check=True,
)