86 lines
2.0 KiB
Python
86 lines
2.0 KiB
Python
from __future__ import annotations
|
|
|
|
import os
|
|
import shlex
|
|
import shutil
|
|
import subprocess
|
|
from dataclasses import dataclass
|
|
from pathlib import Path
|
|
from typing import Mapping, Sequence
|
|
|
|
|
|
class CommandNotFoundError(RuntimeError):
|
|
pass
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class CommandResult:
|
|
command: tuple[str, ...]
|
|
returncode: int
|
|
stdout: str
|
|
stderr: str
|
|
|
|
|
|
def command_exists(command: str) -> bool:
|
|
if "/" in command:
|
|
path = Path(command).expanduser()
|
|
return path.exists() and os.access(path, os.X_OK)
|
|
return shutil.which(command) is not None
|
|
|
|
|
|
def quote_command(command: Sequence[str]) -> str:
|
|
return " ".join(shlex.quote(str(part)) for part in command)
|
|
|
|
|
|
def require_command(command: str) -> None:
|
|
if not command_exists(command):
|
|
raise CommandNotFoundError(f"Required command not found: {command}")
|
|
|
|
|
|
def _effective_env(env: Mapping[str, str] | None) -> dict[str, str] | None:
|
|
if env is None:
|
|
return None
|
|
effective = dict(os.environ)
|
|
effective.update({str(key): str(value) for key, value in env.items()})
|
|
return effective
|
|
|
|
|
|
def run_command(
|
|
command: Sequence[str],
|
|
*,
|
|
cwd: Path | None = None,
|
|
env: Mapping[str, str] | None = None,
|
|
capture: bool = False,
|
|
check: bool = True,
|
|
) -> CommandResult:
|
|
if not command:
|
|
raise ValueError("Command cannot be empty")
|
|
|
|
require_command(str(command[0]))
|
|
|
|
completed = subprocess.run(
|
|
[str(part) for part in command],
|
|
cwd=str(cwd) if cwd else None,
|
|
env=_effective_env(env),
|
|
check=False,
|
|
text=True,
|
|
capture_output=capture,
|
|
)
|
|
|
|
result = CommandResult(
|
|
command=tuple(str(part) for part in command),
|
|
returncode=completed.returncode,
|
|
stdout=completed.stdout or "",
|
|
stderr=completed.stderr or "",
|
|
)
|
|
|
|
if check and completed.returncode != 0:
|
|
raise subprocess.CalledProcessError(
|
|
completed.returncode,
|
|
list(result.command),
|
|
output=result.stdout,
|
|
stderr=result.stderr,
|
|
)
|
|
|
|
return result
|