149 lines
4.8 KiB
Python
149 lines
4.8 KiB
Python
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:
|
|
import datetime
|
|
timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
|
with open(str(self.log_file), "a", encoding="utf-8") as f:
|
|
f.write(f"[{timestamp}] {text}\n")
|
|
except Exception:
|
|
pass
|
|
|
|
def run(
|
|
self,
|
|
cmd: List[str],
|
|
check: bool = False,
|
|
env: Optional[Dict[str, str]] = None,
|
|
timeout: Optional[int] = None,
|
|
stream: bool = False,
|
|
) -> CommandResult:
|
|
full_env = os.environ.copy()
|
|
if env:
|
|
full_env.update(env)
|
|
|
|
self._log(f"Executing: {' '.join(cmd)}")
|
|
|
|
try:
|
|
if stream and not os.environ.get("LINUX_UPDATER_NO_STREAM"):
|
|
import selectors
|
|
proc = subprocess.Popen(
|
|
cmd,
|
|
stdout=subprocess.PIPE,
|
|
stderr=subprocess.PIPE,
|
|
env=full_env,
|
|
)
|
|
stdout_acc: List[str] = []
|
|
stderr_acc: List[str] = []
|
|
|
|
sel = selectors.DefaultSelector()
|
|
sel.register(proc.stdout, selectors.EVENT_READ, data=(sys.stdout, stdout_acc))
|
|
sel.register(proc.stderr, selectors.EVENT_READ, data=(sys.stderr, stderr_acc))
|
|
|
|
while sel.get_map():
|
|
events = sel.select(timeout=0.2)
|
|
for key, _ in events:
|
|
raw = os.read(key.fileobj.fileno(), 1024)
|
|
if not raw:
|
|
sel.unregister(key.fileobj)
|
|
continue
|
|
text = raw.decode("utf-8", errors="replace")
|
|
key.data[0].write(text)
|
|
key.data[0].flush()
|
|
key.data[1].append(text)
|
|
|
|
proc.wait(timeout=timeout)
|
|
stdout = "".join(stdout_acc)
|
|
stderr = "".join(stderr_acc)
|
|
success = (proc.returncode == 0)
|
|
else:
|
|
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,
|
|
)
|