22809262fd4598b150428e7d8a4ea0fe1aef54e2
[saartuer.git] / tyshell
1 #!/usr/bin/python3
2 import os
3 import readline
4 import shlex
5 import sys
6 import subprocess
7 import socket
8
9 tuerSock = "/run/tuer.sock"
10
11 # use a histfile
12 histfile = os.path.join(os.path.expanduser("~"), ".tyshellhist")
13 try:
14     readline.read_history_file(histfile)
15 except IOError:
16     pass
17 import atexit
18 atexit.register(readline.write_history_file, histfile)
19
20 # available commands
21 def helpcmd(c):
22         print("Available commands: %s" % ", ".join(sorted(commands.keys())))
23
24 def extcmd(cmd):
25         def run(c):
26                 ret = subprocess.call(cmd)
27                 if ret != 0:
28                         print("Command returned non-zero exit statis %d" % ret)
29         return run
30
31 def sendcmd(addr, cmd):
32         def run(c):
33                 print("Running %s..." % (cmd))
34                 s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
35                 s.connect(addr)
36                 s.settimeout(10.0)
37                 s.send(cmd.encode())
38                 data = s.recv(4)
39                 s.close()
40                 print(data.decode('utf-8'))
41         return run
42
43 def exitcmd(c):
44         print("Bye")
45         return True
46
47 commands = {
48         'exit': exitcmd,
49         'help': helpcmd,
50         'open': sendcmd(tuerSock, 'open'),
51         'close': sendcmd(tuerSock, 'close'),
52         'buzz': sendcmd(tuerSock, 'buzz'),
53 }
54
55 # input loop
56 print("Welcome to tyshell. Use help to see what you can do.")
57 while True:
58         try:
59                 command = input("$ ")
60         except EOFError:
61                 print()
62                 break
63         command = shlex.split(command)
64         if not len(command): continue
65         # find suiting commands
66         if command[0] in commands: # needed in case a complete command is a prefix of another one
67                 cmdoptions = [command[0]]
68         else:
69                 cmdoptions = list(filter(lambda x: command[0].startswith(x), commands.keys()))
70         # check how many we found
71         if len(cmdoptions) == 0: # no commands fit prefix
72                 print("Command %s not found. Use help." % command[0])
73         elif len(cmdoptions) == 1: # exactly one command fits (prefix)
74                 try:
75                         res = commands[cmdoptions[0]](command)
76                         if res: break
77                 except Exception as e:
78                         print("Error while executing %s: %s" % (command[0], str(e)))
79         else: # multiple commands fit the prefix
80                 print("Ambiguous command prefix, please choose one of the following:")
81                 print("\t", " ".join(cmdoptions))
82                 # TODO: put current "command[0]" into the shell for the next command, but such that it is deletable with backspace
83