fix: make the repository pre-commit checks portable on Windows

Use the hook environment’s Python interpreter and select the supported process, terminal, and locking APIs at their platform boundaries. Keep all existing hook checks enabled and fix the tracked SVG EOF that fails a clean all-files run.
This commit is contained in:
LIziak112
2026-11-25 20:35:27 +08:00
parent 14796c70f6
commit 257c5e62dc
11 changed files with 29 additions and 17 deletions

View File

@@ -14,8 +14,8 @@ repos:
hooks:
- id: deeptutor-repo-hygiene
name: DeepTutor repository hygiene
entry: python3 scripts/check_repo_hygiene.py
language: system
entry: python scripts/check_repo_hygiene.py
language: python
pass_filenames: false
always_run: true

View File

@@ -17,4 +17,4 @@
<path d="M588.38,397.61c7.96,0,14.03,5.81,14.03,13.71c0,7.9-6.07,13.71-14.03,13.71s-14.03-5.81-14.03-13.71 C574.36,403.42,580.43,397.61,588.38,397.61z M588.38,402.95c-4.82,0-8.27,3.66-8.27,8.37c0,4.71,3.45,8.37,8.27,8.37 s8.27-3.66,8.27-8.37C596.65,406.62,593.2,402.95,588.38,402.95z" />
<path d="M638.44,398.24h5.64l-7.14,26.17h-7.64l-5.02-19.47l-5.36,19.47h-7.64l-6.86-26.17h5.75l5.13,20.89l5.69-20.89h6.58 l5.47,20.89L638.44,398.24z" />
</g>
</svg>
</svg>

Before

Width:  |  Height:  |  Size: 2.7 KiB

After

Width:  |  Height:  |  Size: 2.7 KiB

View File

