-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathcommand.py
More file actions
executable file
·160 lines (98 loc) · 3.65 KB
/
command.py
File metadata and controls
executable file
·160 lines (98 loc) · 3.65 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
#!/usr/bin/env python2
# coding: utf-8
import argparse
import copy
import sys
import logging
import os
from pykit import dictutil
logger = logging.getLogger(__name__)
def command(**kwargs):
root, parser = add_command_help(kwargs)
inputs = sys.argv[1:]
try:
cmds = []
while len(inputs) > 0 and root.has_key(inputs[0]):
k = inputs.pop(0)
cmds.append(k)
node = root[k]
if is_node_executable(node):
call_able, args = parse_executable_node(parser, cmds, node, inputs)
try:
logger.debug("command: " + repr(cmds) + ' args: ' + repr(args) + ' cwd: ' + repr(os.getcwd()))
rc = call_able(*args)
sys.exit(0
if rc is True or rc is 0 or rc is None
else 1)
except Exception as e:
logger.exception(repr(e))
sys.stderr.write(repr(e))
sys.exit(1)
else:
root = node
if need_to_show_help(parser):
if len(cmds) > 0:
argv = [' '.join(cmds)] + inputs
else:
argv = inputs
parser.parse_args(argv)
else:
sys.stderr.write('No such command: ' + ' '.join(sys.argv[1:]))
sys.exit(2)
except Exception as e:
logger.exception(repr(e))
sys.stderr.write(repr(e))
sys.exit(1)
def add_command_help(commands):
new_cmds = copy.deepcopy(commands)
help_msgs = new_cmds.get('__add_help__')
desc = new_cmds.get('__description__')
for k in ('__add_help__', '__description__'):
if new_cmds.has_key(k):
del new_cmds[k]
if help_msgs is None:
return new_cmds, None
parser = argparse.ArgumentParser(description=desc, epilog='\n')
subparsers = parser.add_subparsers(help=' command(s) to select ...')
for cmds, execute_able in dictutil.depth_iter(new_cmds):
help = help_msgs.get(tuple(cmds), '')
cmd = ' '.join(cmds)
cmd_parser = subparsers.add_parser(cmd, help=help)
if need_param_help(execute_able):
call_able = execute_able[0]
param_msgs = execute_able[1:]
params = add_param_help(cmd_parser, param_msgs)
# delete help message
dictutil.make_setter(cmds)(new_cmds, (call_able, params))
return new_cmds, parser
def add_param_help(parser, param_msgs):
params = []
for param, msg in param_msgs:
parser.add_argument(param, **msg)
param = param.lstrip('-')
params.append(param)
return params
def parse_executable_node(parser, cmds, execute_able, args):
if not need_to_show_help(parser):
# no __add_help__ but has paramter help message
if args_need_to_parse(execute_able):
return execute_able[0], args
return execute_able, args
args_parsed = parser.parse_args([' '.join(cmds)] + args)
# to dict
args_parsed = vars(args_parsed)
if not args_need_to_parse(execute_able):
return execute_able, args
call_able, params = execute_able
args = [args_parsed.get(x) for x in params]
return call_able, args
def is_node_executable(node):
if isinstance(node, (list, tuple)) and len(node) > 0:
return callable(node[0])
return callable(node)
def need_to_show_help(parser):
return parser is not None
def args_need_to_parse(execute_able):
return isinstance(execute_able, tuple)
def need_param_help(execute_able):
return isinstance(execute_able, (list, tuple)) and len(execute_able) > 1