forked from conan-io/conan
/
command.py
72 lines (58 loc) · 2.37 KB
/
command.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
import argparse
from conans.cli.cli import SmartFormatter, OnceArgument
from conans.errors import ConanException
class ConanCommand(object):
def __init__(self, method, group, formatters=None):
self._formatters = {}
for kind, action in formatters.items():
if callable(action):
self._formatters[kind] = action
else:
raise ConanException("Invalid formatter for {}. The formatter must be"
"a valid function".format(kind))
self._group = group or "Misc commands"
self._name = method.__name__.replace("_", "-")
self._method = method
if method.__doc__:
self._doc = method.__doc__
else:
raise ConanException("No documentation string defined for command: '{}'. Conan "
"commands should provide a documentation string explaining "
"its use briefly.".format(self._name))
self._parser = argparse.ArgumentParser(description=self._doc,
prog="conan {}".format(self._name),
formatter_class=SmartFormatter)
formatters_list = list(self._formatters.keys())
if self._formatters:
self._output_help_message = "Select the output format: {}"\
.format(", ".join(formatters_list))
self._parser.add_argument('-o', '--output', default="cli", choices=formatters_list,
action=OnceArgument, help=self._output_help_message)
def run(self, conan_api, *args, **kwargs):
try:
info = self._method(*args, conan_api=conan_api, **kwargs)
parser_args = self._parser.parse_args(*args)
if info:
self._formatters[parser_args.output](info, conan_api.out)
except Exception:
raise
@property
def group(self):
return self._group
@property
def name(self):
return self._name
@property
def method(self):
return self._method
@property
def doc(self):
return self._doc
@property
def parser(self):
return self._parser
def conan_command(group, formatters=None):
def decorator(f):
cmd = ConanCommand(f, group, formatters)
return cmd
return decorator