@@ -151,7 +151,7 @@ def _reset_runtime_singletons() -> None:
def _get_pgid(pid: int | None) -> int | None:
if pid is None or os.name == "nt":
if pid is None or not hasattr(os, "getpgid"):
return None
try:
return os.getpgid(pid)
@@ -241,7 +241,7 @@ def _send_tree_signal(pid: int | None, pgid: int | None, sig: signal.Signals | i
if completed.returncode not in (0, 128):
raise RuntimeError(f"taskkill {pid} failed with exit code {completed.returncode}")
return
if os.name != "nt" and pgid is not None:
if pgid is not None and hasattr(os, "killpg"):
os.killpg(pgid, sig)
else:
os.kill(pid, sig)
@@ -277,7 +277,7 @@ def _signal_target(
def _group_alive(proc: ManagedProcess) -> bool:
"""A group can outlive its leader (npm and worker launchers do this)."""
if os.name == "nt" or proc.pgid is None:
if proc.pgid is None or not hasattr(os, "killpg"):
return False
try:
os.killpg(proc.pgid, 0)
@@ -335,7 +335,7 @@ def _terminate_all(
logger.warning("Could not inspect %s", proc.name, exc_info=True)
if running or _group_alive(proc):
active.append(proc)
if not running and os.name != "nt":
if not running and hasattr(os, "getpgid"):
# Recover same-group children even when the launcher has
# already reaped npm or another short-lived parent.
for child in psutil.process_iter():

View File

@@ -223,6 +223,8 @@ def _proc_entry(pid: int) -> tuple[int, str, str] | None:
def _proc_rss(pid: int) -> int | None:
if not hasattr(os, "sysconf"):
return None
try:
fields = Path(f"/proc/{pid}/statm").read_text(encoding="utf-8").split()
except OSError:

View File

@@ -5,6 +5,7 @@ from __future__ import annotations
import os
import signal
import subprocess
import sys
import time
from typing import Literal
@@ -15,7 +16,7 @@ def kill_process_tree(pid: int) -> None:
Callers still reap their process/streams before releasing runtime leases.
Windows Process.kill() alone leaves build and renderer children running.
"""
if os.name != "nt":
if sys.platform != "win32":
for attempt in range(5):
try:
os.killpg(pid, signal.SIGKILL)

View File

@@ -132,7 +132,7 @@ def _render_sync(data: bytes, suffix: str, cache_dir: Path, key: str, soffice: s
# `soffice` may launch soffice.bin; kill the whole process group,
# rather than leaving a converter running after the request ends.
try:
if os.name == "posix" and hasattr(os, "killpg"):
if hasattr(os, "killpg") and hasattr(signal, "SIGKILL"):
os.killpg(process.pid, signal.SIGKILL)
else:
process.kill()

View File

@@ -59,7 +59,7 @@ def cli_process(cmd: list[str], log_path: Path, env: dict[str, str]):
# Attach before execution: no child can escape an assignment race.
kwargs["creationflags"] = win32con.CREATE_SUSPENDED | subprocess.CREATE_NO_WINDOW
process = subprocess.Popen(cmd, **kwargs) # nosec B603: fixed argv, shell=False
win32job.AssignProcessToJobObject(job, int(process._handle))
win32job.AssignProcessToJobObject(job, int(process._handle)) # type: ignore[attr-defined] # CPython Windows process handle
assigned = True
threads = psutil.Process(process.pid).threads()
if len(threads) != 1:
@@ -89,7 +89,7 @@ def cli_process(cmd: list[str], log_path: Path, env: dict[str, str]):
time.sleep(0.05)
finally:
job.Close()
elif process is not None:
elif sys.platform != "win32" and process is not None:
for sig in (signal.SIGTERM, signal.SIGKILL):
try:
os.killpg(process.pid, sig)
@@ -111,6 +111,8 @@ def cli_process(cmd: list[str], log_path: Path, env: dict[str, str]):
def _process_group_exists(pgid: int) -> bool:
"""Only ESRCH confirms absence; EPERM may hide members or just zombies."""
if sys.platform == "win32":
raise NotImplementedError("POSIX process groups are unavailable on Windows")
try:
os.killpg(pgid, 0)
except ProcessLookupError:
@@ -125,7 +127,7 @@ def _process_group_alive(pgid: int) -> bool:
if not _process_group_exists(pgid):
return False
if sys.platform != "darwin":
if sys.platform != "darwin" and hasattr(os, "getpgid"):
import psutil
saw_member = False

View File

@@ -4,6 +4,7 @@ from collections.abc import Iterator
from contextlib import contextmanager
import errno
from pathlib import Path
import sys
try: # POSIX
import fcntl
@@ -18,7 +19,7 @@ except ImportError: # pragma: no cover - exercised only off Windows
@contextmanager
def exclusive_lock(lock_path: Path) -> Iterator[None]:
with lock_path.open("a+b") as lock_file:
if fcntl is not None:
if sys.platform != "win32" and fcntl is not None:
fcntl.flock(lock_file.fileno(), fcntl.LOCK_EX)
elif msvcrt is not None:
# Without a lock, workers starting together race the WAL switch
@@ -41,7 +42,7 @@ def exclusive_lock(lock_path: Path) -> Iterator[None]:
try:
yield
finally:
if fcntl is not None:
if sys.platform != "win32" and fcntl is not None:
fcntl.flock(lock_file.fileno(), fcntl.LOCK_UN)
elif msvcrt is not None:
lock_file.seek(0)

View File

@@ -19,6 +19,7 @@ import re
import select
import shutil
import signal
import sys
import tempfile
import time
@@ -159,7 +160,7 @@ def _capture_model_screen() -> str | None:
on screen, or ``None`` if we couldn't get there. POSIX-only; gracefully
returns ``None`` when ``pyte`` is unavailable or the platform has no pty.
"""
if os.name != "posix":
if sys.platform == "win32" or os.name != "posix":
return None
try:
import pty

View File

@@ -38,6 +38,10 @@ _LLM_ROUND_CALL_KINDS = frozenset({"agent_loop_round", "llm_final_response"})
def _utf8_aware_terminal_input(stream: TextIO) -> Iterator[None]:
"""Make canonical-mode erase treat UTF-8 input as complete characters."""
if sys.platform == "win32":
yield
return
try:
import termios
except ImportError:

View File

@@ -20,7 +20,8 @@ def test_cleanup_rechecks_group_after_permission_race(monkeypatch, group_exists)
raise PermissionError("group changed during signal")
raise ProcessLookupError("group already reaped")
monkeypatch.setattr(process, "os", SimpleNamespace(name="posix", killpg=killpg))
monkeypatch.setattr(process, "sys", SimpleNamespace(platform="linux"))
monkeypatch.setattr(process, "os", SimpleNamespace(killpg=killpg))
# The POSIX branch is simulated on every OS; Windows has no SIGKILL.
monkeypatch.setattr(process.signal, "SIGKILL", 9, raising=False)
monkeypatch.setattr(process.time, "sleep", lambda _: None)
@@ -38,7 +39,7 @@ def test_windows_cleanup_targets_the_entire_owned_tree(monkeypatch, returncode):
from deeptutor.runtime import process
calls = []
monkeypatch.setattr(process, "os", SimpleNamespace(name="nt"))
monkeypatch.setattr(process, "sys", SimpleNamespace(platform="win32"))
def run(argv, **kwargs):
calls.append((argv, kwargs))