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

30 lines
1.2 KiB
Python

"""Start a mutation tool, through --prefix's shell text where the run gives one, and wait for it."""
import dataclasses
import shlex
import subprocess
from failure import Failure
@dataclasses.dataclass(frozen=True)
class Ran:
code: int
output: str # stdout and stderr, as the tool interleaved them
def run_tool(argv: list[str], cwd: str, prefix: str | None) -> Ran | Failure:
"""Run a tool in cwd, 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:
ran = subprocess.run(command, cwd=cwd, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, encoding="utf-8", errors="replace")
except OSError as failure:
return Failure(f"{shlex.join(argv)} could not start: {failure.strerror}")
return Ran(ran.returncode, ran.stdout)
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:]]))