Create and store all command method argument parsers for a given Cmd instance. Parser creation and retrieval are accomplished through the get() method.
| 230 | |
| 231 | |
| 232 | class CommandParsers: |
| 233 | """Create and store all command method argument parsers for a given Cmd instance. |
| 234 | |
| 235 | Parser creation and retrieval are accomplished through the get() method. |
| 236 | """ |
| 237 | |
| 238 | def __init__(self, cmd: "Cmd") -> None: |
| 239 | """Initialize CommandParsers. |
| 240 | |
| 241 | :param cmd: the Cmd instance whose parsers are being managed |
| 242 | """ |
| 243 | self._cmd = cmd |
| 244 | |
| 245 | # Keyed by the fully qualified method names. This is more reliable than |
| 246 | # the methods themselves, since wrapping a method will change its address. |
| 247 | self._parsers: dict[str, Cmd2ArgumentParser] = {} |
| 248 | |
| 249 | @staticmethod |
| 250 | def _fully_qualified_name(command_method: BoundCommandFunc) -> str: |
| 251 | """Return the fully qualified name of a method or None if a method wasn't passed in.""" |
| 252 | try: |
| 253 | return f"{command_method.__module__}.{command_method.__qualname__}" |
| 254 | except AttributeError: |
| 255 | return "" |
| 256 | |
| 257 | def __contains__(self, command_method: BoundCommandFunc) -> bool: |
| 258 | """Return whether a given method's parser is in self. |
| 259 | |
| 260 | If the parser does not yet exist, it will be created if applicable. |
| 261 | This is basically for checking if a method is argarse-based. |
| 262 | """ |
| 263 | parser = self.get(command_method) |
| 264 | return bool(parser) |
| 265 | |
| 266 | def get(self, command_method: BoundCommandFunc) -> Cmd2ArgumentParser | None: |
| 267 | """Return a given method's parser or None if the method is not argparse-based. |
| 268 | |
| 269 | If the parser does not yet exist, it will be created. |
| 270 | """ |
| 271 | full_method_name = self._fully_qualified_name(command_method) |
| 272 | if not full_method_name: |
| 273 | return None |
| 274 | |
| 275 | if full_method_name not in self._parsers: |
| 276 | if not command_method.__name__.startswith(COMMAND_FUNC_PREFIX): |
| 277 | return None |
| 278 | command = command_method.__name__[len(COMMAND_FUNC_PREFIX) :] |
| 279 | |
| 280 | parser_builder = getattr(command_method, constants.CMD_ATTR_ARGPARSER, None) |
| 281 | if parser_builder is None: |
| 282 | return None |
| 283 | |
| 284 | parent = self._cmd.find_commandset_for_command(command) or self._cmd |
| 285 | parser = self._cmd._build_parser(parent, parser_builder) |
| 286 | |
| 287 | # To ensure accurate usage strings, recursively update 'prog' values |
| 288 | # within the parser to match the command name. |
| 289 | parser.update_prog(command) |
no outgoing calls
no test coverage detected
searching dependent graphs…