1
0
Fork 0
mirror of https://github.com/yavook/kiwi-scp.git synced 2025-12-08 01:23:01 +00:00
kiwi-scp/src/kiwi/subcommands/_utils.py

104 lines
2.7 KiB
Python
Raw Normal View History

2020-08-10 15:40:56 +00:00
import logging
2020-08-10 12:50:47 +00:00
import os
import subprocess
2020-08-11 12:03:00 +00:00
from ..parser import Parser
from ..config import LoadedConfig
2020-08-10 12:50:47 +00:00
def is_executable(filename):
if filename is None:
return False
return os.path.isfile(filename) and os.access(filename, os.X_OK)
def find_exe_file(exe_name):
for path in os.environ['PATH'].split(os.pathsep):
exe_file = os.path.join(path, exe_name)
if is_executable(exe_file):
return exe_file
return None
def get_exe_key(exe_name):
return f'executables:{exe_name}'
class SubCommand:
__name = None
2020-08-11 12:03:00 +00:00
_sub_parser = None
def __init__(self, name, **kwargs):
self.__name = name
2020-08-11 12:03:00 +00:00
self._sub_parser = Parser().get_subparsers().add_parser(name, **kwargs)
def __str__(self):
return self.__name
2020-08-11 12:03:00 +00:00
def run(self, config, args):
pass
2020-08-10 15:40:56 +00:00
class DockerCommand:
class __DockerCommand:
__cmd = []
def __init__(self, exe_name):
config = LoadedConfig.get()
self.__cmd = [config[get_exe_key(exe_name)]]
2020-08-10 15:40:56 +00:00
if DockerCommand.__requires_root:
self.__cmd = [config[get_exe_key("sudo")], *self.__cmd]
2020-08-11 10:08:03 +00:00
def __build_cmd(self, args, **kwargs):
cmd = [*self.__cmd, *args]
2020-08-11 10:08:03 +00:00
logging.debug(f"DockerProgram cmd{cmd}, kwargs{kwargs}")
2020-08-10 15:40:56 +00:00
return cmd
def run(self, args, **kwargs):
return subprocess.run(
2020-08-11 10:08:03 +00:00
self.__build_cmd(args, **kwargs),
2020-08-10 15:40:56 +00:00
**kwargs
)
def run_less(self, args, **kwargs):
process = subprocess.Popen(
2020-08-11 10:08:03 +00:00
self.__build_cmd(args, **kwargs),
2020-08-10 15:40:56 +00:00
stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
**kwargs
)
less_process = subprocess.run(
['less', '-R', '+G'],
stdin=process.stdout
)
process.communicate()
return less_process
__exe_name = None
__instances = {}
__requires_root = None
def __init__(self, exe_name):
2020-08-10 15:40:56 +00:00
if DockerCommand.__requires_root is None:
try:
config = LoadedConfig.get()
subprocess.run(
2020-08-10 12:50:47 +00:00
[config[get_exe_key('docker')], 'ps'],
check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL
)
2020-08-10 15:40:56 +00:00
DockerCommand.__requires_root = False
except subprocess.CalledProcessError:
2020-08-10 15:40:56 +00:00
DockerCommand.__requires_root = True
self.__exe_name = exe_name
2020-08-10 15:40:56 +00:00
if exe_name not in DockerCommand.__instances:
DockerCommand.__instances[exe_name] = DockerCommand.__DockerCommand(exe_name)
def __getattr__(self, item):
return getattr(self.__instances[self.__exe_name], item)