forked from Charcoal-SE/SmokeDetector
-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.py
executable file
·93 lines (72 loc) · 2.24 KB
/
util.py
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
#!/usr/bin/env python3
# A CLI utility for various Smokey functions
import sys
import os
import shlex
import inspect
import helpers
helpers.log = lambda *args, **kwargs: None # Override log() for less verbosity
import chatcommands
# A utility is "name: (description, func)"
utilities = {}
def utility(name, description):
def wrapper(func):
global utilities
utilities[name] = (description, func)
return func
return wrapper
@utility("bisect", "finds out which blacklist/watchlist item matches a string")
def util_bisect(*args):
for s in args:
print(chatcommands.bisect.__func__(None, s) + "\n")
@utility("exit", "exit this utility (interactive mode)")
def util_exit():
exit()
@utility("help", "display a list of available sub-commands")
def util_help():
cmds = [(n, v[0], v[1]) for n, v in utilities.items()]
maxlen = max([len(x[0]) for x in cmds])
template = " {{:{}}} {{}}".format(maxlen)
print("List of available commands:\n" + "\n".join([template.format(n, d) for n, d, f in cmds]))
def main_start_interactive():
try:
import readline
except ImportError:
pass
print("Smokey utility\nType \"help\" for a list of commands", file=sys.stderr)
def main_loop(args):
try:
name = args.pop(0)
except IndexError:
exit()
if name not in utilities:
print("Error: function {!r} is not defined".format(name), file=sys.stderr)
return
desc, func = utilities[name]
func_args = inspect.getargspec(func)
min_args = len(func_args[0] or "") - len(func_args[3] or "")
if len(args) < min_args:
print("Too few arguments")
elif not func_args[1] and len(args) > len(func_args[0] or ""):
print("Too many arguments")
else:
func(*args)
def get_input():
try:
s = ""
s = input("$ ")
while True:
try:
return shlex.split(s)
except ValueError:
s += input("> ") # continue reading
except EOFError:
print()
return [] if s else ["exit"]
if __name__ == "__main__":
if len(sys.argv) == 1:
main_start_interactive()
while True:
main_loop(get_input())
else:
main_loop(sys.argv[1:])