Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

55 lines
1.5KB

  1. from pathlib import PurePath
  2. from typing import Iterable, Union, Optional, Iterator
  3. from typing_extensions import Protocol
  4. import subprocess
  5. from .util import Pathish
  6. CommandLineArg = Union[str, PurePath, int, float]
  7. CommandLineArg1 = Union[CommandLineArg, Iterable[CommandLineArg]]
  8. CommandLineArg2 = Union[CommandLineArg1, Iterable[CommandLineArg1]]
  9. CommandLineArg3 = Union[CommandLineArg2, Iterable[CommandLineArg2]]
  10. CommandLineArg4 = Union[CommandLineArg3, Iterable[CommandLineArg3]]
  11. class CommandLine(Protocol):
  12. def __iter__(self) -> Iterator[Union['CommandLine', CommandLineArg]]:
  13. pass
  14. # CommandLine = Union[CommandLineArg4, Iterable[CommandLineArg4]]
  15. class ProcessResult(Protocol):
  16. returncode: int
  17. stdout: bytes
  18. def flatten_cmd(cmd: CommandLine) -> Iterable[str]:
  19. if isinstance(cmd, (str, PurePath)):
  20. yield str(cmd)
  21. elif isinstance(cmd, (int, float)):
  22. yield str(cmd)
  23. elif hasattr(cmd, '__iter__'):
  24. each = (flatten_cmd(arg) for arg in cmd) # type: ignore
  25. for item in each:
  26. yield from item
  27. else:
  28. assert False, f'Invalid command line element: {repr(cmd)}'
  29. def run(*cmd: CommandLine, cwd: Optional[Pathish] = None, check: bool = False) -> ProcessResult:
  30. return subprocess.run(
  31. list(flatten_cmd(cmd)),
  32. cwd=cwd,
  33. check=check,
  34. )
  35. def check_run(*cmd: CommandLine, cwd: Optional[Pathish] = None) -> ProcessResult:
  36. return subprocess.run(
  37. list(flatten_cmd(cmd)),
  38. cwd=cwd,
  39. check=True,
  40. )