nix-update/nix_update/utils.py

39 lines
1.0 KiB
Python
Raw Normal View History

2020-03-16 13:06:32 +03:00
import os
import subprocess
import sys
from pathlib import Path
from typing import IO, Any, Callable, List, Optional, Union, Dict
2020-03-16 13:06:32 +03:00
HAS_TTY = sys.stdout.isatty()
ROOT = Path(os.path.dirname(os.path.realpath(__file__)))
def color_text(code: int, file: IO[Any] = sys.stdout) -> Callable[[str], None]:
def wrapper(text: str) -> None:
if HAS_TTY:
print(f"\x1b[{code}m{text}\x1b[0m", file=file)
else:
print(text, file=file)
return wrapper
warn = color_text(31, file=sys.stderr)
info = color_text(32)
def run(
command: List[str],
cwd: Optional[Union[Path, str]] = None,
stdout: Union[None, int, IO[Any]] = subprocess.PIPE,
2022-11-10 18:56:26 +03:00
stderr: Union[None, int, IO[Any]] = subprocess.PIPE,
2020-03-24 16:25:17 +03:00
check: bool = True,
extra_env: Dict[str, str] = {},
2020-05-05 13:15:29 +03:00
) -> "subprocess.CompletedProcess[str]":
2020-03-16 13:06:32 +03:00
info("$ " + " ".join(command))
env = os.environ.copy()
env.update(extra_env)
return subprocess.run(
2022-11-10 18:56:26 +03:00
command, cwd=cwd, check=check, text=True, stdout=stdout, stderr=stderr, env=env
)