|
7 | 7 | __copyright__ = "Copyright 2024, Embeint Holdings Pty Ltd" |
8 | 8 |
|
9 | 9 | import argparse |
| 10 | +import importlib |
10 | 11 | import importlib.util |
| 12 | +import os |
11 | 13 | import pathlib |
12 | | -import pkgutil |
13 | 14 | import sys |
14 | 15 | import types |
| 16 | +from dataclasses import dataclass |
| 17 | +from typing import Any |
15 | 18 |
|
16 | 19 | import argcomplete |
| 20 | +from argcomplete.lexers import split_line |
17 | 21 |
|
18 | | -import infuse_iot.tools |
19 | | -from infuse_iot.commands import InfuseCommand |
20 | 22 | from infuse_iot.credentials import get_custom_tool_path |
| 23 | +from infuse_iot.tools.registry import TOOLS, ToolSpec, load_extension_tools |
21 | 24 | from infuse_iot.version import __version__ |
22 | 25 |
|
23 | 26 |
|
| 27 | +@dataclass(frozen=True) |
| 28 | +class RegisteredTool: |
| 29 | + spec: ToolSpec |
| 30 | + extension_path: pathlib.Path | None = None |
| 31 | + |
| 32 | + |
24 | 33 | class InfuseApp: |
25 | 34 | """The infuse 'application' object""" |
26 | 35 |
|
27 | 36 | def __init__(self): |
28 | 37 | self.args = None |
29 | 38 | self.parser = argparse.ArgumentParser("infuse") |
30 | 39 | self.parser.add_argument("--version", action="version", version=f"{__version__}") |
31 | | - self._tools = {} |
| 40 | + self._tools: dict[str, RegisteredTool] = {} |
| 41 | + self._tool_parsers = {} |
| 42 | + self._loaded_tools = set() |
32 | 43 | # Load tools |
33 | 44 | self._load_tools(self.parser) |
34 | | - # Handle CLI tab completion |
35 | | - argcomplete.autocomplete(self.parser) |
36 | 45 |
|
37 | 46 | def run(self, argv): |
38 | 47 | """Run the chosen subtool handler""" |
| 48 | + argv = argv or sys.argv[1:] |
| 49 | + self._load_selected_tool(argv) |
| 50 | + self._load_selected_completion_tool() |
| 51 | + # Handle CLI tab completion |
| 52 | + argcomplete.autocomplete(self.parser) |
39 | 53 | self.args = self.parser.parse_args(argv) |
40 | 54 |
|
41 | 55 | tool = self.args.tool_class(self.args) |
42 | 56 | tool.run() |
43 | 57 |
|
44 | | - def _load_from_module(self, parent_parser: argparse._SubParsersAction, module: types.ModuleType): |
45 | | - tool_cls: InfuseCommand = module.SubCommand |
46 | | - parser = parent_parser.add_parser( |
47 | | - tool_cls.NAME, |
48 | | - help=tool_cls.HELP, |
49 | | - description=tool_cls.DESCRIPTION, |
50 | | - formatter_class=argparse.RawDescriptionHelpFormatter, |
51 | | - ) |
| 58 | + def _load_from_module( |
| 59 | + self, |
| 60 | + parent_parser: argparse._SubParsersAction, |
| 61 | + module: types.ModuleType, |
| 62 | + parser: argparse.ArgumentParser | None = None, |
| 63 | + ): |
| 64 | + tool_cls: Any = module.SubCommand |
| 65 | + if parser is None: |
| 66 | + parser = parent_parser.add_parser( |
| 67 | + tool_cls.NAME, |
| 68 | + help=tool_cls.HELP, |
| 69 | + description=tool_cls.DESCRIPTION, |
| 70 | + formatter_class=argparse.RawDescriptionHelpFormatter, |
| 71 | + ) |
52 | 72 | parser.set_defaults(tool_class=tool_cls) |
53 | 73 | tool_cls.add_parser(parser) |
54 | 74 |
|
| 75 | + def _load_selected_tool(self, argv: list[str]): |
| 76 | + if not argv: |
| 77 | + return |
| 78 | + |
| 79 | + if argv[0] not in self._tools or argv[0] in self._loaded_tools: |
| 80 | + return |
| 81 | + |
| 82 | + tool = self._tools[argv[0]] |
| 83 | + module = self._import_tool_module(tool) |
| 84 | + self._load_from_module(self._tools_parser, module, self._tool_parsers[tool.spec.name]) |
| 85 | + self._loaded_tools.add(tool.spec.name) |
| 86 | + |
| 87 | + def _import_tool_module(self, tool: RegisteredTool) -> types.ModuleType: |
| 88 | + if tool.extension_path is None: |
| 89 | + return importlib.import_module(tool.spec.module) |
| 90 | + |
| 91 | + module_path = tool.extension_path / f"{tool.spec.module.replace('.', '/')}.py" |
| 92 | + module_name = f"infuse_iot_custom_tools.{tool.spec.module}" |
| 93 | + spec = importlib.util.spec_from_file_location(module_name, module_path) |
| 94 | + if spec is None or spec.loader is None: |
| 95 | + raise ImportError(f"Failed to import custom tool module: {module_path}") |
| 96 | + |
| 97 | + module = importlib.util.module_from_spec(spec) |
| 98 | + spec.loader.exec_module(module) |
| 99 | + return module |
| 100 | + |
| 101 | + def _load_selected_completion_tool(self): |
| 102 | + if "_ARGCOMPLETE" not in os.environ: |
| 103 | + return |
| 104 | + |
| 105 | + comp_line = os.environ["COMP_LINE"] |
| 106 | + comp_point = int(os.environ["COMP_POINT"]) |
| 107 | + _, _, _, comp_words, _ = split_line(comp_line, comp_point) |
| 108 | + |
| 109 | + # Match argcomplete's own executable/module offset handling. |
| 110 | + start = int(os.environ["_ARGCOMPLETE"]) - 1 |
| 111 | + parser_words = comp_words[start:] |
| 112 | + if len(parser_words) > 1: |
| 113 | + self._load_selected_tool(parser_words[1:]) |
| 114 | + |
55 | 115 | def _load_tools(self, parser: argparse.ArgumentParser): |
56 | | - tools_parser = parser.add_subparsers(title="commands", metavar="<command>", required=True) |
| 116 | + self._tools_parser = parser.add_subparsers(title="commands", metavar="<command>", required=True) |
57 | 117 |
|
58 | | - # Iterate over local tools |
59 | | - for _, name, _ in pkgutil.walk_packages(infuse_iot.tools.__path__): |
60 | | - full_name = f"{infuse_iot.tools.__name__}.{name}" |
61 | | - module = importlib.import_module(full_name) |
62 | | - self._load_from_module(tools_parser, module) |
| 118 | + # Register local tools without importing their implementation modules. |
| 119 | + for tool in TOOLS: |
| 120 | + self._register_tool(tool) |
63 | 121 |
|
64 | 122 | # Load custom tools, if configured |
65 | 123 | if extension_tools := get_custom_tool_path(): |
66 | 124 | extension_path = pathlib.Path(extension_tools) |
67 | | - for _, name, _ in pkgutil.walk_packages([extension_tools]): |
68 | | - full_name = f"{infuse_iot.tools.__name__}.{name}" |
69 | | - full_path = str(extension_path / f"{name}.py") |
70 | | - spec = importlib.util.spec_from_file_location(full_name, full_path) |
71 | | - if spec is None or spec.loader is None: |
72 | | - continue |
73 | | - module = importlib.util.module_from_spec(spec) |
74 | | - try: |
75 | | - spec.loader.exec_module(module) |
76 | | - except Exception as e: |
77 | | - print(f"Failed to import '{name}': {str(e)}") |
78 | | - continue |
79 | | - if hasattr(module, "SubCommand"): |
80 | | - self._load_from_module(tools_parser, module) |
| 125 | + for tool in load_extension_tools(extension_path): |
| 126 | + self._register_tool(tool, extension_path) |
| 127 | + |
| 128 | + def _register_tool(self, tool: ToolSpec, extension_path: pathlib.Path | None = None): |
| 129 | + if tool.name in self._tools: |
| 130 | + raise ValueError(f"Tool already registered: {tool.name}") |
| 131 | + |
| 132 | + self._tools[tool.name] = RegisteredTool(tool, extension_path) |
| 133 | + self._tool_parsers[tool.name] = self._tools_parser.add_parser( |
| 134 | + tool.name, |
| 135 | + help=tool.help, |
| 136 | + description=tool.description, |
| 137 | + formatter_class=argparse.RawDescriptionHelpFormatter, |
| 138 | + ) |
81 | 139 |
|
82 | 140 |
|
83 | 141 | def main(argv=None): |
|
0 commit comments