from contextlib import contextmanager
from shlex import split
from subprocess import check_output
import os


def run(cmd, workspace):
    '''
    wrapper for executing the commands generated by the class members.
    commands are passed through shlex.parse for convenience.

    :param cmd: - String of the command to run. eg: echo "hello world".

    :returns: STDOUT of command execution

    :usage: c.run('docker-compose ps')
    '''
    with chdir("{}".format(workspace)):
        out = check_output(split(cmd))
        return out


# This is helpful for setting working directory context
@contextmanager
def chdir(path):
    '''Change the current working directory to a different directory to run
    commands and return to the previous directory after the command is done.'''
    old_dir = os.getcwd()
    os.chdir(path)
    yield
    os.chdir(old_dir)
