-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathcmd.py
39 lines (32 loc) · 1.21 KB
/
cmd.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
class Cmd:
@staticmethod
def execute(state, argv):
if not len(argv):
raise Exception('please provide a command, available: %s' %
' '.join(Cmd.cmds.iterkeys()))
cmd = argv.pop(0)
if not cmd in Cmd.cmds:
raise Exception('no such command, available: %s' %
' '.join(Cmd.cmds.iterkeys()))
fn = Cmd.cmds[cmd]
return fn(state, argv)
cmds = {}
def add_cmd(name, has_template, arity):
def gen(fn):
def check(args):
if len(args) != arity:
raise Exception('"%s" has %d args, %d given' % (name, arity, len(args)))
def no_templ(state, args):
check(args)
return fn(state, *args)
def templ(state, args):
if not len(args):
raise Exception('"%s" requires template name as 1st arg' % name)
tname = args.pop(0)
with open(tname, 'r') as tfile:
template = tfile.read()
check(args)
return fn(state, template, *args)
if name in Cmd.cmds: raise Exception('duplicate cmd "%s"' % name)
Cmd.cmds[name] = no_templ if not has_template else templ
return gen