Debian Codegraph @

osc_lib/cli/parseractions.py

raw
1 # Copyright 2013 OpenStack Foundation
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License"); you may
4 # not use this file except in compliance with the License. You may obtain
5 # 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, WITHOUT
11 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 # License for the specific language governing permissions and limitations
13 # under the License.
14 #
15
16 """argparse Custom Actions"""
17
18 import argparse
19 import collections.abc
20 import typing as ty
21
22 from osc_lib.i18n import _
23
24 _T = ty.TypeVar('_T')
25
26
27 class KeyValueAction(argparse.Action):
28 """A custom action to parse arguments as key=value pairs
29
30 Ensures that ``dest`` is a dict and values are strings.
31 """
32
33 def __call__(
34 self,
35 parser: argparse.ArgumentParser,
36 namespace: argparse.Namespace,
37 values: str | ty.Sequence[ty.Any] | None,
38 option_string: str | None = None,
39 ) -> None:
40 if not isinstance(values, str):
41 raise TypeError('expected str')
42
43 # Make sure we have an empty dict rather than None
44 if getattr(namespace, self.dest, None) is None:
45 setattr(namespace, self.dest, {})
46
47 # Add value if an assignment else remove it
48 if '=' in values:
49 values_list = values.split('=', 1)
50 # NOTE(qtang): Prevent null key setting in property
51 if '' == values_list[0]:
52 msg = _("Property key must be specified: %s")
53 raise argparse.ArgumentError(self, msg % str(values))
54 else:
55 getattr(namespace, self.dest, {}).update(dict([values_list]))
56 else:
57 msg = _("Expected 'key=value' type, but got: %s")
58 raise argparse.ArgumentError(self, msg % str(values))
59
60
61 class KeyValueAppendAction(argparse.Action):
62 """A custom action to parse arguments as key=value pairs
63
64 Ensures that ``dest`` is a dict and values are lists of strings.
65 """
66
67 def __call__(
68 self,
69 parser: argparse.ArgumentParser,
70 namespace: argparse.Namespace,
71 values: str | ty.Sequence[ty.Any] | None,
72 option_string: str | None = None,
73 ) -> None:
74 if not isinstance(values, str):
75 raise TypeError('expected str')
76
77 # Make sure we have an empty dict rather than None
78 if getattr(namespace, self.dest, None) is None:
79 setattr(namespace, self.dest, {})
80
81 # Add value if an assignment else remove it
82 if '=' in values:
83 key, value = values.split('=', 1)
84 # NOTE(qtang): Prevent null key setting in property
85 if '' == key:
86 msg = _("Property key must be specified: %s")
87 raise argparse.ArgumentError(self, msg % str(values))
88
89 dest = getattr(namespace, self.dest)
90 if key in dest:
91 dest[key].append(value)
92 else:
93 dest[key] = [value]
94 else:
95 msg = _("Expected 'key=value' type, but got: %s")
96 raise argparse.ArgumentError(self, msg % str(values))
97
98
99 class MultiKeyValueAction(argparse.Action):
100 """A custom action to parse arguments as key1=value1,key2=value2 pairs
101
102 Ensure that ``dest`` is a list. The list will finally contain multiple
103 dicts, with key=value pairs in them.
104
105 NOTE: The arguments string should be a comma separated key-value pairs.
106 And comma(',') and equal('=') may not be used in the key or value.
107 """
108
109 def __init__(
110 self,
111 option_strings: ty.Sequence[str],
112 dest: str,
113 nargs: int | str | None = None,
114 required_keys: ty.Sequence[str] | None = None,
115 optional_keys: ty.Sequence[str] | None = None,
116 const: _T | None = None,
117 default: _T | str | None = None,
118 type: collections.abc.Callable[[str], _T] | None = None,
119 choices: collections.abc.Iterable[_T] | None = None,
120 required: bool = False,
121 help: str | None = None,
122 metavar: str | tuple[str, ...] | None = None,
123 ) -> None:
124 """Initialize the action object, and parse customized options
125
126 Required keys and optional keys can be specified when initializing
127 the action to enable the key validation. If none of them specified,
128 the key validation will be skipped.
129
130 :param required_keys: a list of required keys
131 :param optional_keys: a list of optional keys
132 """
133 if nargs:
134 msg = _("Parameter 'nargs' is not allowed, but got %s")
135 raise ValueError(msg % nargs)
136
137 super().__init__(
138 option_strings,
139 dest,
140 nargs=nargs,
141 const=const,
142 default=default,
143 type=type,
144 choices=choices,
145 required=required,
146 help=help,
147 metavar=metavar,
148 )
149
150 # required_keys: A list of keys that is required. None by default.
151 if required_keys and not isinstance(required_keys, list):
152 msg = _("'required_keys' must be a list")
153 raise TypeError(msg)
154
155 self.required_keys = set(required_keys or [])
156
157 # optional_keys: A list of keys that is optional. None by default.
158 if optional_keys and not isinstance(optional_keys, list):
159 msg = _("'optional_keys' must be a list")
160 raise TypeError(msg)
161 self.optional_keys = set(optional_keys or [])
162
163 def validate_keys(self, keys: ty.Sequence[str]) -> None:
164 """Validate the provided keys.
165
166 :param keys: A list of keys to validate.
167 """
168 # Check key validation
169 valid_keys = self.required_keys | self.optional_keys
170 if valid_keys:
171 invalid_keys = [k for k in keys if k not in valid_keys]
172 if invalid_keys:
173 msg = _(
174 "Invalid keys %(invalid_keys)s specified.\n"
175 "Valid keys are: %(valid_keys)s"
176 )
177 raise argparse.ArgumentError(
178 self,
179 msg
180 % {
181 'invalid_keys': ', '.join(invalid_keys),
182 'valid_keys': ', '.join(valid_keys),
183 },
184 )
185
186 if self.required_keys:
187 missing_keys = [k for k in self.required_keys if k not in keys]
188 if missing_keys:
189 msg = _(
190 "Missing required keys %(missing_keys)s.\n"
191 "Required keys are: %(required_keys)s"
192 )
193 raise argparse.ArgumentError(
194 self,
195 msg
196 % {
197 'missing_keys': ', '.join(missing_keys),
198 'required_keys': ', '.join(self.required_keys),
199 },
200 )
201
202 def __call__(
203 self,
204 parser: argparse.ArgumentParser,
205 namespace: argparse.Namespace,
206 values: str | ty.Sequence[ty.Any] | None,
207 option_string: str | None = None,
208 ) -> None:
209 if not isinstance(values, str):
210 raise TypeError('expected str')
211
212 # Make sure we have an empty list rather than None
213 if getattr(namespace, self.dest, None) is None:
214 setattr(namespace, self.dest, [])
215
216 params: dict[str, str] = {}
217 for kv in values.split(','):
218 # Add value if an assignment else raise ArgumentError
219 if '=' in kv:
220 kv_list = kv.split('=', 1)
221 # NOTE(qtang): Prevent null key setting in property
222 if '' == kv_list[0]:
223 msg = _("Each property key must be specified: %s")
224 raise argparse.ArgumentError(self, msg % str(kv))
225 else:
226 params.update(dict([kv_list]))
227 else:
228 msg = _(
229 "Expected comma separated 'key=value' pairs, but got: %s"
230 )
231 raise argparse.ArgumentError(self, msg % str(kv))
232
233 # Check key validation
234 self.validate_keys(list(params))
235
236 # Update the dest dict
237 getattr(namespace, self.dest, []).append(params)
238
239
240 class MultiKeyValueCommaAction(MultiKeyValueAction):
241 """Custom action to parse arguments from a set of key=value pair
242
243 Ensures that ``dest`` is a dict.
244 Parses dict by separating comma separated string into individual values
245 Ex. key1=val1,val2,key2=val3 => {"key1": "val1,val2", "key2": "val3"}
246 """
247
248 def __call__(
249 self,
250 parser: argparse.ArgumentParser,
251 namespace: argparse.Namespace,
252 values: str | ty.Sequence[ty.Any] | None,
253 option_string: str | None = None,
254 ) -> None:
255 """Overwrite the __call__ function of MultiKeyValueAction
256
257 This is done to handle scenarios where we may have comma seperated
258 data as a single value.
259 """
260 if not isinstance(values, str):
261 msg = _("Invalid key=value pair, non-string value provided: %s")
262 raise argparse.ArgumentError(self, msg % str(values))
263
264 # Make sure we have an empty list rather than None
265 if getattr(namespace, self.dest, None) is None:
266 setattr(namespace, self.dest, [])
267
268 params: dict[str, str] = {}
269 key = ''
270 for kv in values.split(','):
271 # Add value if an assignment else raise ArgumentError
272 if '=' in kv:
273 kv_list = kv.split('=', 1)
274 # NOTE(qtang): Prevent null key setting in property
275 if '' == kv_list[0]:
276 msg = _("A key must be specified before '=': %s")
277 raise argparse.ArgumentError(self, msg % str(kv))
278 else:
279 params.update(dict([kv_list]))
280 key = kv_list[0]
281 else:
282 # If the ',' split does not have key=value pair, then it
283 # means the current value is a part of the previous
284 # key=value pair, so append it.
285 try:
286 params[key] = f"{params[key]},{kv}"
287 except KeyError:
288 msg = _("A key=value pair is required: %s")
289 raise argparse.ArgumentError(self, msg % str(kv))
290
291 # Check key validation
292 self.validate_keys(list(params))
293
294 # Update the dest dict
295 getattr(namespace, self.dest, []).append(params)
296
297
298 class RangeAction(argparse.Action):
299 """A custom action to parse a single value or a range of values
300
301 Parses single integer values or a range of integer values delimited
302 by a colon and returns a tuple of integers:
303 '4' sets ``dest`` to (4, 4)
304 '6:9' sets ``dest`` to (6, 9)
305 """
306
307 def __call__(
308 self,
309 parser: argparse.ArgumentParser,
310 namespace: argparse.Namespace,
311 values: str | ty.Sequence[ty.Any] | None,
312 option_string: str | None = None,
313 ) -> None:
314 if not isinstance(values, str):
315 msg = _("Invalid range, non-string value provided")
316 raise argparse.ArgumentError(self, msg)
317
318 range = values.split(':')
319 if len(range) == 0:
320 # Nothing passed, return a zero default
321 setattr(namespace, self.dest, (0, 0))
322 elif len(range) == 1:
323 # Only a single value is present
324 setattr(namespace, self.dest, (int(range[0]), int(range[0])))
325 elif len(range) == 2:
326 # Range of two values
327 if int(range[0]) <= int(range[1]):
328 setattr(namespace, self.dest, (int(range[0]), int(range[1])))
329 else:
330 msg = _("Invalid range, %(min)s is not less than %(max)s")
331 raise argparse.ArgumentError(
332 self,
333 msg
334 % {
335 'min': range[0],
336 'max': range[1],
337 },
338 )
339 else:
340 # Too many values
341 msg = _("Invalid range, too many values")
342 raise argparse.ArgumentError(self, msg)
343
344
345 class NonNegativeAction(argparse.Action):
346 """A custom action to check whether the value is non-negative or not
347
348 Ensures the value is >= 0.
349 """
350
351 def __call__(
352 self,
353 parser: argparse.ArgumentParser,
354 namespace: argparse.Namespace,
355 values: str | ty.Sequence[ty.Any] | None,
356 option_string: str | None = None,
357 ) -> None:
358 if not isinstance(values, str | int | float):
359 msg = _("%s expected a non-negative integer")
360 raise argparse.ArgumentError(self, msg % str(option_string))
361
362 if int(values) >= 0:
363 setattr(namespace, self.dest, values)
364 else:
365 msg = _("%s expected a non-negative integer")
366 raise argparse.ArgumentError(self, msg % str(option_string))