|
| 1 | +import os |
| 2 | +import platform |
| 3 | +import subprocess |
| 4 | +from dataclasses import dataclass |
| 5 | +from pathlib import Path |
| 6 | +from typing import Dict, Optional, Sequence, Self |
| 7 | +from .result import RunResult |
| 8 | + |
| 9 | + |
| 10 | +@dataclass |
| 11 | +class BinaryRunner: |
| 12 | + """Cross-platform runner for the gitmastery binary.""" |
| 13 | + |
| 14 | + binary_path: str |
| 15 | + project_root: Path |
| 16 | + |
| 17 | + @classmethod |
| 18 | + def from_env( |
| 19 | + cls, |
| 20 | + env_var: str = "GITMASTERY_BINARY", |
| 21 | + project_root: Optional[Path] = None, |
| 22 | + ) -> Self: |
| 23 | + """Build a runner from an environment variable.""" |
| 24 | + if project_root is None: |
| 25 | + project_root = Path(__file__).resolve().parents[2] |
| 26 | + |
| 27 | + raw = os.environ.get(env_var, "").strip() |
| 28 | + if raw: |
| 29 | + binary_path = raw |
| 30 | + else: |
| 31 | + system = platform.system().lower() |
| 32 | + if system == "windows": |
| 33 | + binary_path = str(project_root / "dist" / "gitmastery.exe") |
| 34 | + else: |
| 35 | + binary_path = str(project_root / "dist" / "gitmastery") |
| 36 | + |
| 37 | + return cls(binary_path=binary_path, project_root=project_root) |
| 38 | + |
| 39 | + def run( |
| 40 | + self, |
| 41 | + args: Sequence[str] = (), |
| 42 | + *, |
| 43 | + cwd: Optional[Path] = None, |
| 44 | + env: Optional[Dict[str, str]] = None, |
| 45 | + timeout: int = 30, |
| 46 | + stdin_text: Optional[str] = None, |
| 47 | + ) -> RunResult: |
| 48 | + """Execute the binary with args and return a RunResult.""" |
| 49 | + cmd = [self.binary_path] + list(args) |
| 50 | + run_env = os.environ.copy() |
| 51 | + if env: |
| 52 | + run_env.update(env) |
| 53 | + |
| 54 | + run_env.setdefault("NO_COLOR", "1") |
| 55 | + run_env.setdefault("PYTHONIOENCODING", "utf-8") |
| 56 | + |
| 57 | + proc = subprocess.run( |
| 58 | + cmd, |
| 59 | + cwd=str(cwd) if cwd else str(self.project_root), |
| 60 | + env=run_env, |
| 61 | + capture_output=True, |
| 62 | + text=True, |
| 63 | + timeout=timeout if timeout > 0 else None, |
| 64 | + input=stdin_text, |
| 65 | + ) |
| 66 | + return RunResult( |
| 67 | + stdout=proc.stdout, |
| 68 | + stderr=proc.stderr, |
| 69 | + returncode=proc.returncode, |
| 70 | + command=cmd, |
| 71 | + ) |
0 commit comments