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,143 @@
|
|
|
1
|
+
# cli_def/runtime/scanner.py
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from typing import Mapping, Any, Sequence
|
|
5
|
+
from dataclasses import dataclass, field
|
|
6
|
+
|
|
7
|
+
import pkgutil
|
|
8
|
+
import importlib
|
|
9
|
+
import importlib.util
|
|
10
|
+
import logging
|
|
11
|
+
import subprocess
|
|
12
|
+
import sys
|
|
13
|
+
import os
|
|
14
|
+
import json
|
|
15
|
+
import copy
|
|
16
|
+
|
|
17
|
+
from .handler_support import (
|
|
18
|
+
CliHandlerMeta,
|
|
19
|
+
get_all_handlers_catalog,
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
@dataclass
|
|
23
|
+
class CliHandlerScannerResult:
|
|
24
|
+
scan_coverage: dict[str, Any]|None = None
|
|
25
|
+
catalog: Mapping[str, Sequence[CliHandlerMeta]]|None = None
|
|
26
|
+
_catalog_digest: dict[str, Sequence[Any]]|None = None
|
|
27
|
+
|
|
28
|
+
def to_digest(self) -> dict[str, Any]:
|
|
29
|
+
if self._catalog_digest is None:
|
|
30
|
+
digest = {}
|
|
31
|
+
if self.catalog:
|
|
32
|
+
for key, lst in self.catalog.items():
|
|
33
|
+
digest[key] = [meta.to_dict() for meta in lst]
|
|
34
|
+
self._catalog_digest = digest
|
|
35
|
+
|
|
36
|
+
return {
|
|
37
|
+
"scan_coverage": self.scan_coverage,
|
|
38
|
+
"catalog_digest": self._catalog_digest
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
@classmethod
|
|
42
|
+
def from_digest(cls, digest: Mapping[str, Any]) -> CliHandlerScannerResult:
|
|
43
|
+
return cls(
|
|
44
|
+
scan_coverage = digest.get("scan_coverage"),
|
|
45
|
+
catalog = None,
|
|
46
|
+
_catalog_digest = digest.get("catalog_digest")
|
|
47
|
+
)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class CliHandlerScanner:
|
|
52
|
+
|
|
53
|
+
def scan(self,
|
|
54
|
+
package_name: str,
|
|
55
|
+
*,
|
|
56
|
+
no_subprocess: bool,
|
|
57
|
+
recursive: bool,
|
|
58
|
+
) -> CliHandlerScannerResult|None:
|
|
59
|
+
|
|
60
|
+
#print(f"package_name: {package_name}")
|
|
61
|
+
if not self.can_import(package_name):
|
|
62
|
+
print(f"[ERROR] package not found: {package_name}")
|
|
63
|
+
return None
|
|
64
|
+
|
|
65
|
+
if no_subprocess:
|
|
66
|
+
logging.info("[scan without subprocess]")
|
|
67
|
+
scan_coverage = self.import_modules(package_name, recursive)
|
|
68
|
+
catalog = get_all_handlers_catalog()
|
|
69
|
+
return CliHandlerScannerResult(
|
|
70
|
+
scan_coverage=dict(scan_coverage),
|
|
71
|
+
catalog=catalog
|
|
72
|
+
)
|
|
73
|
+
|
|
74
|
+
# use subprocess
|
|
75
|
+
logging.info("[scan with subprocess]")
|
|
76
|
+
proc_result = subprocess.run([
|
|
77
|
+
sys.executable,
|
|
78
|
+
"-m",
|
|
79
|
+
"cli_def.runtime._internal.scan_runner",
|
|
80
|
+
package_name,
|
|
81
|
+
] + (
|
|
82
|
+
["--recursive"] if recursive else []
|
|
83
|
+
)
|
|
84
|
+
, capture_output=True,
|
|
85
|
+
text=True,
|
|
86
|
+
env=os.environ.copy()
|
|
87
|
+
)
|
|
88
|
+
if proc_result.returncode != 0:
|
|
89
|
+
logging.warning("scanner subprocess unsucceeded")
|
|
90
|
+
return None
|
|
91
|
+
|
|
92
|
+
logging.debug(f"@@@ result.stdout: {proc_result.stdout}")
|
|
93
|
+
digest = json.loads(proc_result.stdout)
|
|
94
|
+
|
|
95
|
+
if not isinstance(digest, Mapping):
|
|
96
|
+
logging.warning("scanner subprocess returns incorrect format of value")
|
|
97
|
+
return None
|
|
98
|
+
|
|
99
|
+
return CliHandlerScannerResult.from_digest(digest)
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def can_import(self, module_name: str) -> bool:
|
|
104
|
+
try:
|
|
105
|
+
spec = importlib.util.find_spec(module_name)
|
|
106
|
+
return spec is not None
|
|
107
|
+
except ModuleNotFoundError:
|
|
108
|
+
return False
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def import_modules(self, package: str, recursive: bool) -> Mapping[str, bool]:
|
|
112
|
+
result = {}
|
|
113
|
+
pkg_or_module = None
|
|
114
|
+
try:
|
|
115
|
+
pkg_or_module = importlib.import_module(package)
|
|
116
|
+
result[package] = True
|
|
117
|
+
except ImportError:
|
|
118
|
+
result[package] = False
|
|
119
|
+
|
|
120
|
+
logging.debug(f"@import_modules() type({package}) = {type(pkg_or_module)}")
|
|
121
|
+
|
|
122
|
+
if pkg_or_module and hasattr(pkg_or_module, "__path__"):
|
|
123
|
+
pkg = pkg_or_module
|
|
124
|
+
|
|
125
|
+
if not recursive:
|
|
126
|
+
for _, name, ispkg in pkgutil.iter_modules(pkg.__path__):
|
|
127
|
+
pkg = f"{package}.{name}"
|
|
128
|
+
try:
|
|
129
|
+
importlib.import_module(f"{package}.{name}")
|
|
130
|
+
result[pkg] = True
|
|
131
|
+
except ImportError:
|
|
132
|
+
result[pkg] = False
|
|
133
|
+
else:
|
|
134
|
+
for _, name, _ in pkgutil.walk_packages(pkg.__path__, package + "."):
|
|
135
|
+
try:
|
|
136
|
+
importlib.import_module(name)
|
|
137
|
+
result[name] = True
|
|
138
|
+
except ImportError:
|
|
139
|
+
result[name] = False
|
|
140
|
+
return result
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
|
|
@@ -0,0 +1,286 @@
|
|
|
1
|
+
# cli_def/runtime/session.py
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
from typing import Optional, Callable, Any, Protocol
|
|
4
|
+
from dataclasses import dataclass
|
|
5
|
+
|
|
6
|
+
import logging
|
|
7
|
+
import pprint
|
|
8
|
+
try:
|
|
9
|
+
import readline
|
|
10
|
+
except ImportError:
|
|
11
|
+
pass
|
|
12
|
+
|
|
13
|
+
from ..models import CliDef
|
|
14
|
+
from ..parsers import CliDefParser
|
|
15
|
+
from .runner import CliRunner
|
|
16
|
+
from .context import CliRuntimeContext
|
|
17
|
+
from .result import ResultStore, ResultView, CliHandlerResult
|
|
18
|
+
from .event import CliEvent
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
# --------------------------------------------------------------------------------
|
|
22
|
+
# CliSession protocol
|
|
23
|
+
# --------------------------------------------------------------------------------
|
|
24
|
+
class CliSessionProtocol(Protocol):
|
|
25
|
+
def repl(self):
|
|
26
|
+
...
|
|
27
|
+
|
|
28
|
+
def push_repl_mode(self, name: str, mode_handler: Callable[[CliSessionProtocol, str], bool], prompt: str):
|
|
29
|
+
...
|
|
30
|
+
|
|
31
|
+
def pop_repl_mode(self) -> bool:
|
|
32
|
+
...
|
|
33
|
+
|
|
34
|
+
@property
|
|
35
|
+
def result_store(self) -> ResultStore:
|
|
36
|
+
...
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
# --------------------------------------------------------------------------------
|
|
40
|
+
# Misc dataclasses
|
|
41
|
+
# --------------------------------------------------------------------------------
|
|
42
|
+
@dataclass
|
|
43
|
+
class ReplModeRecord:
|
|
44
|
+
name: str
|
|
45
|
+
mode_handler: Callable[[CliSession, str], bool]
|
|
46
|
+
prompt: str|None
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
# --------------------------------------------------------------------------------
|
|
50
|
+
# CliSession class
|
|
51
|
+
# --------------------------------------------------------------------------------
|
|
52
|
+
class CliSession(CliSessionProtocol):
|
|
53
|
+
_DEFAULT_PROMPT="cli-def> "
|
|
54
|
+
|
|
55
|
+
SAFE_BUILTINS = {
|
|
56
|
+
"len": len,
|
|
57
|
+
"sorted": sorted,
|
|
58
|
+
"min": min,
|
|
59
|
+
"max": max,
|
|
60
|
+
"sum": sum,
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
SAFE_GLOBALS = {
|
|
64
|
+
"__builtins__": SAFE_BUILTINS
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def __init__(
|
|
69
|
+
self,
|
|
70
|
+
cli_def: CliDef,
|
|
71
|
+
fallback_handler: Callable[[CliEvent], CliHandlerResult|None]|None = None,
|
|
72
|
+
profile: str|None = None,
|
|
73
|
+
cli_def_file: str|None = None,
|
|
74
|
+
*,
|
|
75
|
+
ctx: CliRuntimeContext|None = None,
|
|
76
|
+
):
|
|
77
|
+
self.cli_def: CliDef = cli_def
|
|
78
|
+
self.fallback_handler: Callable[[CliEvent], CliHandlerResult|None]|None = fallback_handler
|
|
79
|
+
self.profile = profile
|
|
80
|
+
self._cli_def_file = cli_def_file
|
|
81
|
+
self.runtime_ctx = ctx
|
|
82
|
+
|
|
83
|
+
self._result_store = ResultStore()
|
|
84
|
+
|
|
85
|
+
# self._prompt_stack: list[str] = []
|
|
86
|
+
# self._repl_stack: list[Callable[[str], Any]] = []
|
|
87
|
+
self._mode_stack: list[ReplModeRecord] = []
|
|
88
|
+
|
|
89
|
+
self._build_runtime()
|
|
90
|
+
|
|
91
|
+
# --- lifecycle -------------------------------------------------
|
|
92
|
+
|
|
93
|
+
def _build_runtime(self):
|
|
94
|
+
self.runner = CliRunner(
|
|
95
|
+
self.cli_def,
|
|
96
|
+
fallback_handler=self.fallback_handler,
|
|
97
|
+
session=self,
|
|
98
|
+
)
|
|
99
|
+
|
|
100
|
+
def _make_prog_name(self) -> str:
|
|
101
|
+
if self.profile:
|
|
102
|
+
return f"{self.cli_def.key}[{self.profile}]"
|
|
103
|
+
return self.cli_def.key
|
|
104
|
+
|
|
105
|
+
# --- public API ------------------------------------------------
|
|
106
|
+
|
|
107
|
+
def reload_from_text(self, toml_text: str) -> bool:
|
|
108
|
+
parser = CliDefParser()
|
|
109
|
+
new_cli_def = parser.parse_from_toml_text(toml_text)
|
|
110
|
+
if new_cli_def is None:
|
|
111
|
+
return False
|
|
112
|
+
self.cli_def = new_cli_def
|
|
113
|
+
self._build_runtime()
|
|
114
|
+
return True
|
|
115
|
+
|
|
116
|
+
def reload_from_file(self, path: str|None=None) -> bool:
|
|
117
|
+
path = path or self._cli_def_file
|
|
118
|
+
if path is None:
|
|
119
|
+
return False
|
|
120
|
+
parser = CliDefParser()
|
|
121
|
+
new_cli_def = parser.parse_from_toml(path)
|
|
122
|
+
if new_cli_def is None:
|
|
123
|
+
return False
|
|
124
|
+
self.cli_def = new_cli_def
|
|
125
|
+
self._build_runtime()
|
|
126
|
+
if path != self._cli_def_file:
|
|
127
|
+
self._cli_def_file = path
|
|
128
|
+
return True
|
|
129
|
+
|
|
130
|
+
@property
|
|
131
|
+
def result_store(self) -> ResultStore:
|
|
132
|
+
return self._result_store
|
|
133
|
+
|
|
134
|
+
# --- execution -------------------------------------------------
|
|
135
|
+
|
|
136
|
+
def execute_line(self, line: str) -> Any:
|
|
137
|
+
return self.runner.run(line)
|
|
138
|
+
|
|
139
|
+
# --- REPL ------------------------------------------------------
|
|
140
|
+
def push_repl_mode(
|
|
141
|
+
self,
|
|
142
|
+
name:str,
|
|
143
|
+
mode_handler: Callable[[CliSession, str], bool],
|
|
144
|
+
prompt: str|None = None):
|
|
145
|
+
self._mode_stack.append(
|
|
146
|
+
ReplModeRecord(
|
|
147
|
+
name=name,
|
|
148
|
+
mode_handler=mode_handler,
|
|
149
|
+
prompt=prompt,
|
|
150
|
+
)
|
|
151
|
+
)
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def pop_repl_mode(self):
|
|
155
|
+
if len(self._mode_stack):
|
|
156
|
+
self._mode_stack.pop()
|
|
157
|
+
return True
|
|
158
|
+
return False
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def _setup_initial_prompt(self, prompt: str|None):
|
|
162
|
+
prompt = prompt or self.cli_def.prompt or self._DEFAULT_PROMPT
|
|
163
|
+
self._initial_prompt = prompt
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def _make_prompt(self):
|
|
167
|
+
return "".join(
|
|
168
|
+
[self._initial_prompt.strip()] +
|
|
169
|
+
[(mode.prompt or mode.name).strip()
|
|
170
|
+
for mode in self._mode_stack]
|
|
171
|
+
) + " "
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def repl(self, prompt: str|None = None):
|
|
175
|
+
self._setup_initial_prompt(prompt)
|
|
176
|
+
while True:
|
|
177
|
+
prompt = self._make_prompt()
|
|
178
|
+
try:
|
|
179
|
+
line = input(prompt).strip()
|
|
180
|
+
except EOFError:
|
|
181
|
+
print()
|
|
182
|
+
if not self.pop_repl_mode():
|
|
183
|
+
break
|
|
184
|
+
except KeyboardInterrupt:
|
|
185
|
+
print("<Ctrl-C>")
|
|
186
|
+
if not self.pop_repl_mode():
|
|
187
|
+
break
|
|
188
|
+
|
|
189
|
+
if len(self._mode_stack):
|
|
190
|
+
self._mode_stack[-1].mode_handler(self, line)
|
|
191
|
+
continue
|
|
192
|
+
|
|
193
|
+
if not line:
|
|
194
|
+
continue
|
|
195
|
+
|
|
196
|
+
try:
|
|
197
|
+
if self._handle_builtin(line):
|
|
198
|
+
continue
|
|
199
|
+
except EOFError:
|
|
200
|
+
print()
|
|
201
|
+
break
|
|
202
|
+
|
|
203
|
+
try:
|
|
204
|
+
before_result_len = self.result_store.len()
|
|
205
|
+
self.execute_line(line)
|
|
206
|
+
after_result_len = self.result_store.len()
|
|
207
|
+
if after_result_len != before_result_len:
|
|
208
|
+
print()
|
|
209
|
+
print(f"-> out[{after_result_len-1}]")
|
|
210
|
+
except Exception as e:
|
|
211
|
+
print(f"[error] {e}")
|
|
212
|
+
except SystemExit: # parse error
|
|
213
|
+
print("Parse Error")
|
|
214
|
+
continue
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
# --- built-in commands -----------------------------------------
|
|
218
|
+
|
|
219
|
+
def _handle_builtin(self, line: str) -> bool:
|
|
220
|
+
if line in ("exit", "quit"):
|
|
221
|
+
raise EOFError()
|
|
222
|
+
|
|
223
|
+
if line == "help":
|
|
224
|
+
# self.parser.print_help()
|
|
225
|
+
self.runner.show_help()
|
|
226
|
+
return True
|
|
227
|
+
|
|
228
|
+
if line == "reload":
|
|
229
|
+
if self.reload_from_file():
|
|
230
|
+
print("[reloaded]")
|
|
231
|
+
return True
|
|
232
|
+
|
|
233
|
+
if line.startswith("load "):
|
|
234
|
+
path = line.split(" ", 1)[1]
|
|
235
|
+
if self.reload_from_file(path):
|
|
236
|
+
print(f"[loaded] {path}")
|
|
237
|
+
return True
|
|
238
|
+
|
|
239
|
+
if line == ">":
|
|
240
|
+
self.push_repl_mode(
|
|
241
|
+
"eval",
|
|
242
|
+
lambda _, x: self._eval_mode(x),
|
|
243
|
+
"eval>> "
|
|
244
|
+
)
|
|
245
|
+
return True
|
|
246
|
+
|
|
247
|
+
if line.startswith(">"):
|
|
248
|
+
possible_expr = line[1:].strip()
|
|
249
|
+
logging.debug(f"@@@ possible_expr={possible_expr!r}")
|
|
250
|
+
try:
|
|
251
|
+
evaluated = self._repl_eval_expression(possible_expr)
|
|
252
|
+
pprint.pprint(evaluated)
|
|
253
|
+
except Exception as e:
|
|
254
|
+
print(f"Error: {type(e).__name__}: {e}")
|
|
255
|
+
return True
|
|
256
|
+
|
|
257
|
+
return False
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
# --- eval mode ------------------------------------------------------
|
|
261
|
+
|
|
262
|
+
def _eval_mode(self, line: str):
|
|
263
|
+
possible_expr = line.strip()
|
|
264
|
+
if len(line) == 0:
|
|
265
|
+
self.pop_repl_mode()
|
|
266
|
+
return True
|
|
267
|
+
|
|
268
|
+
logging.debug(f"@@@ possible_expr={possible_expr!r}")
|
|
269
|
+
try:
|
|
270
|
+
evaluated = self._repl_eval_expression(possible_expr)
|
|
271
|
+
pprint.pprint(evaluated)
|
|
272
|
+
except Exception as e:
|
|
273
|
+
print(f"Error: {type(e).__name__}: {e}")
|
|
274
|
+
return True
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
def _repl_eval_expression(self, expr):
|
|
278
|
+
out_views = [ResultView(r) for r in self.result_store.all()]
|
|
279
|
+
last_out_view = out_views[-1] if len(out_views) else None
|
|
280
|
+
context = {
|
|
281
|
+
"raw_out": self.result_store.all_data(),
|
|
282
|
+
"out": out_views,
|
|
283
|
+
"_": last_out_view,
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
return eval(expr, self.SAFE_GLOBALS, context)
|
cli_def/runtime/utils.py
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
# cli_def/runtime/utils.py
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
from typing import Sequence, Any
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import logging
|
|
7
|
+
|
|
8
|
+
from .context import CliRuntimeContext
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def make_runtime_context(
|
|
12
|
+
args: argparse.Namespace|None = None,
|
|
13
|
+
default_ctx: CliRuntimeContext|None = None,
|
|
14
|
+
) -> CliRuntimeContext:
|
|
15
|
+
if args is None:
|
|
16
|
+
return default_ctx or CliRuntimeContext()
|
|
17
|
+
|
|
18
|
+
ctx = CliRuntimeContext(
|
|
19
|
+
debug=bool(getattr(args, "debug", False)),
|
|
20
|
+
verbose=bool(getattr(args, "verbose", False)),
|
|
21
|
+
lang=getattr(args, "lang", "en"),
|
|
22
|
+
backend=getattr(args, "backend", None),
|
|
23
|
+
extra={
|
|
24
|
+
k: v for k, v in vars(args).items()
|
|
25
|
+
if not k.startswith("_") and
|
|
26
|
+
not k in ("debug", "verbose", "lang", "backend")
|
|
27
|
+
}
|
|
28
|
+
)
|
|
29
|
+
return ctx
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def setup_logging(ctx: CliRuntimeContext):
|
|
33
|
+
level = logging.DEBUG if ctx.debug else logging.INFO if ctx.verbose else logging.WARNING
|
|
34
|
+
#print(f"level={level}, {logging.getLevelName(level)}")
|
|
35
|
+
#logging.basicConfig(level=level) # does not work
|
|
36
|
+
logger = logging.getLogger()
|
|
37
|
+
logger.setLevel(level)
|
|
38
|
+
if level < logging.WARNING:
|
|
39
|
+
logging.info(f"level={get_logging_level_name()}")
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def get_logging_level() -> int:
|
|
43
|
+
logger = logging.getLogger()
|
|
44
|
+
return logger.level
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def get_logging_level_name() -> str:
|
|
48
|
+
level = get_logging_level()
|
|
49
|
+
|
|
50
|
+
for k, v in logging.getLevelNamesMapping().items():
|
|
51
|
+
if v == level:
|
|
52
|
+
return k
|
|
53
|
+
return "UNKNOWN_LEVEL"
|
|
54
|
+
|
cli_def/script/common.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
# cli_def/script/handlers/common.py
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from importlib import resources
|
|
5
|
+
|
|
6
|
+
from ..runtime import (
|
|
7
|
+
CliEvent,
|
|
8
|
+
)
|
|
9
|
+
from ..ops import (
|
|
10
|
+
load_cli_def_path,
|
|
11
|
+
)
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def load_builtin_cli_def(*relative_paths):
|
|
15
|
+
path = resources.files("cli_def.resources")
|
|
16
|
+
if len(relative_paths):
|
|
17
|
+
path = path.joinpath(*relative_paths)
|
|
18
|
+
else:
|
|
19
|
+
path = path.joinpath("cli_def.toml")
|
|
20
|
+
return load_cli_def_path(path)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def print_handler(event: CliEvent):
|
|
24
|
+
print("=== fallback handler ===")
|
|
25
|
+
print(" PATH:", event.path)
|
|
26
|
+
print(" PARAMS:", event.params)
|
|
27
|
+
if event.extra_args:
|
|
28
|
+
print(" EXTRA:", event.extra_args)
|
|
29
|
+
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
# cli_def/script/handlers/dummy.py
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
from typing import Sequence, Any
|
|
4
|
+
import logging
|
|
5
|
+
import copy
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
from ...runtime import (
|
|
9
|
+
CliEvent,
|
|
10
|
+
)
|
|
11
|
+
|
|
12
|
+
from ...runtime import cli_def_handler, CliHandlerResult
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
# --------------------------------------------------------------------------------
|
|
19
|
+
# dummy handlers for scan command test
|
|
20
|
+
# --------------------------------------------------------------------------------
|
|
21
|
+
@cli_def_handler("/cli-def/test1", late_binding=False, description="early binding test1")
|
|
22
|
+
def dummy1_early(event: CliEvent):
|
|
23
|
+
pass
|
|
24
|
+
|
|
25
|
+
@cli_def_handler("/cli-def/test2", late_binding=False, description="early binding test2", tags=["demo"])
|
|
26
|
+
def dummy2_early(event: CliEvent):
|
|
27
|
+
pass
|
|
28
|
+
|
|
29
|
+
@cli_def_handler("/cli-def/test3", late_binding=False, description="learly binding test3", tags=["demo"])
|
|
30
|
+
def dummy3_early(event: CliEvent):
|
|
31
|
+
pass
|
|
32
|
+
|
|
33
|
+
@cli_def_handler("/cli-def/test1", late_binding=True, description="late binding test1")
|
|
34
|
+
def dummy1(event: CliEvent):
|
|
35
|
+
pass
|
|
36
|
+
|
|
37
|
+
@cli_def_handler("/cli-def/test2", late_binding=True, description="late binding test2", tags=["demo"])
|
|
38
|
+
def dummy2(event: CliEvent):
|
|
39
|
+
pass
|
|
40
|
+
|
|
41
|
+
@cli_def_handler("/cli-def/test3", late_binding=True, description="late binding test3", tags=["demo"])
|
|
42
|
+
def dummy3(event: CliEvent):
|
|
43
|
+
pass
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
# cli_def/script/handlers/dummy2.py
|
|
2
|
+
|
|
3
|
+
from ...runtime import (
|
|
4
|
+
cli_def_handler,
|
|
5
|
+
CliEvent,
|
|
6
|
+
)
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
# --------------------------------------------------------------------------------
|
|
10
|
+
# dummy handlers for scan command
|
|
11
|
+
# --------------------------------------------------------------------------------
|
|
12
|
+
@cli_def_handler("/cli-def/testA", late_binding=True, description="late binding testA")
|
|
13
|
+
def dummyA(event: CliEvent):
|
|
14
|
+
pass
|
|
15
|
+
|
|
16
|
+
@cli_def_handler("/cli-def/testB", late_binding=True, description="late binding testB", tags=["demo"])
|
|
17
|
+
def dummyB(event: CliEvent):
|
|
18
|
+
pass
|
|
19
|
+
|
|
20
|
+
@cli_def_handler("/cli-def/testC", late_binding=True, description="late binding testC", tags=["demo"])
|
|
21
|
+
def dummyC(event: CliEvent):
|
|
22
|
+
pass
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
# cli_def/script/handlers/dump.py
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
from typing import Sequence, Any
|
|
4
|
+
import logging
|
|
5
|
+
|
|
6
|
+
from ...runtime import (
|
|
7
|
+
CliEvent,
|
|
8
|
+
CliHandlerResult,
|
|
9
|
+
)
|
|
10
|
+
from ...ops import (
|
|
11
|
+
load_cli_def_path,
|
|
12
|
+
CliDefDumper,
|
|
13
|
+
)
|
|
14
|
+
|
|
15
|
+
from ...runtime import cli_def_handler, CliHandlerResult
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
# --------------------------------------------------------------------------------
|
|
20
|
+
#
|
|
21
|
+
# dump command handler
|
|
22
|
+
#
|
|
23
|
+
# --------------------------------------------------------------------------------
|
|
24
|
+
@cli_def_handler("/cli-def/dump", description="builtin dump command handler", late_binding=True)
|
|
25
|
+
def run_dump(event: CliEvent):
|
|
26
|
+
#check_entrypoints = event.params.get("check_entrypoints", False)
|
|
27
|
+
|
|
28
|
+
logging.info("=== dump command ===")
|
|
29
|
+
|
|
30
|
+
cli_def_file = event.params.get("cli_def_file")
|
|
31
|
+
|
|
32
|
+
assert cli_def_file is not None
|
|
33
|
+
cli_def = load_cli_def_path(cli_def_file)
|
|
34
|
+
if cli_def is None:
|
|
35
|
+
return CliHandlerResult.make_error(
|
|
36
|
+
event,
|
|
37
|
+
f"cli_def could not load: {cli_def_file}",
|
|
38
|
+
)
|
|
39
|
+
|
|
40
|
+
# table = CliDefDumper.dump(cli_def)
|
|
41
|
+
# if check_entrypoints:
|
|
42
|
+
|
|
43
|
+
table = CliDefDumper.dump_pretty(cli_def)
|
|
44
|
+
|
|
45
|
+
return CliHandlerResult.make_result(
|
|
46
|
+
event,
|
|
47
|
+
"run_dump",
|
|
48
|
+
data=table
|
|
49
|
+
)
|
|
50
|
+
|