File size: 1,114 Bytes
504d922
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
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