cli-def 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- cli_def/__init__.py +16 -0
- cli_def/backend/__init__.py +2 -0
- cli_def/backend/argparse/__init__.py +10 -0
- cli_def/backend/argparse/argparse_builder.py +238 -0
- cli_def/backend/click/__init__.py +13 -0
- cli_def/backend/click/click_binder.py +46 -0
- cli_def/backend/click/click_builder.py +182 -0
- cli_def/backend/protocols.py +22 -0
- cli_def/demo/__init__.py +2 -0
- cli_def/demo/handlers.py +125 -0
- cli_def/demo/profiles/advanced.toml +39 -0
- cli_def/demo/profiles/beginner.toml +21 -0
- cli_def/models/__init__.py +17 -0
- cli_def/models/abstract_node.py +87 -0
- cli_def/models/argument_def.py +84 -0
- cli_def/models/cli_def.py +28 -0
- cli_def/models/command_def.py +49 -0
- cli_def/models/mult_def.py +81 -0
- cli_def/models/schema/cli_schema.py +24 -0
- cli_def/ops/__init__.py +16 -0
- cli_def/ops/dumper.py +216 -0
- cli_def/ops/loader.py +56 -0
- cli_def/ops/utils/__init__.py +3 -0
- cli_def/ops/utils/pretty_renderer.py +543 -0
- cli_def/ops/utils/renderer.py +199 -0
- cli_def/ops/utils/renderer_ops.py +169 -0
- cli_def/parsers/__init__.py +10 -0
- cli_def/parsers/parser.py +101 -0
- cli_def/resources/cli_def.toml +126 -0
- cli_def/runtime/__init__.py +22 -0
- cli_def/runtime/_internal/__init__.py +2 -0
- cli_def/runtime/_internal/scan_runner.py +28 -0
- cli_def/runtime/context.py +12 -0
- cli_def/runtime/dispatcher.py +197 -0
- cli_def/runtime/event.py +35 -0
- cli_def/runtime/handler_support.py +75 -0
- cli_def/runtime/result.py +117 -0
- cli_def/runtime/runner.py +178 -0
- cli_def/runtime/scanner.py +143 -0
- cli_def/runtime/session.py +286 -0
- cli_def/runtime/utils.py +54 -0
- cli_def/script/__init__.py +2 -0
- cli_def/script/common.py +29 -0
- cli_def/script/handlers/__init__.py +14 -0
- cli_def/script/handlers/dummy.py +43 -0
- cli_def/script/handlers/dummy2.py +22 -0
- cli_def/script/handlers/dump.py +50 -0
- cli_def/script/handlers/repl.py +70 -0
- cli_def/script/handlers/run.py +70 -0
- cli_def/script/handlers/scan.py +179 -0
- cli_def/script/handlers/search.py +116 -0
- cli_def/script/main.py +32 -0
- cli_def-0.1.0.dist-info/METADATA +400 -0
- cli_def-0.1.0.dist-info/RECORD +58 -0
- cli_def-0.1.0.dist-info/WHEEL +5 -0
- cli_def-0.1.0.dist-info/entry_points.txt +2 -0
- cli_def-0.1.0.dist-info/licenses/LICENSE +21 -0
- cli_def-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
# cli_def/runtime/dispatcher.py
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
from typing import Callable, Mapping, Any, Sequence, Iterable
|
|
4
|
+
import importlib
|
|
5
|
+
import argparse
|
|
6
|
+
import logging
|
|
7
|
+
|
|
8
|
+
from .event import CliEvent
|
|
9
|
+
from ..models import (
|
|
10
|
+
CliDef,
|
|
11
|
+
ExecutableNode,
|
|
12
|
+
CommandDef,
|
|
13
|
+
MultDef,
|
|
14
|
+
)
|
|
15
|
+
|
|
16
|
+
from .handler_support import get_registered_handler
|
|
17
|
+
from .context import CliRuntimeContext
|
|
18
|
+
from .result import CliHandlerResult
|
|
19
|
+
|
|
20
|
+
# --------------------------------------------------------------------------------
|
|
21
|
+
# Dispatcher class
|
|
22
|
+
# --------------------------------------------------------------------------------
|
|
23
|
+
class CliDispatcher:
|
|
24
|
+
|
|
25
|
+
def __init__(self, cli_def: CliDef, fallback_handler: Callable[[CliEvent], CliHandlerResult|None]|Any = None):
|
|
26
|
+
self.cli_def : CliDef = cli_def
|
|
27
|
+
self.fallback_handler : Callable[[CliEvent], Any] = fallback_handler or type(self)._default_fallback_handler
|
|
28
|
+
self._handler_cache: dict[str, Callable] = {}
|
|
29
|
+
self._pre_load_entrypoints()
|
|
30
|
+
|
|
31
|
+
@staticmethod
|
|
32
|
+
def _default_fallback_handler(event: CliEvent):
|
|
33
|
+
print("[fallback handler of Dispatcher]")
|
|
34
|
+
print(" PATH:", event.path)
|
|
35
|
+
print(" PARAMS:", event.params)
|
|
36
|
+
if event.extra_args:
|
|
37
|
+
print(" EXTRA:", event.extra_args)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _pre_load_entrypoints(self):
|
|
41
|
+
# executables = self.cli_def.select_all(
|
|
42
|
+
# lambda node: isinstance(node, ExecutableNode)
|
|
43
|
+
# and node.entrypoint is not None
|
|
44
|
+
# )
|
|
45
|
+
entrypoints = {
|
|
46
|
+
node.entrypoint for node in self.cli_def.iter_all_nodes()
|
|
47
|
+
if isinstance(node, ExecutableNode) and node.entrypoint is not None
|
|
48
|
+
}
|
|
49
|
+
for entrypoint in entrypoints:
|
|
50
|
+
self._resolve_handler_entrypoint(entrypoint)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def dispatch(
|
|
54
|
+
self,
|
|
55
|
+
args: argparse.Namespace,
|
|
56
|
+
extra_args: Sequence[str]|None = None,
|
|
57
|
+
ctx: CliRuntimeContext|None = None,
|
|
58
|
+
) -> Any: # args: argparse.Namespace
|
|
59
|
+
event = self._build_event(args, extra_args=extra_args, ctx=ctx)
|
|
60
|
+
handler = self._resolve_handler(event.command) or self.fallback_handler
|
|
61
|
+
result = handler(event)
|
|
62
|
+
return self.normalize_result(result, event)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
# called via click binder
|
|
66
|
+
def _dispatch(
|
|
67
|
+
self,
|
|
68
|
+
defpath: str,
|
|
69
|
+
kwargs: dict[str, Any],
|
|
70
|
+
extra_args: Sequence[str]|None = None,
|
|
71
|
+
ctx: CliRuntimeContext|None = None,
|
|
72
|
+
) -> Any:
|
|
73
|
+
logging.debug(f"@@@ Dispatcher._dispatcher called {defpath}")
|
|
74
|
+
command = self.cli_def.find(defpath)
|
|
75
|
+
if command is None:
|
|
76
|
+
raise RuntimeError(f"Command not found from defpath: [{defpath}]")
|
|
77
|
+
assert isinstance(command, CommandDef)
|
|
78
|
+
params = self._normalize(command, dict(kwargs))
|
|
79
|
+
event = CliEvent.create(
|
|
80
|
+
path=defpath,
|
|
81
|
+
command=command,
|
|
82
|
+
params=params,
|
|
83
|
+
event_source=self,
|
|
84
|
+
extra_args=extra_args,
|
|
85
|
+
ctx=ctx,
|
|
86
|
+
)
|
|
87
|
+
handler = self._resolve_handler(event.command) or self.fallback_handler
|
|
88
|
+
result = handler(event)
|
|
89
|
+
return self.normalize_result(result, event)
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def _build_event(
|
|
93
|
+
self,
|
|
94
|
+
args: argparse.Namespace,
|
|
95
|
+
extra_args: Sequence[str]|None = None,
|
|
96
|
+
ctx: CliRuntimeContext|None = None,
|
|
97
|
+
):
|
|
98
|
+
command = getattr(args, "_command", None)
|
|
99
|
+
path = getattr(args, "_path", None)
|
|
100
|
+
|
|
101
|
+
if command is None or path is None:
|
|
102
|
+
raise RuntimeError("No command metadata found")
|
|
103
|
+
|
|
104
|
+
params = {
|
|
105
|
+
k: v for k, v in vars(args).items()
|
|
106
|
+
if not k.startswith("_") and (
|
|
107
|
+
k not in ("_path", "_command", "command"))
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
params = self._normalize(command, params)
|
|
111
|
+
|
|
112
|
+
event = CliEvent(
|
|
113
|
+
path=path,
|
|
114
|
+
command=command,
|
|
115
|
+
params=params,
|
|
116
|
+
event_source=self,
|
|
117
|
+
extra_args=list(extra_args) if extra_args else None,
|
|
118
|
+
ctx=ctx,
|
|
119
|
+
)
|
|
120
|
+
|
|
121
|
+
return event
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def _normalize(self, command: CommandDef, params: Mapping[str, Any]):
|
|
125
|
+
result = {}
|
|
126
|
+
|
|
127
|
+
# key → ArgumentDef のマップ作る
|
|
128
|
+
arg_map = {arg.key: arg for arg in command.arguments}
|
|
129
|
+
|
|
130
|
+
for k, v in params.items():
|
|
131
|
+
arg = arg_map.get(k)
|
|
132
|
+
|
|
133
|
+
if arg is None:
|
|
134
|
+
result[k] = v
|
|
135
|
+
continue
|
|
136
|
+
|
|
137
|
+
mult: MultDef = arg.mult
|
|
138
|
+
|
|
139
|
+
# unbox if mult definition is (1,1)
|
|
140
|
+
if mult.is_fixed and mult.lower == 1:
|
|
141
|
+
if isinstance(v, list):
|
|
142
|
+
result[k] = v[0] if v else None
|
|
143
|
+
else:
|
|
144
|
+
result[k] = v
|
|
145
|
+
else:
|
|
146
|
+
result[k] = v
|
|
147
|
+
|
|
148
|
+
return result
|
|
149
|
+
|
|
150
|
+
def _resolve_handler(self, command: CommandDef):
|
|
151
|
+
path = command.defpath # "MyCLI/command1"
|
|
152
|
+
|
|
153
|
+
handler = get_registered_handler(path)
|
|
154
|
+
if handler:
|
|
155
|
+
logging.debug(f"handler found in registry: {path}")
|
|
156
|
+
return handler
|
|
157
|
+
|
|
158
|
+
if command.entrypoint:
|
|
159
|
+
return self._resolve_handler_entrypoint(command.entrypoint)
|
|
160
|
+
|
|
161
|
+
logging.debug(f"handler NOT found {path} -> fallback")
|
|
162
|
+
return self.fallback_handler
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def _resolve_handler_entrypoint(self, handler_str: str) -> Callable | None:
|
|
166
|
+
if handler_str is None:
|
|
167
|
+
return None
|
|
168
|
+
|
|
169
|
+
# at first find in cache
|
|
170
|
+
if handler_str in self._handler_cache:
|
|
171
|
+
return self._handler_cache[handler_str]
|
|
172
|
+
|
|
173
|
+
module_path, func_name = handler_str.split(":")
|
|
174
|
+
try:
|
|
175
|
+
module = importlib.import_module(module_path)
|
|
176
|
+
except ModuleNotFoundError:
|
|
177
|
+
raise RuntimeError(f"Failed to load handler: {handler_str}")
|
|
178
|
+
|
|
179
|
+
func = getattr(module, func_name)
|
|
180
|
+
if func is None:
|
|
181
|
+
raise RuntimeError(f"Failed to load handler: {handler_str}")
|
|
182
|
+
|
|
183
|
+
self._handler_cache[handler_str] = func
|
|
184
|
+
return func
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def normalize_result(self, result: Any, event: CliEvent) -> CliHandlerResult:
|
|
188
|
+
if result is None:
|
|
189
|
+
return CliHandlerResult(defpath=event.command.defpath)
|
|
190
|
+
|
|
191
|
+
if isinstance(result, CliHandlerResult):
|
|
192
|
+
return result
|
|
193
|
+
|
|
194
|
+
return CliHandlerResult(
|
|
195
|
+
defpath=event.command.defpath,
|
|
196
|
+
data=result
|
|
197
|
+
)
|
cli_def/runtime/event.py
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
# cli_def/runtime/event.py
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
from typing import Any, Sequence
|
|
5
|
+
from ..models.command_def import CommandDef
|
|
6
|
+
|
|
7
|
+
from .context import CliRuntimeContext
|
|
8
|
+
|
|
9
|
+
# --------------------------------------------------------------------------------
|
|
10
|
+
# CliEvent class
|
|
11
|
+
# --------------------------------------------------------------------------------
|
|
12
|
+
@dataclass
|
|
13
|
+
class CliEvent:
|
|
14
|
+
path: list[str]
|
|
15
|
+
command: CommandDef
|
|
16
|
+
params: dict[str, Any]
|
|
17
|
+
event_source: Any|None = None
|
|
18
|
+
extra_args: Sequence[str]|None = None
|
|
19
|
+
ctx: CliRuntimeContext|None = None
|
|
20
|
+
|
|
21
|
+
@property
|
|
22
|
+
def name(self) -> str:
|
|
23
|
+
return self.path[-1]
|
|
24
|
+
|
|
25
|
+
def __post_init__(self):
|
|
26
|
+
# fix path from defpath
|
|
27
|
+
if isinstance(self.path, str):
|
|
28
|
+
self.path = [p for p in self.path.split("/") if len(p)]
|
|
29
|
+
|
|
30
|
+
@classmethod
|
|
31
|
+
def create(cls, *args, **kwargs) -> CliEvent:
|
|
32
|
+
return cls(
|
|
33
|
+
*args,
|
|
34
|
+
**kwargs
|
|
35
|
+
)
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
# cli_def/runtime/handlers.py
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from typing import Callable, Iterable, Any, Mapping, Sequence
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
|
|
7
|
+
_EARLY_BINDING_HANDLER_REGISTRY: dict[str, Callable] = {}
|
|
8
|
+
_ALL_HANDLERS_CATALOG: dict[str, list[CliHandlerMeta]] = {}
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
@dataclass
|
|
12
|
+
class CliHandlerMeta:
|
|
13
|
+
path: str
|
|
14
|
+
module: str
|
|
15
|
+
name: str
|
|
16
|
+
tags: set[str]|None = None
|
|
17
|
+
description: str|None = None
|
|
18
|
+
late_binding: bool = False
|
|
19
|
+
|
|
20
|
+
@property
|
|
21
|
+
def entrypoint(self) -> str:
|
|
22
|
+
return f"{self.module}:{self.name}"
|
|
23
|
+
|
|
24
|
+
def to_dict(self) -> dict[str, Any]:
|
|
25
|
+
return {
|
|
26
|
+
"path": self.path,
|
|
27
|
+
"module": self.module,
|
|
28
|
+
"name": self.name,
|
|
29
|
+
"tags": list(self.tags) if self.tags else [],
|
|
30
|
+
"description": self.description,
|
|
31
|
+
"late_binding": self.late_binding,
|
|
32
|
+
"entrypoint": self.entrypoint,
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def cli_def_handler(
|
|
37
|
+
path: str,
|
|
38
|
+
*,
|
|
39
|
+
late_binding: bool = False,
|
|
40
|
+
tags: Iterable[str]|None = None,
|
|
41
|
+
description: str|None = None,
|
|
42
|
+
) -> Callable[[Callable], Callable]:
|
|
43
|
+
|
|
44
|
+
def decorator(func: Callable):
|
|
45
|
+
meta = CliHandlerMeta(
|
|
46
|
+
path=path,
|
|
47
|
+
module=func.__module__,
|
|
48
|
+
name=func.__name__,
|
|
49
|
+
tags=set(tags) if tags else None,
|
|
50
|
+
description=description,
|
|
51
|
+
late_binding=late_binding,
|
|
52
|
+
)
|
|
53
|
+
_ALL_HANDLERS_CATALOG.setdefault(path, [])
|
|
54
|
+
_ALL_HANDLERS_CATALOG[path].append(meta)
|
|
55
|
+
if not late_binding:
|
|
56
|
+
_EARLY_BINDING_HANDLER_REGISTRY[path] = func
|
|
57
|
+
return func
|
|
58
|
+
return decorator
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def get_registered_handler(path: str) -> Callable | None:
|
|
62
|
+
return _EARLY_BINDING_HANDLER_REGISTRY.get(path)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def clear_registry():
|
|
66
|
+
_EARLY_BINDING_HANDLER_REGISTRY.clear()
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def get_all_handlers_catalog() -> Mapping[str, Sequence[CliHandlerMeta]]:
|
|
70
|
+
return _ALL_HANDLERS_CATALOG
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def clear_all_handlers_catalog():
|
|
74
|
+
_ALL_HANDLERS_CATALOG.clear()
|
|
75
|
+
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
# cli_def/runtime/result.py
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from enum import Enum, auto
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from typing import Any, Optional
|
|
7
|
+
|
|
8
|
+
from .event import CliEvent
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
@dataclass
|
|
12
|
+
class CliResult:
|
|
13
|
+
results: list[CliHandlerResult]
|
|
14
|
+
exit_code: int = 0
|
|
15
|
+
|
|
16
|
+
def all_data(self) -> list[Any]:
|
|
17
|
+
return [
|
|
18
|
+
r.to_dict() if r else None
|
|
19
|
+
for r in self.results
|
|
20
|
+
]
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class CliHandlerResultKind(Enum):
|
|
24
|
+
OK = auto()
|
|
25
|
+
FAILED = auto()
|
|
26
|
+
|
|
27
|
+
def __str__(self) -> str:
|
|
28
|
+
return self.name
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
@dataclass
|
|
32
|
+
class CliHandlerResult:
|
|
33
|
+
defpath: str
|
|
34
|
+
kind: CliHandlerResultKind = CliHandlerResultKind.OK
|
|
35
|
+
data: Any = None
|
|
36
|
+
message: Optional[str] = None
|
|
37
|
+
|
|
38
|
+
@classmethod
|
|
39
|
+
def make_result(cls, event: CliEvent, message: str|None = None, data: Any = None, kind: CliHandlerResultKind = CliHandlerResultKind.OK) -> "CliHandlerResult":
|
|
40
|
+
return cls(
|
|
41
|
+
defpath=event.command.defpath,
|
|
42
|
+
kind=kind,
|
|
43
|
+
data=data,
|
|
44
|
+
message=message
|
|
45
|
+
)
|
|
46
|
+
|
|
47
|
+
@classmethod
|
|
48
|
+
def make_error(cls, event: CliEvent, message: str|None = None, data: Any = None) -> "CliHandlerResult":
|
|
49
|
+
return cls(
|
|
50
|
+
defpath=event.command.defpath,
|
|
51
|
+
kind=CliHandlerResultKind.FAILED,
|
|
52
|
+
data=data,
|
|
53
|
+
message=message
|
|
54
|
+
)
|
|
55
|
+
|
|
56
|
+
def to_dict(self) -> dict[str, Any]:
|
|
57
|
+
return {
|
|
58
|
+
"defpath": self.defpath,
|
|
59
|
+
"kind": str(self.kind),
|
|
60
|
+
"data": self.data,
|
|
61
|
+
"message": self.message,
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
class ResultStore:
|
|
66
|
+
def __init__(self):
|
|
67
|
+
self._results: list[CliHandlerResult] = []
|
|
68
|
+
|
|
69
|
+
def add(self, result):
|
|
70
|
+
self._results.append(result)
|
|
71
|
+
|
|
72
|
+
def last(self):
|
|
73
|
+
return self._results[-1] if self._results else None
|
|
74
|
+
|
|
75
|
+
def get(self, index):
|
|
76
|
+
return self._results[index]
|
|
77
|
+
|
|
78
|
+
def all(self):
|
|
79
|
+
return list(self._results)
|
|
80
|
+
|
|
81
|
+
def len(self) -> int:
|
|
82
|
+
return len(self._results)
|
|
83
|
+
|
|
84
|
+
def all_data(self) -> list[Any]:
|
|
85
|
+
return [
|
|
86
|
+
r.to_dict() for r in self._results
|
|
87
|
+
]
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
# view object used in repl
|
|
92
|
+
class ResultView:
|
|
93
|
+
def __init__(self, result: CliHandlerResult):
|
|
94
|
+
self._r = result
|
|
95
|
+
|
|
96
|
+
def __getitem__(self, key):
|
|
97
|
+
return self._r.data[key]
|
|
98
|
+
|
|
99
|
+
def __repr__(self):
|
|
100
|
+
return repr(self._r.data)
|
|
101
|
+
|
|
102
|
+
def __len__(self):
|
|
103
|
+
data = self._r.data
|
|
104
|
+
return len(data)
|
|
105
|
+
|
|
106
|
+
def __bool__(self):
|
|
107
|
+
data = self._r.data
|
|
108
|
+
return bool(data)
|
|
109
|
+
|
|
110
|
+
def __iter__(self):
|
|
111
|
+
data = self._r.data
|
|
112
|
+
return iter(data)
|
|
113
|
+
|
|
114
|
+
def __contains__(self, item):
|
|
115
|
+
data = self._r.data
|
|
116
|
+
return item in data
|
|
117
|
+
|
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
# cli_def/runtime/runner.py
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
from typing import Sequence, Iterable, Any, Callable, TYPE_CHECKING, Tuple
|
|
4
|
+
|
|
5
|
+
import sys
|
|
6
|
+
import argparse
|
|
7
|
+
import logging
|
|
8
|
+
|
|
9
|
+
from ..models import CliDef
|
|
10
|
+
from ..backend.argparse import ArgparseBuilder
|
|
11
|
+
from ..ops import CliDefDumper
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
from .dispatcher import CliDispatcher
|
|
15
|
+
from .context import CliRuntimeContext
|
|
16
|
+
from .event import CliEvent
|
|
17
|
+
from .result import (
|
|
18
|
+
CliHandlerResult,
|
|
19
|
+
CliHandlerResultKind,
|
|
20
|
+
CliResult,
|
|
21
|
+
)
|
|
22
|
+
from .utils import (
|
|
23
|
+
make_runtime_context,
|
|
24
|
+
setup_logging,
|
|
25
|
+
)
|
|
26
|
+
if TYPE_CHECKING:
|
|
27
|
+
from .session import CliSession
|
|
28
|
+
|
|
29
|
+
class CliRunner:
|
|
30
|
+
|
|
31
|
+
def __init__(
|
|
32
|
+
self,
|
|
33
|
+
cli_def: CliDef,
|
|
34
|
+
fallback_handler: Callable[[CliEvent], CliHandlerResult|None]|None = None,
|
|
35
|
+
*,
|
|
36
|
+
default_backend: str="argparse",
|
|
37
|
+
default_ctx: CliRuntimeContext|None = None,
|
|
38
|
+
session: CliSession|None = None,
|
|
39
|
+
):
|
|
40
|
+
self.cli_def = cli_def
|
|
41
|
+
self.fallback_handler = fallback_handler
|
|
42
|
+
self.default_backend = default_backend
|
|
43
|
+
self.backend: str|None = None
|
|
44
|
+
self.default_ctx = default_ctx
|
|
45
|
+
self.session = session
|
|
46
|
+
|
|
47
|
+
self.ctx: CliRuntimeContext|None = None
|
|
48
|
+
self.builder: ArgparseBuilder = ArgparseBuilder()
|
|
49
|
+
self.dispatcher: CliDispatcher = CliDispatcher(self.cli_def, fallback_handler=self.fallback_handler)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def run(self, argv: Iterable[str]| str | None = None) -> CliResult:
|
|
53
|
+
argv = self._normalize_argv(argv)
|
|
54
|
+
|
|
55
|
+
early_args, remaining = self._early_parse(argv)
|
|
56
|
+
self.ctx = self._make_context(early_args)
|
|
57
|
+
|
|
58
|
+
if self._should_show_help(argv):
|
|
59
|
+
self._show_help()
|
|
60
|
+
return CliResult([], exit_code=1)
|
|
61
|
+
|
|
62
|
+
self._setup_runtime()
|
|
63
|
+
|
|
64
|
+
self.backend = self._determine_backend()
|
|
65
|
+
|
|
66
|
+
handler_result = self._execute_backend(remaining)
|
|
67
|
+
#print(f"@@@ hander_result = {type(handler_result)}, datatype={type(handler_result.data)}")
|
|
68
|
+
if self.session:
|
|
69
|
+
self.session.result_store.add(handler_result)
|
|
70
|
+
return self._normalize_result([handler_result])
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def compute_exit_code(self, results: Iterable[CliHandlerResult]):
|
|
74
|
+
for r in results:
|
|
75
|
+
if r.kind == CliHandlerResultKind.FAILED:
|
|
76
|
+
return 1
|
|
77
|
+
return 0
|
|
78
|
+
|
|
79
|
+
def _normalize_argv(self, argv: Iterable[str]|None) -> list[str]:
|
|
80
|
+
if argv is None:
|
|
81
|
+
argv = sys.argv[1:]
|
|
82
|
+
|
|
83
|
+
if isinstance(argv, str):
|
|
84
|
+
import shlex
|
|
85
|
+
argv = shlex.split(argv)
|
|
86
|
+
|
|
87
|
+
return list(argv)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def _early_parse(self, argv: Sequence[str]) -> Tuple[argparse.Namespace|None, Sequence[str]]:
|
|
91
|
+
parser = self._build_early_parser()
|
|
92
|
+
if parser:
|
|
93
|
+
return parser.parse_known_args(argv)
|
|
94
|
+
return None, argv
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _build_early_parser(self) -> argparse.ArgumentParser|None:
|
|
98
|
+
early_parser = self.builder.build_early_argparse(self.cli_def)
|
|
99
|
+
return early_parser
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def _make_context(self, args: argparse.Namespace|None=None):
|
|
103
|
+
return make_runtime_context(args, self.default_ctx)
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _setup_runtime(self):
|
|
107
|
+
assert self.ctx is not None
|
|
108
|
+
setup_logging(self.ctx)
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def _should_show_help(self, argv: Sequence[str]):
|
|
112
|
+
return "--help" in argv or "-h" in argv
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def show_help(self):
|
|
116
|
+
return self._show_help()
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def _show_help(self):
|
|
120
|
+
CliDefDumper.dump_pretty(self.cli_def, as_help=True)
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def _determine_backend(self) -> str:
|
|
124
|
+
assert self.ctx is not None
|
|
125
|
+
backend = self.ctx.backend or self.default_backend
|
|
126
|
+
return backend or "argparse"
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def _execute_backend(self, argv: Sequence[str]):
|
|
130
|
+
if self.backend == "click":
|
|
131
|
+
logging.info("[click] backend")
|
|
132
|
+
return self._execute_click(argv)
|
|
133
|
+
|
|
134
|
+
logging.info("[argparse] backend")
|
|
135
|
+
return self._execute_argparse(argv)
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def _execute_argparse(self, argv: Sequence[str]) -> Any:
|
|
139
|
+
builder = self.builder
|
|
140
|
+
if builder is None:
|
|
141
|
+
builder = ArgparseBuilder()
|
|
142
|
+
parser = builder.build(self.cli_def)
|
|
143
|
+
args, remaining = parser.parse_known_args(args=argv)
|
|
144
|
+
return self.dispatcher.dispatch(args, remaining, ctx=self.ctx)
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def _execute_click(self, argv: Sequence[str]) -> Any:
|
|
148
|
+
import click
|
|
149
|
+
from ..backend.click import ClickBuilder, ClickBinder
|
|
150
|
+
builder = ClickBuilder()
|
|
151
|
+
root = builder.build(self.cli_def)
|
|
152
|
+
|
|
153
|
+
binder = ClickBinder(dispatcher=self.dispatcher, ctx=self.ctx)
|
|
154
|
+
binder.bind(builder.defpath_mapping)
|
|
155
|
+
|
|
156
|
+
try:
|
|
157
|
+
result = root(
|
|
158
|
+
args=list(argv) if argv is not None else None,
|
|
159
|
+
standalone_mode=False,
|
|
160
|
+
)
|
|
161
|
+
|
|
162
|
+
return result
|
|
163
|
+
|
|
164
|
+
except click.exceptions.NoArgsIsHelpError as e:
|
|
165
|
+
click.echo(e.ctx.get_help())
|
|
166
|
+
return 0
|
|
167
|
+
|
|
168
|
+
except click.exceptions.ClickException as e:
|
|
169
|
+
e.show()
|
|
170
|
+
return e.exit_code
|
|
171
|
+
|
|
172
|
+
def _normalize_result(self, results: Iterable[CliHandlerResult]) -> CliResult:
|
|
173
|
+
exit_code = self.compute_exit_code(results)
|
|
174
|
+
result = CliResult(
|
|
175
|
+
exit_code=exit_code,
|
|
176
|
+
results=list(results)
|
|
177
|
+
)
|
|
178
|
+
return result
|