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
|
2020-08-13 12:26:49 +00:00
|
|
|
logging.info(f"Shell '{shell}' not found in container")
|
2020-08-13 11:00:32 +00:00
|
|
|
return False
|
|
|
|
|
|
|
|
|
|
|
|
class ShellCommand(ServiceCommand):
|
|
|
|
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(
|
|
|
|
'-s', '--shell', type=str, default="/bin/bash",
|
|
|
|
help="shell to spawn"
|
|
|
|
)
|
|
|
|
|
|
|
|
def run(self, config, args):
|
2020-08-13 12:26:49 +00:00
|
|
|
compose_cmd = ['exec', args.services[0]]
|
|
|
|
shell = args.shell
|
2020-08-13 11:00:32 +00:00
|
|
|
|
2020-08-13 12:26:49 +00:00
|
|
|
if not _service_has_shell(config, args, compose_cmd, shell):
|
|
|
|
# fallback
|
|
|
|
shell = '/bin/bash'
|
2020-08-13 11:00:32 +00:00
|
|
|
|
2020-08-13 12:26:49 +00:00
|
|
|
if not _service_has_shell(config, args, compose_cmd, shell):
|
|
|
|
# safe fallback
|
|
|
|
shell = '/bin/sh'
|
2020-08-13 11:00:32 +00:00
|
|
|
|
2020-08-13 12:26:49 +00:00
|
|
|
# spawn shell
|
|
|
|
DockerCommand('docker-compose').run(
|
|
|
|
config, args, [*compose_cmd, shell]
|
|
|
|
)
|