from __future__ import annotations import subprocess from dataclasses import dataclass from pathlib import Path from typing import Sequence @dataclass class CommandResult: command: list[str] returncode: int stdout: str stderr: str class SubprocessError(RuntimeError): """Raised on failed subprocess execution when strict mode is enabled.""" def run_command( command: Sequence[str], cwd: Path | None = None, timeout: int | None = None, strict: bool = False, ) -> CommandResult: """Run command via subprocess with robust, non-throwing default behavior.""" proc = subprocess.run( list(command), cwd=str(cwd) if cwd else None, timeout=timeout, check=False, capture_output=True, text=True, ) result = CommandResult(command=list(command), returncode=proc.returncode, stdout=proc.stdout, stderr=proc.stderr) if strict and result.returncode != 0: raise SubprocessError( f"Command failed ({result.returncode}): {' '.join(result.command)}\n{result.stderr.strip()}" ) return result