This commit fixes tightening type check fallout. add_subcommands() with a string pattern collects every class of the calling module whose name matches the pattern. inspect.getmembers() yields plain objects, so the unannotated collection list is inferred as list[object], which is not compatible with the declared list[type[Cmd]] parameter type, and make check fails on it. Annotate the collection list as list[type[Cmd]] and narrow it to subclasses of Cmd via issubclass(). This makes the implementation match the declared signature and stops classes lacking the Cmd interface from being registered as subcommands, where they would break later when instantiated and treated as Cmd in __add_cmd_to_parser(). Signed-off-by: Jan Lindemann <jan@janware.com> Assisted-by: unsloth/Qwen3.8-27B-GGUF:Q4_K_M with pi.dev v0.85.1
71 lines
2.2 KiB
Python
71 lines
2.2 KiB
Python
from __future__ import annotations
|
|
|
|
import abc
|
|
import argparse
|
|
import inspect
|
|
import re
|
|
import sys
|
|
|
|
from argparse import ArgumentParser
|
|
from typing import TYPE_CHECKING, Any
|
|
|
|
from . import log
|
|
|
|
if TYPE_CHECKING:
|
|
from .Cmds import Cmds
|
|
|
|
# full blown example of one level of nested subcommands
|
|
# git -C project remote -v show -n myremote
|
|
|
|
class Cmd(abc.ABC): # export
|
|
|
|
@abc.abstractmethod
|
|
async def run(self, args: Any) -> Any:
|
|
pass
|
|
|
|
def __init__(self, name: str, help: str) -> None:
|
|
self.name = name
|
|
self.help = help
|
|
self.parent = None
|
|
self.children: list[Cmd] = []
|
|
self.child_classes: list[type[Cmd]] = []
|
|
self.app: Cmds | None = None
|
|
|
|
async def _run(self, args: Any) -> Any:
|
|
pass
|
|
|
|
def add_parser(self, parsers: Any) -> ArgumentParser:
|
|
r = parsers.add_parser(
|
|
self.name,
|
|
help = self.help,
|
|
formatter_class = argparse.ArgumentDefaultsHelpFormatter
|
|
)
|
|
r.set_defaults(func = self.run)
|
|
return r # type: ignore[no-any-return]
|
|
|
|
def add_subcommands(self, cmd: str | type[Cmd] | list[type[Cmd]]) -> None:
|
|
if isinstance(cmd, str):
|
|
sc: list[type[Cmd]] = []
|
|
for name, obj in inspect.getmembers(sys.modules[self.__class__.__module__]):
|
|
if inspect.isclass(obj) and issubclass(obj, Cmd):
|
|
if re.search(cmd, str(obj)):
|
|
sc.append(obj)
|
|
log.slog(log.DEBUG, f"Found subcommand {obj}")
|
|
self.add_subcommands(sc)
|
|
return
|
|
if isinstance(cmd, list):
|
|
for c in cmd:
|
|
self.add_subcommands(c)
|
|
return
|
|
self.child_classes.append(cmd)
|
|
|
|
# To be overridden by derived class in case the command does take arguments.
|
|
# Will be called from App base class constructor and set up the parser hierarchy
|
|
def add_arguments(self, parser: ArgumentParser) -> None:
|
|
pass
|
|
|
|
def conf_value(self, path: str, default: Any = None) -> Any:
|
|
ret = None if self.app is None else self.app.conf_value(path, default)
|
|
if ret is None and default is not None:
|
|
return default
|
|
return ret
|