Files
pkgmgr/pkgmgr/run_command.py
Kevin Veen-Birkenbach f57ab0c2d1 Refactor pkgmgr self-install handling, add pip-enabled Python env to flake, and fix Nix/pip integration
- Rename requirements.txt to _requirements.txt to avoid unintended self-install via PythonInstaller.
- Update flake.nix to provide Python with pip in both devShell and runtime closure.
- Generate a wrapper for pkgmgr that uses the pip-enabled interpreter.
- Adjust NixFlakeInstaller to correctly handle old profile removal and install outputs.
- Update run_command to support string commands and allow_failure.
- Improve integration test by adding nix profile cleanup and debugging output.

Reference: https://chatgpt.com/share/69345df2-a960-800f-8395-92a7c3a6629f
2025-12-06 17:47:46 +01:00

46 lines
1.2 KiB
Python

# pkgmgr/run_command.py
import subprocess
import sys
from typing import List, Optional, Union
CommandType = Union[str, List[str]]
def run_command(
cmd: CommandType,
cwd: Optional[str] = None,
preview: bool = False,
allow_failure: bool = False,
) -> subprocess.CompletedProcess:
"""
Run a command and optionally exit on error.
- If `cmd` is a string, it is executed with `shell=True`.
- If `cmd` is a list of strings, it is executed without a shell.
"""
if isinstance(cmd, str):
display = cmd
else:
display = " ".join(cmd)
where = cwd or "."
if preview:
print(f"[Preview] In '{where}': {display}")
# Fake a successful result; most callers ignore the return value anyway
return subprocess.CompletedProcess(cmd, 0) # type: ignore[arg-type]
print(f"Running in '{where}': {display}")
if isinstance(cmd, str):
result = subprocess.run(cmd, cwd=cwd, shell=True)
else:
result = subprocess.run(cmd, cwd=cwd)
if result.returncode != 0 and not allow_failure:
print(f"Command failed with exit code {result.returncode}. Exiting.")
sys.exit(result.returncode)
return result