2020-08-13 11:00:32 +00:00
|
|
|
# system
|
|
|
|
import logging
|
|
|
|
import subprocess
|
|
|
|
|
|
|
|
# local
|
|
|
|
from ._subcommand import ServiceCommand
|
|
|
|
from .utils.dockercommand import DockerCommand
|
|
|
|
|
|
|
|
|
2020-08-13 12:26:49 +00:00
|
|
|
def _service_has_shell(config, args, compose_cmd, shell):
|
2020-08-13 11:00:32 +00:00
|
|
|
try:
|
|
|
|
# test if desired shell exists
|
|
|
|
DockerCommand('docker-compose').run(
|
2020-08-13 12:26:49 +00:00
|
|
|
config, args, [*compose_cmd, '/bin/sh', '-c', f"which {shell}"],
|
2020-08-13 11:00:32 +00:00
|
|
|
check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL
|
|
|
|
)
|
|
|
|
return True
|
|
|
|
|
|
|
|
except subprocess.CalledProcessError:
|
|
|
|
# fallback
|
|
|
|
return False
|
|
|
|
|
|
|
|
|
2020-08-15 02:06:25 +00:00
|
|
|
def _find_shell(config, args, compose_cmd):
|
|
|
|
# as a last resort, fallback to "sh"
|
|
|
|
shells = ['/bin/sh', 'sh']
|
|
|
|
|
|
|
|
# load favorite shells from config
|
|
|
|
if config['runtime:shells']:
|
|
|
|
shells = [*config['runtime:shells'], *shells]
|
|
|
|
|
|
|
|
# consider shell from args
|
|
|
|
if args.shell:
|
|
|
|
shells = [args.shell, *shells]
|
|
|
|
|
|
|
|
logging.debug(f"Shells priority: {shells}")
|
|
|
|
|
|
|
|
# actually try shells
|
|
|
|
for i, shell in enumerate(shells):
|
|
|
|
if _service_has_shell(config, args, compose_cmd, shell):
|
|
|
|
# shell found
|
|
|
|
logging.debug(f"Using shell '{shell}'")
|
|
|
|
return shell
|
|
|
|
elif i + 1 < len(shells):
|
|
|
|
# not found, try next
|
|
|
|
logging.info(f"Shell '{shell}' not found in container, trying '{shells[i+1]}'")
|
|
|
|
else:
|
|
|
|
# not found, search exhausted
|
|
|
|
logging.error(f"None of the shells {shells} found in container, please provide -s SHELL!")
|
|
|
|
return None
|
|
|
|
|
|
|
|
|
2020-08-15 00:06:55 +00:00
|
|
|
class ShCommand(ServiceCommand):
|
2020-08-13 11:00:32 +00:00
|
|
|
def __init__(self):
|
|
|
|
super().__init__(
|
2020-08-13 12:26:49 +00:00
|
|
|
'sh',
|
|
|
|
description="Spawn shell inside a project's service"
|
2020-08-13 11:00:32 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
# -s switch: Select shell
|
|
|
|
self._sub_parser.add_argument(
|
2020-08-15 02:06:25 +00:00
|
|
|
'-s', '--shell', type=str,
|
2020-08-13 11:00:32 +00:00
|
|
|
help="shell to spawn"
|
|
|
|
)
|
|
|
|
|
|
|
|
def run(self, config, args):
|
2020-08-13 12:26:49 +00:00
|
|
|
compose_cmd = ['exec', args.services[0]]
|
2020-08-15 02:06:25 +00:00
|
|
|
shell = _find_shell(config, args, compose_cmd)
|
2020-08-13 11:00:32 +00:00
|
|
|
|
2020-08-15 02:06:25 +00:00
|
|
|
if shell:
|
|
|
|
# spawn shell
|
|
|
|
DockerCommand('docker-compose').run(
|
|
|
|
config, args, [*compose_cmd, shell]
|
|
|
|
)
|