Debian Codegraph @

osrf_pycommon/cli_utils/verb_pattern.py

raw
1 # Copyright 2014 Open Source Robotics Foundation, Inc.
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15 """API for implementing commands and verbs which used the verb pattern."""
16
17 import sys
18 import inspect
19
20 try:
21 import importlib.metadata as importlib_metadata
22 except ModuleNotFoundError:
23 import importlib_metadata
24
25
26 def call_prepare_arguments(func, parser, sysargs=None):
27 """Call a prepare_arguments function with the correct number of parameters.
28
29 The ``prepare_arguments`` function of a verb can either take one parameter,
30 ``parser``, or two parameters ``parser`` and ``args``, where ``args`` are
31 the current arguments being processed.
32
33 :param func: Callable ``prepare_arguments`` function.
34 :type func: Callable
35 :param parser: parser which is always passed to the function
36 :type parser: :py:class:`argparse.ArgumentParser`
37 :param sysargs: arguments to optionally pass to the function, if needed
38 :type sysargs: list
39 :returns: return value of function or the parser if the function
40 returns None.
41 :rtype: :py:class:`argparse.ArgumentParser`
42 :raises: ValueError if a function with the wrong number of parameters
43 is given
44 """
45 func_args = [parser]
46 # If the provided function takes two arguments and args were given
47 # also give the args to the function
48
49 # Remove the following if condition and keep else condition once Xenial is
50 # dropped
51 if sys.version_info[0] < 3:
52 arguments, _, _, defaults = inspect.getargspec(func)
53
54 else:
55 arguments, _, _, defaults, _, _, _ = inspect.getfullargspec(func)
56
57 if arguments[0] == 'self':
58 del arguments[0]
59 if defaults:
60 arguments = arguments[:-len(defaults)]
61 if len(arguments) not in [1, 2]:
62 # Remove the following if condition once Xenial is dropped
63 if sys.version_info[0] < 3:
64 raise ValueError("Given function '{0}' must have one or two "
65 "parameters (excluding self), but got '{1}' "
66 "parameters: '{2}'"
67 .format(func.__name__,
68 len(arguments),
69 ', '.join(inspect.getargspec(func)[0])))
70
71 raise ValueError("Given function '{0}' must have one or two "
72 "parameters (excluding self), but got '{1}' "
73 "parameters: '{2}'"
74 .format(func.__name__,
75 len(arguments),
76 ', '.join(inspect.getfullargspec(func)[0])))
77
78 if len(arguments) == 2:
79 func_args.append(sysargs or [])
80 return func(*func_args) or parser
81
82
83 def create_subparsers(parser, cmd_name, verbs, group, sysargs, title=None):
84 """Creates argparse subparsers for each verb which can be discovered.
85
86 Using the ``verbs`` parameter, the available verbs are iterated through.
87 For each verb a subparser is created for it using the ``parser`` parameter.
88 The ``cmd_name`` is used to fill the title and description of the
89 ``add_subparsers`` function call.
90 The ``group`` parameter is used with each verb to load the verb's
91 ``description``, ``prepare_arguments`` function, and the verb's
92 ``argument_preprocessors`` if available.
93 Each verb's ``prepare_arguments`` function is called, allowing them to
94 add arguments.
95 Finally a list of ``argument_preprocessors`` functions and verb subparsers
96 are returned, one for each verb.
97
98 :param parser: parser for this command
99 :type parser: :py:class:`argparse.ArgumentParser`
100 :param str cmd_name: name of the command to which the verbs are being added
101 :param list verbs: list of verbs (by name as a string)
102 :param str group: name of the ``entry_point`` group for the verbs
103 :param list sysargs: list of system arguments
104 :param str title: optional custom title for the command
105 :returns: tuple of argument_preprocessors and verb subparsers
106 :rtype: tuple
107 """
108 metavar = '[' + ' | '.join(verbs) + ']'
109 subparser = parser.add_subparsers(
110 title=title or '{0} command'.format(cmd_name),
111 metavar=metavar,
112 description='Call `{0} {1} -h` for help on each verb.'.format(
113 cmd_name, metavar),
114 dest='verb'
115 )
116
117 argument_preprocessors = {}
118 verb_subparsers = {}
119
120 for verb in verbs:
121 desc = load_verb_description(verb, group)
122 cmd_parser = subparser.add_parser(
123 desc['verb'], description=desc['description'])
124 cmd_parser = call_prepare_arguments(
125 desc['prepare_arguments'],
126 cmd_parser,
127 sysargs,
128 )
129
130 cmd_parser.set_defaults(main=desc['main'])
131
132 if 'argument_preprocessor' in desc:
133 argument_preprocessors[verb] = desc['argument_preprocessor']
134 else:
135 argument_preprocessors[verb] = default_argument_preprocessor
136 verb_subparsers[verb] = cmd_parser
137
138 return argument_preprocessors, verb_subparsers
139
140
141 def default_argument_preprocessor(args):
142 """Return unmodified args and an empty dict for extras"""
143 extras = {}
144 return args, extras
145
146
147 def list_verbs(group):
148 """List verbs available for a given ``entry_point`` group.
149
150 :param str group: ``entry_point`` group name for the verbs to list
151 :returns: list of verb names for the given ``entry_point`` group
152 :rtype: list of str
153 """
154 verbs = []
155 entry_points = importlib_metadata.entry_points()
156 if hasattr(entry_points, 'select'):
157 groups = entry_points.select(group=group)
158 else:
159 groups = entry_points.get(group, [])
160 for entry_point in groups:
161 verbs.append(entry_point.name)
162 return verbs
163
164
165 def load_verb_description(verb_name, group):
166 """Load description of a verb in a given group by name.
167
168 :param str verb_name: name of the verb to load, as a string
169 :param str group: ``entry_point`` group name which the verb is in
170 :returns: verb description
171 :rtype: dict
172 """
173 entry_points = importlib_metadata.entry_points()
174 if hasattr(entry_points, 'select'):
175 groups = entry_points.select(group=group)
176 else:
177 groups = entry_points.get(group, [])
178 for entry_point in groups:
179 if entry_point.name == verb_name:
180 return entry_point.load()
181
182
183 def split_arguments_by_verb(arguments):
184 """Split arguments by verb.
185
186 Given a list of arguments (list of strings), the verb, the pre verb
187 arguments, and the post verb arguments are returned.
188
189 For example:
190
191 .. code-block:: python
192
193 >>> args = ['--command-arg1', 'verb', '--verb-arg1', '--verb-arg2']
194 >>> split_arguments_by_verb(args)
195 ('verb', ['--command-arg1'], ['--verb-arg1', '--verb-arg2'])
196
197 :param list arguments: list of system arguments
198 :returns: the verb (str), pre verb args (list), and post verb args (list)
199 :rtype: tuple
200 """
201 verb = None
202 pre_verb_args = []
203 post_verb_args = []
204 for index, arg in enumerate(arguments):
205 # If the arg does not start with a `-` then it is a positional argument
206 # The first positional argument must be the verb
207 if not arg.startswith('-'):
208 verb = arg
209 post_verb_args = arguments[index + 1:]
210 break
211 # Otherwise it is a pre-verb option
212 pre_verb_args.append(arg)
213 return verb, pre_verb_args, post_verb_args