Debian Codegraph @

test/lib/ansible_test/_internal/cli/argparsing/parsers.py

raw
1 """General purpose composite argument parsing and completion."""
2
3 from __future__ import annotations
4
5 import abc
6 import collections.abc as c
7 import contextlib
8 import dataclasses
9 import enum
10 import os
11 import re
12 import typing as t
13
14 # NOTE: When choosing delimiters, take into account Bash and argcomplete behavior.
15 #
16 # Recommended characters for assignment and/or continuation: `/` `:` `=`
17 #
18 # The recommended assignment_character list is due to how argcomplete handles continuation characters.
19 # see: https://github.com/kislyuk/argcomplete/blob/5a20d6165fbb4d4d58559378919b05964870cc16/argcomplete/__init__.py#L557-L558
20
21 PAIR_DELIMITER = ','
22 ASSIGNMENT_DELIMITER = '='
23 PATH_DELIMITER = '/'
24
25
26 # This class was originally frozen. However, that causes issues when running under Python 3.11.
27 # See: https://github.com/python/cpython/issues/99856
28 @dataclasses.dataclass
29 class Completion(Exception):
30 """Base class for argument completion results."""
31
32
33 @dataclasses.dataclass
34 class CompletionUnavailable(Completion):
35 """Argument completion unavailable."""
36
37 message: str = 'No completions available.'
38
39
40 @dataclasses.dataclass
41 class CompletionError(Completion):
42 """Argument completion error."""
43
44 message: t.Optional[str] = None
45
46
47 @dataclasses.dataclass
48 class CompletionSuccess(Completion):
49 """Successful argument completion result."""
50
51 list_mode: bool
52 consumed: str
53 continuation: str
54 matches: list[str] = dataclasses.field(default_factory=list)
55
56 @property
57 def preserve(self) -> bool:
58 """
59 True if argcomplete should not mangle completion values, otherwise False.
60 Only used when more than one completion exists to avoid overwriting the word undergoing completion.
61 """
62 return len(self.matches) > 1 and self.list_mode
63
64 @property
65 def completions(self) -> list[str]:
66 """List of completion values to return to argcomplete."""
67 completions = self.matches
68 continuation = '' if self.list_mode else self.continuation
69
70 if not self.preserve:
71 # include the existing prefix to avoid rewriting the word undergoing completion
72 completions = [f'{self.consumed}{completion}{continuation}' for completion in completions]
73
74 return completions
75
76
77 class ParserMode(enum.Enum):
78 """Mode the parser is operating in."""
79
80 PARSE = enum.auto()
81 COMPLETE = enum.auto()
82 LIST = enum.auto()
83
84
85 class ParserError(Exception):
86 """Base class for all parsing exceptions."""
87
88
89 @dataclasses.dataclass
90 class ParserBoundary:
91 """Boundary details for parsing composite input."""
92
93 delimiters: str
94 required: bool
95 match: t.Optional[str] = None
96 ready: bool = True
97
98
99 @dataclasses.dataclass
100 class ParserState:
101 """State of the composite argument parser."""
102
103 mode: ParserMode
104 remainder: str = ''
105 consumed: str = ''
106 boundaries: list[ParserBoundary] = dataclasses.field(default_factory=list)
107 namespaces: list[t.Any] = dataclasses.field(default_factory=list)
108 parts: list[str] = dataclasses.field(default_factory=list)
109
110 @property
111 def incomplete(self) -> bool:
112 """True if parsing is incomplete (unparsed input remains), otherwise False."""
113 return self.remainder is not None
114
115 def match(self, value: str, choices: list[str]) -> bool:
116 """Return True if the given value matches the provided choices, taking into account parsing boundaries, otherwise return False."""
117 if self.current_boundary:
118 delimiters, delimiter = self.current_boundary.delimiters, self.current_boundary.match
119 else:
120 delimiters, delimiter = '', None
121
122 for choice in choices:
123 if choice.rstrip(delimiters) == choice:
124 # choice is not delimited
125 if value == choice:
126 return True # value matched
127 else:
128 # choice is delimited
129 if f'{value}{delimiter}' == choice:
130 return True # value and delimiter matched
131
132 return False
133
134 def read(self) -> str:
135 """Read and return the next input segment, taking into account parsing boundaries."""
136 delimiters = "".join(boundary.delimiters for boundary in self.boundaries)
137
138 if delimiters:
139 pattern = '([' + re.escape(delimiters) + '])'
140 regex = re.compile(pattern)
141 parts = regex.split(self.remainder, 1)
142 else:
143 parts = [self.remainder]
144
145 if len(parts) > 1:
146 value, delimiter, remainder = parts
147 else:
148 value, delimiter, remainder = parts[0], None, None
149
150 for boundary in reversed(self.boundaries):
151 if delimiter and delimiter in boundary.delimiters:
152 boundary.match = delimiter
153 self.consumed += value + delimiter
154 break
155
156 boundary.match = None
157 boundary.ready = False
158
159 if boundary.required:
160 break
161
162 self.remainder = remainder
163
164 return value
165
166 @property
167 def root_namespace(self) -> t.Any:
168 """THe root namespace."""
169 return self.namespaces[0]
170
171 @property
172 def current_namespace(self) -> t.Any:
173 """The current namespace."""
174 return self.namespaces[-1]
175
176 @property
177 def current_boundary(self) -> t.Optional[ParserBoundary]:
178 """The current parser boundary, if any, otherwise None."""
179 return self.boundaries[-1] if self.boundaries else None
180
181 def set_namespace(self, namespace: t.Any) -> None:
182 """Set the current namespace."""
183 self.namespaces.append(namespace)
184
185 @contextlib.contextmanager
186 def delimit(self, delimiters: str, required: bool = True) -> c.Iterator[ParserBoundary]:
187 """Context manager for delimiting parsing of input."""
188 boundary = ParserBoundary(delimiters=delimiters, required=required)
189
190 self.boundaries.append(boundary)
191
192 try:
193 yield boundary
194 finally:
195 self.boundaries.pop()
196
197 if boundary.required and not boundary.match:
198 raise ParserError('required delimiter not found, hit up-level delimiter or end of input instead')
199
200
201 @dataclasses.dataclass
202 class DocumentationState:
203 """State of the composite argument parser's generated documentation."""
204
205 sections: dict[str, str] = dataclasses.field(default_factory=dict)
206
207
208 class Parser(metaclass=abc.ABCMeta):
209 """Base class for all composite argument parsers."""
210
211 @abc.abstractmethod
212 def parse(self, state: ParserState) -> t.Any:
213 """Parse the input from the given state and return the result."""
214
215 def document(self, state: DocumentationState) -> t.Optional[str]:
216 """Generate and return documentation for this parser."""
217 raise Exception(f'Undocumented parser: {type(self)}')
218
219
220 class MatchConditions(enum.Flag):
221 """Acceptable condition(s) for matching user input to available choices."""
222
223 CHOICE = enum.auto()
224 """Match any choice."""
225 ANY = enum.auto()
226 """Match any non-empty string."""
227 NOTHING = enum.auto()
228 """Match an empty string which is not followed by a boundary match."""
229
230
231 class DynamicChoicesParser(Parser, metaclass=abc.ABCMeta):
232 """Base class for composite argument parsers which use a list of choices that can be generated during completion."""
233
234 def __init__(self, conditions: MatchConditions = MatchConditions.CHOICE) -> None:
235 self.conditions = conditions
236
237 @abc.abstractmethod
238 def get_choices(self, value: str) -> list[str]:
239 """Return a list of valid choices based on the given input value."""
240
241 def no_completion_match(self, value: str) -> CompletionUnavailable: # pylint: disable=unused-argument
242 """Return an instance of CompletionUnavailable when no match was found for the given value."""
243 return CompletionUnavailable()
244
245 def no_choices_available(self, value: str) -> ParserError: # pylint: disable=unused-argument
246 """Return an instance of ParserError when parsing fails and no choices are available."""
247 return ParserError('No choices available.')
248
249 def parse(self, state: ParserState) -> t.Any:
250 """Parse the input from the given state and return the result."""
251 value = state.read()
252 choices = self.get_choices(value)
253
254 if state.mode == ParserMode.PARSE or state.incomplete:
255 if self.conditions & MatchConditions.CHOICE and state.match(value, choices):
256 return value
257
258 if self.conditions & MatchConditions.ANY and value:
259 return value
260
261 if self.conditions & MatchConditions.NOTHING and not value and state.current_boundary and not state.current_boundary.match:
262 return value
263
264 if state.mode == ParserMode.PARSE:
265 if choices:
266 raise ParserError(f'"{value}" not in: {", ".join(choices)}')
267
268 raise self.no_choices_available(value)
269
270 raise CompletionUnavailable()
271
272 matches = [choice for choice in choices if choice.startswith(value)]
273
274 if not matches:
275 raise self.no_completion_match(value)
276
277 continuation = state.current_boundary.delimiters if state.current_boundary and state.current_boundary.required else ''
278
279 raise CompletionSuccess(
280 list_mode=state.mode == ParserMode.LIST,
281 consumed=state.consumed,
282 continuation=continuation,
283 matches=matches,
284 )
285
286
287 class ChoicesParser(DynamicChoicesParser):
288 """Composite argument parser which relies on a static list of choices."""
289
290 def __init__(self, choices: list[str], conditions: MatchConditions = MatchConditions.CHOICE) -> None:
291 self.choices = choices
292
293 super().__init__(conditions=conditions)
294
295 def get_choices(self, value: str) -> list[str]:
296 """Return a list of valid choices based on the given input value."""
297 return self.choices
298
299 def document(self, state: DocumentationState) -> t.Optional[str]:
300 """Generate and return documentation for this parser."""
301 return '|'.join(self.choices)
302
303
304 class EnumValueChoicesParser(ChoicesParser):
305 """Composite argument parser which relies on a static list of choices derived from the values of an enum."""
306
307 def __init__(self, enum_type: t.Type[enum.Enum], conditions: MatchConditions = MatchConditions.CHOICE) -> None:
308 self.enum_type = enum_type
309
310 super().__init__(choices=[str(item.value) for item in enum_type], conditions=conditions)
311
312 def parse(self, state: ParserState) -> t.Any:
313 """Parse the input from the given state and return the result."""
314 value = super().parse(state)
315 return self.enum_type(value)
316
317
318 class IntegerParser(DynamicChoicesParser):
319 """Composite argument parser for integers."""
320
321 PATTERN = re.compile('^[1-9][0-9]*$')
322
323 def __init__(self, maximum: t.Optional[int] = None) -> None:
324 self.maximum = maximum
325
326 super().__init__()
327
328 def get_choices(self, value: str) -> list[str]:
329 """Return a list of valid choices based on the given input value."""
330 if not value:
331 numbers = list(range(1, 10))
332 elif self.PATTERN.search(value):
333 int_prefix = int(value)
334 base = int_prefix * 10
335 numbers = [int_prefix] + [base + i for i in range(0, 10)]
336 else:
337 numbers = []
338
339 # NOTE: the minimum is currently fixed at 1
340
341 if self.maximum is not None:
342 numbers = [n for n in numbers if n <= self.maximum]
343
344 return [str(n) for n in numbers]
345
346 def parse(self, state: ParserState) -> t.Any:
347 """Parse the input from the given state and return the result."""
348 value = super().parse(state)
349 return int(value)
350
351 def document(self, state: DocumentationState) -> t.Optional[str]:
352 """Generate and return documentation for this parser."""
353 return '{integer}'
354
355
356 class BooleanParser(ChoicesParser):
357 """Composite argument parser for boolean (yes/no) values."""
358
359 def __init__(self) -> None:
360 super().__init__(['yes', 'no'])
361
362 def parse(self, state: ParserState) -> bool:
363 """Parse the input from the given state and return the result."""
364 value = super().parse(state)
365 return value == 'yes'
366
367
368 class AnyParser(ChoicesParser):
369 """Composite argument parser which accepts any input value."""
370
371 def __init__(self, nothing: bool = False, no_match_message: t.Optional[str] = None) -> None:
372 self.no_match_message = no_match_message
373
374 conditions = MatchConditions.ANY
375
376 if nothing:
377 conditions |= MatchConditions.NOTHING
378
379 super().__init__([], conditions=conditions)
380
381 def no_completion_match(self, value: str) -> CompletionUnavailable:
382 """Return an instance of CompletionUnavailable when no match was found for the given value."""
383 if self.no_match_message:
384 return CompletionUnavailable(message=self.no_match_message)
385
386 return super().no_completion_match(value)
387
388 def no_choices_available(self, value: str) -> ParserError:
389 """Return an instance of ParserError when parsing fails and no choices are available."""
390 if self.no_match_message:
391 return ParserError(self.no_match_message)
392
393 return super().no_choices_available(value)
394
395
396 class RelativePathNameParser(DynamicChoicesParser):
397 """Composite argument parser for relative path names."""
398
399 RELATIVE_NAMES = ['.', '..']
400
401 def __init__(self, choices: list[str]) -> None:
402 self.choices = choices
403
404 super().__init__()
405
406 def get_choices(self, value: str) -> list[str]:
407 """Return a list of valid choices based on the given input value."""
408 choices = list(self.choices)
409
410 if value in self.RELATIVE_NAMES:
411 # complete relative names, but avoid suggesting them unless the current name is relative
412 # unfortunately this will be sorted in reverse of what bash presents ("../ ./" instead of "./ ../")
413 choices.extend(f'{item}{PATH_DELIMITER}' for item in self.RELATIVE_NAMES)
414
415 return choices
416
417
418 class FileParser(Parser):
419 """Composite argument parser for absolute or relative file paths."""
420
421 def parse(self, state: ParserState) -> str:
422 """Parse the input from the given state and return the result."""
423 if state.mode == ParserMode.PARSE:
424 path = AnyParser().parse(state)
425
426 if not os.path.isfile(path):
427 raise ParserError(f'Not a file: {path}')
428 else:
429 path = ''
430
431 with state.delimit(PATH_DELIMITER, required=False) as boundary: # type: ParserBoundary
432 while boundary.ready:
433 directory = path or '.'
434
435 try:
436 with os.scandir(directory) as scan: # type: c.Iterator[os.DirEntry]
437 choices = [f'{item.name}{PATH_DELIMITER}' if item.is_dir() else item.name for item in scan]
438 except OSError:
439 choices = []
440
441 if not path:
442 choices.append(PATH_DELIMITER) # allow absolute paths
443 choices.append('../') # suggest relative paths
444
445 part = RelativePathNameParser(choices).parse(state)
446 path += f'{part}{boundary.match or ""}'
447
448 return path
449
450
451 class AbsolutePathParser(Parser):
452 """Composite argument parser for absolute file paths. Paths are only verified for proper syntax, not for existence."""
453
454 def parse(self, state: ParserState) -> t.Any:
455 """Parse the input from the given state and return the result."""
456 path = ''
457
458 with state.delimit(PATH_DELIMITER, required=False) as boundary: # type: ParserBoundary
459 while boundary.ready:
460 if path:
461 path += AnyParser(nothing=True).parse(state)
462 else:
463 path += ChoicesParser([PATH_DELIMITER]).parse(state)
464
465 path += boundary.match or ''
466
467 return path
468
469
470 class NamespaceParser(Parser, metaclass=abc.ABCMeta):
471 """Base class for composite argument parsers that store their results in a namespace."""
472
473 def parse(self, state: ParserState) -> t.Any:
474 """Parse the input from the given state and return the result."""
475 namespace = state.current_namespace
476 current = getattr(namespace, self.dest)
477
478 if current and self.limit_one:
479 if state.mode == ParserMode.PARSE:
480 raise ParserError('Option cannot be specified more than once.')
481
482 raise CompletionError('Option cannot be specified more than once.')
483
484 value = self.get_value(state)
485
486 if self.use_list:
487 if not current:
488 current = []
489 setattr(namespace, self.dest, current)
490
491 current.append(value)
492 else:
493 setattr(namespace, self.dest, value)
494
495 return value
496
497 def get_value(self, state: ParserState) -> t.Any:
498 """Parse the input from the given state and return the result, without storing the result in the namespace."""
499 return super().parse(state)
500
501 @property
502 def use_list(self) -> bool:
503 """True if the destination is a list, otherwise False."""
504 return False
505
506 @property
507 def limit_one(self) -> bool:
508 """True if only one target is allowed, otherwise False."""
509 return not self.use_list
510
511 @property
512 @abc.abstractmethod
513 def dest(self) -> str:
514 """The name of the attribute where the value should be stored."""
515
516
517 class NamespaceWrappedParser(NamespaceParser):
518 """Composite argument parser that wraps a non-namespace parser and stores the result in a namespace."""
519
520 def __init__(self, dest: str, parser: Parser) -> None:
521 self._dest = dest
522 self.parser = parser
523
524 def get_value(self, state: ParserState) -> t.Any:
525 """Parse the input from the given state and return the result, without storing the result in the namespace."""
526 return self.parser.parse(state)
527
528 @property
529 def dest(self) -> str:
530 """The name of the attribute where the value should be stored."""
531 return self._dest
532
533
534 class KeyValueParser(Parser, metaclass=abc.ABCMeta):
535 """Base class for key/value composite argument parsers."""
536
537 @abc.abstractmethod
538 def get_parsers(self, state: ParserState) -> dict[str, Parser]:
539 """Return a dictionary of key names and value parsers."""
540
541 def parse(self, state: ParserState) -> t.Any:
542 """Parse the input from the given state and return the result."""
543 namespace = state.current_namespace
544 parsers = self.get_parsers(state)
545 keys = list(parsers)
546
547 with state.delimit(PAIR_DELIMITER, required=False) as pair: # type: ParserBoundary
548 while pair.ready:
549 with state.delimit(ASSIGNMENT_DELIMITER):
550 key = ChoicesParser(keys).parse(state)
551
552 value = parsers[key].parse(state)
553
554 setattr(namespace, key, value)
555
556 keys.remove(key)
557
558 return namespace
559
560
561 class PairParser(Parser, metaclass=abc.ABCMeta):
562 """Base class for composite argument parsers consisting of a left and right argument parser, with input separated by a delimiter."""
563
564 def parse(self, state: ParserState) -> t.Any:
565 """Parse the input from the given state and return the result."""
566 namespace = self.create_namespace()
567
568 state.set_namespace(namespace)
569
570 with state.delimit(self.delimiter, self.required) as boundary: # type: ParserBoundary
571 choice = self.get_left_parser(state).parse(state)
572
573 if boundary.match:
574 self.get_right_parser(choice).parse(state)
575
576 return namespace
577
578 @property
579 def required(self) -> bool:
580 """True if the delimiter (and thus right parser) is required, otherwise False."""
581 return False
582
583 @property
584 def delimiter(self) -> str:
585 """The delimiter to use between the left and right parser."""
586 return PAIR_DELIMITER
587
588 @abc.abstractmethod
589 def create_namespace(self) -> t.Any:
590 """Create and return a namespace."""
591
592 @abc.abstractmethod
593 def get_left_parser(self, state: ParserState) -> Parser:
594 """Return the parser for the left side."""
595
596 @abc.abstractmethod
597 def get_right_parser(self, choice: t.Any) -> Parser:
598 """Return the parser for the right side."""
599
600
601 class TypeParser(Parser, metaclass=abc.ABCMeta):
602 """Base class for composite argument parsers which parse a type name, a colon and then parse results based on the type given by the type name."""
603
604 def get_parsers(self, state: ParserState) -> dict[str, Parser]: # pylint: disable=unused-argument
605 """Return a dictionary of type names and type parsers."""
606 return self.get_stateless_parsers()
607
608 @abc.abstractmethod
609 def get_stateless_parsers(self) -> dict[str, Parser]:
610 """Return a dictionary of type names and type parsers."""
611
612 def parse(self, state: ParserState) -> t.Any:
613 """Parse the input from the given state and return the result."""
614 parsers = self.get_parsers(state)
615
616 with state.delimit(':'):
617 key = ChoicesParser(list(parsers)).parse(state)
618
619 value = parsers[key].parse(state)
620
621 return value