Eclectic Media Git run_in_split / master run_in_split / __main__.py
master

Tree @master (Download .tar.gz)

__main__.py @masterraw · history · blame

from os import system, environ
from click import command, argument, option
import shlex


@command()
@argument('command')
@option('--horizontal', is_flag=True,
        help='Split pane horizontally.')
@option('--sleep', is_flag=True,
        help='If true, sleep for five seconds after the command exits.')
@option('--pause', is_flag=True,
        help='If true, pause until user presses enter.')
@option('--pause-on-error', is_flag=True,
        help='If true, pause until user presses enter only if the process does '
        'not exit 0.')
@option('--small', is_flag=True,
        help='Creates pane at 15% of total screen space')
def run_in_pane(command, **kwargs):
    if not list(environ).count('TMUX'):
        raise RuntimeError('CRITICAL! Must be run within TMUX!')

    executable = 'tmux split-window'

    if list(kwargs).count('horizontal'):
        if kwargs['horizontal']:
            executable += ' -h'

    if kwargs['small']:
        executable += ' -p 15'

    executable += " '{}".format(command)
    # current command (if "echo hello world"):
    # tmux split-window 'echo hello world

    if kwargs['sleep']:
        if kwargs['pause'] or kwargs['pause_on_error']:
            raise KeyError('Cannot use --sleep in combination with --pause or '
                           '--pause-on-error!')

        executable += "; sleep 5"
        # current command (if "echo hello world"):
        # tmux split-window 'echo hello world; sleep 5

    if kwargs['pause']:
        if kwargs['sleep'] or kwargs['pause_on_error']:
            raise KeyError('Cannot use --pause in combination with --sleep or '
                           '--pause-on-error!')

        executable += "; read"
        # current command (if "echo hello world"):
        # tmux split-window 'echo hello world; read

    if kwargs['pause_on_error']:
        if kwargs['sleep'] or kwargs['pause']:
            raise KeyError('Cannot use --pause_on_error in combination with '
                           '--sleep or --pause!')

        executable += "; if [ $? != 0 ]; then read; fi"
        # current command (if "echo hello world"):
        # tmux split-window 'echo hello world; if [ $? != 0 ]; then read; fi

    executable += "'"  # close command quote
    system(executable)


try:
    run_in_pane()
except Exception as e:
    print(str(e))