Files
claude-config/bin/mutate_changes/tool_process.py
T

80 lines
3.3 KiB
Python

"""Start a mutation tool, through --prefix's shell text where the run gives one, and wait for it; and make and remove its scratch folder."""
import contextlib
import dataclasses
import pathlib
import shlex
import shutil
import signal
import subprocess
import sys
import tempfile
import typing
from failure import Failure
GRACE_SECONDS = 10 # how long an interrupted tool has to stop on the SIGINT it is passed, before it is killed
@dataclasses.dataclass(frozen=True)
class Ran:
code: int
output: str # stdout and stderr, as the tool interleaved them
class Run(typing.Protocol):
"""Runs a tool in cwd as `run_tool` does, with the run's prefix, environment and killpg bound."""
def __call__(self, argv: list[str], cwd: str) -> Ran | Failure: ...
# The tests hand in a shorter grace, and a killpg that finds the tool's processes gone.
def run_tool(argv: list[str], cwd: str, *, prefix: str | None, env: typing.Mapping[str, str], killpg: typing.Callable[[int, int], None], grace: float = GRACE_SECONDS) -> Ran | Failure:
"""Run a tool in cwd with the environment env, reading each byte of its output that is not UTF-8 as U+FFFD.
With a prefix, sh runs `<prefix> "$@"` with argv as its arguments, so the prefix keeps its own quoting and each of argv stays one word."""
command = ["sh", "-c", f'{prefix} "$@"', "sh", *argv] if prefix else argv
try:
# In a session of its own, the tool and each process it starts share one process group, which ends whole below.
process = subprocess.Popen(command, cwd=cwd, env=env, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, encoding="utf-8", errors="replace", start_new_session=True)
except OSError as failure:
return Failure(f"{shlex.join(argv)} could not start: {failure.strerror}")
try:
output = process.communicate()[0]
except BaseException:
# The run is ending, as on Ctrl-C or the SIGTERM the launcher turns into SystemExit, so end what the tool started too. Ctrl-C
# reaches only this process, so pass the tool SIGINT first: a container's CLI, such as docker compose, then stops its container.
try:
with contextlib.suppress(ProcessLookupError):
killpg(process.pid, signal.SIGINT)
with contextlib.suppress(subprocess.TimeoutExpired):
process.wait(timeout=grace)
finally:
with contextlib.suppress(ProcessLookupError):
killpg(process.pid, signal.SIGKILL)
process.wait()
raise
return Ran(process.returncode, output)
def failed(name: str, ran: Ran) -> Failure:
"""A tool's exit code and the last 40 lines of its output, which hold its error."""
return Failure("\n".join([f"{name} exited {ran.code}:", *ran.output.splitlines()[-40:]]))
def scratch_folder(top: str) -> str | Failure:
"""A new folder in top for one tool's files. It holds a .gitignore of `*`, as pytest's cache folder does, so git lists none of them."""
try:
scratch = tempfile.mkdtemp(prefix=".mutate-changes-", dir=top)
pathlib.Path(scratch, ".gitignore").write_text("*\n", encoding="utf-8")
except OSError as failure:
return Failure(f"could not make a scratch folder in {top}: {failure}")
return scratch
def remove(scratch: str) -> None:
"""Remove a scratch folder, saying on stderr where it can't: the run's report holds, so the run doesn't fail."""
try:
shutil.rmtree(scratch)
except OSError as failure:
print(f"could not remove {scratch}: {failure}", file=sys.stderr)