import os import subprocess import sys from pathlib import Path from typing import Dict, List, Optional from linux_updater.models import CommandResult class CommandRunner: def __init__(self, verbose: bool = False, log_file: Optional[Path] = None) -> None: self.verbose = verbose self.log_file = log_file def _log(self, text: str) -> None: if self.verbose: print(f"[RUNNER] {text}", file=sys.stderr) if self.log_file: try: with open(str(self.log_file), "a", encoding="utf-8") as f: f.write(f"{text}\n") except Exception: pass def run( self, cmd: List[str], check: bool = False, env: Optional[Dict[str, str]] = None, timeout: Optional[int] = None, ) -> CommandResult: full_env = os.environ.copy() if env: full_env.update(env) self._log(f"Executing: {' '.join(cmd)}") try: proc = subprocess.run( cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=full_env, timeout=timeout, ) stdout = proc.stdout.decode("utf-8", errors="replace") stderr = proc.stderr.decode("utf-8", errors="replace") success = (proc.returncode == 0) self._log(f"Exit code: {proc.returncode}") if check and not success: raise subprocess.CalledProcessError(proc.returncode, cmd, output=stdout, stderr=stderr) return CommandResult( return_code=proc.returncode, stdout=stdout, stderr=stderr, success=success, ) except Exception as e: self._log(f"Command execution error: {e}") if check: raise return CommandResult( return_code=1, stdout="", stderr=str(e), success=False, ) def stream_run( self, cmd: List[str], env: Optional[Dict[str, str]] = None, ) -> CommandResult: full_env = os.environ.copy() if env: full_env.update(env) self._log(f"Stream executing: {' '.join(cmd)}") stdout_lines: List[str] = [] try: proc = subprocess.Popen( cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, env=full_env, universal_newlines=True, ) # Stream output in real time if proc.stdout: for line in proc.stdout: sys.stdout.write(line) sys.stdout.flush() stdout_lines.append(line) proc.wait() return CommandResult( return_code=proc.returncode, stdout="".join(stdout_lines), stderr="", success=(proc.returncode == 0), ) except Exception as e: return CommandResult( return_code=1, stdout="".join(stdout_lines), stderr=str(e), success=False, )