kiwi-scp/src/kiwi/runner.py

74 lines
2 KiB
Python
Raw Normal View History

2020-08-12 15:46:50 +00:00
# system
2020-08-11 12:03:00 +00:00
import logging
2020-08-19 15:09:43 +00:00
import subprocess
2020-08-11 12:03:00 +00:00
2020-08-12 15:46:50 +00:00
# local
from . import subcommands
2020-08-19 15:09:43 +00:00
from .subcommands.utils.executable import Executable
2020-08-11 12:03:00 +00:00
from .parser import Parser
class Runner:
2020-08-13 08:48:01 +00:00
"""Singleton: Subcommands setup and run"""
class __Runner:
2020-08-13 08:48:01 +00:00
"""Singleton type"""
__commands = []
def __init__(self):
2020-08-19 15:09:43 +00:00
# probe for Docker access
try:
Executable('docker').run(
['ps'],
check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL
)
except subprocess.CalledProcessError:
raise PermissionError("Cannot access docker, please get into the docker group or run as root!")
2020-08-13 08:48:01 +00:00
# setup all subcommands
for className in subcommands.__all__:
cmd = getattr(subcommands, className)
self.__commands.append(cmd())
def run(self, command=None, args=None):
2020-08-13 08:48:01 +00:00
"""run the desired subcommand"""
if args is None:
args = Parser().get_args()
2020-08-11 12:03:00 +00:00
2020-08-17 08:55:08 +00:00
if command is None:
command = args.command
for cmd in self.__commands:
2020-08-17 08:55:08 +00:00
if str(cmd) == command:
2020-08-13 08:48:01 +00:00
# command found
2020-08-11 12:03:00 +00:00
logging.debug(f"Running '{cmd}' with args: {args}")
2020-08-13 12:26:49 +00:00
try:
result = cmd.run(self, args)
2020-08-13 12:26:49 +00:00
except KeyboardInterrupt:
print()
logging.warning(f"'{cmd}' aborted, inputs may have been discarded.")
2020-08-17 13:00:05 +00:00
result = False
2020-08-13 12:26:49 +00:00
2020-08-17 13:00:05 +00:00
return result
2020-08-13 08:48:01 +00:00
# command not found
2020-08-17 08:55:08 +00:00
logging.error(f"kiwi command '{command}' unknown")
return False
__instance = None
def __init__(self):
if Runner.__instance is None:
2020-08-13 08:48:01 +00:00
# create singleton
Runner.__instance = Runner.__Runner()
def __getattr__(self, item):
2020-08-13 08:48:01 +00:00
"""Inner singleton direct access"""
return getattr(self.__instance, item)