-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathshell.py
More file actions
228 lines (206 loc) · 7.28 KB
/
shell.py
File metadata and controls
228 lines (206 loc) · 7.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
import sys, tty, termios
import commands
conv = { 1: 'Ctrl-A', 2: 'Ctrl-B', 3: 'Ctrl-C', 4: 'Ctrl-D', 5: 'Ctrl-E', 6:
'Ctrl-F', 7: 'Ctrl-G', 8: 'Ctrl-H', 9: 'Ctrl-I', 10: 'Ctrl-J', 11:
'Ctrl-K', 12: 'Ctrl-L', 13: 'Return', 14: 'Ctrl-N', 15: 'Ctrl-O', 16:
'Ctrl-P', 17: 'Ctrl-Q', 18: 'Ctrl-R', 19: 'Ctrl-S', 20: 'Ctrl-T', 21:
'Ctrl-U', 22: 'Ctrl-V', 23: 'Ctrl-W', 24: 'Ctrl-X', 25: 'Ctrl-Y', 26:
'Ctrl-Z', 27: 'Escape', 127: 'Backspace' }
reverse_conv = {v: k for k, v in conv.items()}
def isvalidchar(c):
return type(c) == int and c >= 32 and c <= 122
def getch():
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)
return ch
def eline(l, cmds):
cmd = l.strip().split(' ')
if cmd[0] in cmds:
print()
cmds[cmd[0]]['func'](cmd[1:])
else:
print('\nUNKNOWN INPUT:', l)
def get_escaped_sequence():
c = getch()
if c == '[':
return c + getch()
elif ord(c) in conv:
return 'Alt-' + conv[ord(c)]
elif isvalidchar(ord(c)):
return 'Alt-' + c
else:
return c + getch()
def delchar(s, pos):
if pos == 0: return s
return s[:pos-1] + s[pos:]
def inschar(s, pos, c):
return s[:pos] + c + s[pos:]
def overlap(a, b):
r = ''
for c in range(min(len(a), len(b))):
if a[c] != b[c]: return r
r += a[c]
return r
def complete(s, cmds, cmd):
if cmd != None:
cmds = cmds[cmd]['params']
ls = None
similarcount = 0
for i in cmds:
if i.startswith(s):
if ls == None: ls = i
else:
ls = overlap(ls, i)
similarcount += 1
if ls == None: return s
elif ls == s and similarcount > 0:
print()
for cmd in cmds:
if cmd.startswith(s):
print(cmd)
elif similarcount == 0:
return ls + ' '
return ls
def help(modules, args):
def printhelp(cmd, desc):
print(f' {cmd:16s} {desc}')
if len(args) == 0:
print("To see more help about a module use 'help <module_name>'")
print("List of modules:")
for module in modules:
printhelp(module, modules[module]['desc'])
elif len(args) == 1:
if args[0] not in modules:
print("No such module")
return
print(f'List of commands defined in {args[0]}:')
for cmd in modules[args[0]]['cmds']:
printhelp(cmd, modules[args[0]]['cmds'][cmd]['desc'])
def shell(v = False):
modules = {
'builtin': {
'desc': 'the builtin functions',
'cmds': {
'help': {
'func': lambda line: help(modules, line),
'params': [],
'desc': 'Print help for all commands',
}
}
}
}
modules.update(commands.get_commands())
modules['builtin']['cmds']['help']['params'] = [m for m in modules]
cmds = {}
for module in modules:
cmds.update(modules[module]['cmds'])
keybinds = {
reverse_conv['Return']: 'Submit',
reverse_conv['Backspace']: 'Delete',
reverse_conv['Ctrl-C']: 'Exit',
reverse_conv['Ctrl-D']: 'Exit',
reverse_conv['Ctrl-I']: 'Complete',
reverse_conv['Ctrl-L']: 'Clear',
reverse_conv['Ctrl-A']: 'Home',
reverse_conv['Ctrl-E']: 'End',
reverse_conv['Ctrl-B']: 'BackChar',
'Alt-f': 'ForwardWord',
'Alt-b': 'BackWord',
reverse_conv['Ctrl-K']: 'KillLine',
reverse_conv['Ctrl-F']: 'ForwardChar',
reverse_conv['Ctrl-P']: 'HistoryUp',
reverse_conv['Ctrl-N']: 'HistoryDown',
'[H': 'Home',
'[F': 'End',
'[C': 'ForwardChar',
'[D': 'BackChar',
'[A': 'HistoryUp',
'[B': 'HistoryDown',
}
buf = ''
cursor = 0
history = ['']
hindex = 0
print(end='> ', flush=True)
while c := ord(getch()):
if c == reverse_conv['Escape']:
c = get_escaped_sequence()
if c in keybinds:
match keybinds[c]:
case 'Exit':
print()
print("BYE!")
break
case 'Submit':
if buf.strip() != '':
eline(buf, cmds)
history[-1] = buf
history.append('')
hindex = len(history)-1
buf = ''
cursor = 0
case 'Delete':
buf = delchar(buf, cursor)
if cursor > 0: cursor -= 1
case 'Complete':
i = cursor
while i > 0 and buf[i-1] != ' ': i -= 1
cmd = None
if buf[:i].strip() != '':
cmd = buf.strip().split(' ')[0].strip()
compl = complete(buf[i:cursor], cmds, cmd)
cursor += len(compl) - (cursor-i)
buf = buf[:i] + compl + buf[cursor:]
case 'Clear':
print(end='\033[2J\033[1;0H')
case 'Home':
cursor = 0
case 'End':
cursor = len(buf)
case 'BackChar':
if cursor > 0: cursor -= 1
case 'KillLine':
buf = buf[:cursor]
case 'ForwardChar':
if cursor < len(buf): cursor += 1
case 'BackWord':
if cursor == len(buf): cursor -= 1
if buf[cursor] != ' ': cursor -= 1
while cursor > 0 and buf[cursor] == ' ':
cursor -= 1
while cursor > 0 and buf[cursor] != ' ':
cursor -= 1
if cursor > 1 and cursor < len(buf): cursor += 1
case 'ForwardWord':
if cursor == len(buf): cursor -= 1
if buf[cursor] != ' ': cursor -= 1
while cursor < len(buf) and buf[cursor] == ' ':
cursor += 1
while cursor < len(buf) and buf[cursor] != ' ':
cursor += 1
if cursor > 1 and cursor < len(buf): cursor += 1
case 'HistoryUp':
if hindex > 0: hindex -= 1
buf = history[hindex]
cursor = len(buf)
case 'HistoryDown':
if hindex < len(history)-1: hindex += 1
buf = history[hindex]
cursor = len(buf)
case _:
if v: print('Unimplemented:', keybinds[c])
elif c in conv:
if v: print('\nUnbound:', conv[c], reverse_conv[conv[c]])
elif isvalidchar(c):
buf = inschar(buf, cursor, chr(c))
cursor += 1
else:
if v: print('\nUnknown:', c)
print('\r> ' + buf + '\033[K' + '\033[D' * (len(buf)-cursor), end='', flush=True)
if __name__ == '__main__':
shell(v=False)