Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

49 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, Pathish, 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. command = list(flatten_cmd(cmd))
  31. return subprocess.run(command, cwd=cwd, check=check)
  32. def check_run(*cmd: CommandLine, cwd: Optional[Pathish] = None) -> ProcessResult:
  33. command = list(flatten_cmd(cmd))
  34. return subprocess.run(command, cwd=cwd, check=True)