view sh-replay @ 11:82176b2a61da

Various tweaks to sh-replay
author Jordi Gutiérrez Hermoso <jordigh@octave.org>
date Sat, 08 Mar 2014 21:31:00 -0500
parents 39800c8f0532
children
line wrap: on
line source

#!/usr/bin/env python

import os,sys,subprocess
from colors import yellow, blue, magenta
from sh import hg, cd
import sh

curr_cmd = ""

def getch():
    import sys, tty, termios
    fd = sys.stdin.fileno()
    old_settings = termios.tcgetattr(fd)
    try:
        tty.setraw(sys.stdin.fileno())
        ch = sys.stdin.read(1)
    finally:
        termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
    if ord(ch) == 3:
        sys.exit(0)
    if ord(ch) == 12:
        subprocess.call("reset")
        print_prompt()
        sys.stdout.write(curr_cmd)
        sys.stdout.flush()

    return ch

def get_hg_id():
    try:
        book = hg.id(B=True).strip()
    except:
        book = False

    if book:
        return book

    try:
        branch = hg.branch().strip()
    except:
        return ""

    return branch

def print_prompt():
    cwd = os.getcwd()
    if cwd == "/home/jordi":
        cwd = "~"
    else:
        cwd = os.path.split(cwd)[-1]

    hg_id = get_hg_id()

    sys.stdout.write(yellow("jordi@evolve", style="bold") + ":"
                     + blue(cwd, style="bold") + " "
                     + magenta(hg_id, style="bold") + "\n$ ")

def waitforenter():
    while True:
        key = getch()
        if ord(key) == 13:
            sys.stdout.write("\n")
            sys.stdout.flush()
            break

def backtoslides():
    print
    print "    <---- Back to slides    "
    print
    waitforenter()

def main():
    subprocess.call("reset")
    with open(sys.argv[1]) as f:
        cmds = [cmd.strip() for cmd in f.readlines()
                if cmd.strip() and not cmd.strip().startswith("#")]

    global curr_cmd
    for cmd in cmds:
        print_prompt()

        # Control commands...
        if cmd[0] == "!":
            cmd = cmd[1:]
            if cmd == "RET":
                backtoslides()
            continue

        curr_cmd = ""
        for c in cmd:
            key = getch()
            sys.stdout.write(c)
            sys.stdout.flush()
            curr_cmd += c

        waitforenter()

        if cmd.startswith("cd "):
            cd(cmd[3:])
        else:
            with open("/tmp/cmd", "w") as f:
                f.write("shopt -s expand_aliases\n")
                f.write(cmd + "\n")
                f.flush()

            subprocess.call(["/bin/bash", "-l", "/tmp/cmd"])


if __name__ == "__main__":
    main()