cliutil: New function can_run.

This commit is contained in:
Brett Smith 2021-01-05 16:46:42 -05:00
parent 0045d8d032
commit 902c313b4d
2 changed files with 30 additions and 0 deletions

View file

@ -20,6 +20,7 @@ import os
import pkg_resources import pkg_resources
import re import re
import signal import signal
import subprocess
import sys import sys
import traceback import traceback
import types import types
@ -37,6 +38,7 @@ from typing import (
Any, Any,
BinaryIO, BinaryIO,
Callable, Callable,
Container,
IO, IO,
Iterable, Iterable,
NamedTuple, NamedTuple,
@ -279,6 +281,22 @@ def add_version_argument(parser: argparse.ArgumentParser) -> argparse.Action:
help="Show program version and license information", help="Show program version and license information",
) )
def can_run(
cmd: Sequence[str],
stdout: Optional[int]=subprocess.DEVNULL,
stderr: Optional[int]=None,
ok_returncodes: Container[int]=frozenset([0]),
) -> bool:
try:
with subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=stdout, stderr=stderr) as proc:
# Typing says this can be None, but I don't think that's true
# given that we passed stdin=PIPE.
proc.stdin.close() # type:ignore[union-attr]
except (OSError, subprocess.SubprocessError):
return False
else:
return proc.returncode in ok_returncodes
def date_arg(arg: str) -> datetime.date: def date_arg(arg: str) -> datetime.date:
return datetime.datetime.strptime(arg, '%Y-%m-%d').date() return datetime.datetime.strptime(arg, '%Y-%m-%d').date()

View file

@ -20,6 +20,8 @@ import pytest
from pathlib import Path from pathlib import Path
from . import testutil
from conservancy_beancount import cliutil from conservancy_beancount import cliutil
FILE_NAMES = ['-foobar', '-foo.bin'] FILE_NAMES = ['-foobar', '-foo.bin']
@ -227,3 +229,13 @@ def test_version_argument(argparser, capsys, arg):
]) ])
def test_diff_year(date, diff, expected): def test_diff_year(date, diff, expected):
assert cliutil.diff_year(date, diff) == expected assert cliutil.diff_year(date, diff) == expected
@pytest.mark.parametrize('cmd,expected', [
(['true'], True),
(['true', '--version'], True),
(['false'], False),
(['false', '--version'], False),
([str(testutil.TESTS_DIR)], False),
])
def test_can_run(cmd, expected):
assert cliutil.can_run(cmd) == expected