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.
Files changed (58) hide show
  1. cli_def/__init__.py +16 -0
  2. cli_def/backend/__init__.py +2 -0
  3. cli_def/backend/argparse/__init__.py +10 -0
  4. cli_def/backend/argparse/argparse_builder.py +238 -0
  5. cli_def/backend/click/__init__.py +13 -0
  6. cli_def/backend/click/click_binder.py +46 -0
  7. cli_def/backend/click/click_builder.py +182 -0
  8. cli_def/backend/protocols.py +22 -0
  9. cli_def/demo/__init__.py +2 -0
  10. cli_def/demo/handlers.py +125 -0
  11. cli_def/demo/profiles/advanced.toml +39 -0
  12. cli_def/demo/profiles/beginner.toml +21 -0
  13. cli_def/models/__init__.py +17 -0
  14. cli_def/models/abstract_node.py +87 -0
  15. cli_def/models/argument_def.py +84 -0
  16. cli_def/models/cli_def.py +28 -0
  17. cli_def/models/command_def.py +49 -0
  18. cli_def/models/mult_def.py +81 -0
  19. cli_def/models/schema/cli_schema.py +24 -0
  20. cli_def/ops/__init__.py +16 -0
  21. cli_def/ops/dumper.py +216 -0
  22. cli_def/ops/loader.py +56 -0
  23. cli_def/ops/utils/__init__.py +3 -0
  24. cli_def/ops/utils/pretty_renderer.py +543 -0
  25. cli_def/ops/utils/renderer.py +199 -0
  26. cli_def/ops/utils/renderer_ops.py +169 -0
  27. cli_def/parsers/__init__.py +10 -0
  28. cli_def/parsers/parser.py +101 -0
  29. cli_def/resources/cli_def.toml +126 -0
  30. cli_def/runtime/__init__.py +22 -0
  31. cli_def/runtime/_internal/__init__.py +2 -0
  32. cli_def/runtime/_internal/scan_runner.py +28 -0
  33. cli_def/runtime/context.py +12 -0
  34. cli_def/runtime/dispatcher.py +197 -0
  35. cli_def/runtime/event.py +35 -0
  36. cli_def/runtime/handler_support.py +75 -0
  37. cli_def/runtime/result.py +117 -0
  38. cli_def/runtime/runner.py +178 -0
  39. cli_def/runtime/scanner.py +143 -0
  40. cli_def/runtime/session.py +286 -0
  41. cli_def/runtime/utils.py +54 -0
  42. cli_def/script/__init__.py +2 -0
  43. cli_def/script/common.py +29 -0
  44. cli_def/script/handlers/__init__.py +14 -0
  45. cli_def/script/handlers/dummy.py +43 -0
  46. cli_def/script/handlers/dummy2.py +22 -0
  47. cli_def/script/handlers/dump.py +50 -0
  48. cli_def/script/handlers/repl.py +70 -0
  49. cli_def/script/handlers/run.py +70 -0
  50. cli_def/script/handlers/scan.py +179 -0
  51. cli_def/script/handlers/search.py +116 -0
  52. cli_def/script/main.py +32 -0
  53. cli_def-0.1.0.dist-info/METADATA +400 -0
  54. cli_def-0.1.0.dist-info/RECORD +58 -0
  55. cli_def-0.1.0.dist-info/WHEEL +5 -0
  56. cli_def-0.1.0.dist-info/entry_points.txt +2 -0
  57. cli_def-0.1.0.dist-info/licenses/LICENSE +21 -0
  58. cli_def-0.1.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,21 @@
1
+ # cli_def/demo/profiles/beginner.toml
2
+
3
+ [cli]
4
+ key = "demo"
5
+ help = "Beginner demo CLI"
6
+ prompt = "beginner> " # be used when repl mode
7
+
8
+ [cli.echo]
9
+ help = "Echo message"
10
+ args = [
11
+ {key="message", mult="*", type="str"}
12
+ ]
13
+ entrypoint = "cli_def.demo.handlers:echo"
14
+
15
+ [cli.greet]
16
+ help = "Greet someone"
17
+ args = [
18
+ {key="name", mult="?", type="str"},
19
+ {key="upper", option="--upper", aliases=["-U"], is_flag=true}
20
+ ]
21
+ entrypoint = "cli_def.demo.handlers:greet"
@@ -0,0 +1,17 @@
1
+ # cli_def/models/init.py
2
+ # package marker
3
+
4
+ from .mult_def import MultDef
5
+ from .abstract_node import CliDefNode, ExecutableNode
6
+ from .cli_def import CliDef
7
+ from .command_def import CommandDef
8
+ from .argument_def import ArgumentDef
9
+
10
+ __all__ = [
11
+ "MultDef",
12
+ "CliDefNode",
13
+ "ExecutableNode",
14
+ "CliDef",
15
+ "CommandDef",
16
+ "ArgumentDef",
17
+ ]
@@ -0,0 +1,87 @@
1
+ # cli_def/models/cli_def_node.py
2
+ from __future__ import annotations
3
+ from typing import Optional, Any, Iterator, Mapping, Callable, Iterable, Sequence
4
+ from dataclasses import dataclass, field
5
+ import re
6
+
7
+ # --------------------------------------------------------------------------------
8
+ # CliDefNode class
9
+ # base class of any CliDef node
10
+ # --------------------------------------------------------------------------------
11
+ @dataclass
12
+ class CliDefNode:
13
+ key: str = ""
14
+ parent: CliDefNode|None = None
15
+ extra_defs: dict[str, Any] = field(default_factory=dict)
16
+
17
+ @property
18
+ def defpath(self) -> str:
19
+ if self.parent is not None:
20
+ return "/".join([self.parent.defpath, self.key])
21
+ else:
22
+ return "/" + self.key
23
+
24
+ @property
25
+ def deflevel(self) -> int:
26
+ if self.parent is not None:
27
+ return self.parent.deflevel + 1
28
+ else:
29
+ return 0
30
+
31
+ def iter_all_nodes(self) -> Iterator[CliDefNode]:
32
+ yield self
33
+ for child in self.iter_children():
34
+ yield from child.iter_all_nodes()
35
+
36
+
37
+ def iter_children(self):
38
+ return iter([])
39
+
40
+
41
+ def find(self, path: str) -> CliDefNode|None:
42
+ for node in self.iter_all_nodes():
43
+ if node.defpath == path:
44
+ return node
45
+ return None
46
+
47
+
48
+ def select_first(self, pred: Callable[[CliDefNode], Any]) -> CliDefNode|None:
49
+ for node in self.iter_all_nodes():
50
+ if pred(node):
51
+ return node
52
+
53
+
54
+ def select_all(self, pred: Callable[[CliDefNode], Any]) -> Iterable[CliDefNode]:
55
+ selected = []
56
+ for node in self.iter_all_nodes():
57
+ if pred(node):
58
+ selected.append(node)
59
+ return selected
60
+
61
+
62
+ # detail version moved to ops
63
+ def dump_tree(self) -> Sequence[Sequence[str]]:
64
+ col_keys = ("key", "cls")
65
+ rows = []
66
+ rows.append(col_keys)
67
+ for node in self.iter_all_nodes():
68
+ cells = []
69
+ for col in col_keys:
70
+ if col == "key":
71
+ cell = " " * node.deflevel + (node.key or "")
72
+ elif col == "cls":
73
+ cell = type(node).__name__
74
+ else:
75
+ cell = getattr(node, col, None)
76
+ cells.append(cell)
77
+ rows.append(cells)
78
+ return rows
79
+
80
+
81
+ # --------------------------------------------------------------------------------
82
+ # ExecutableNode
83
+ # base class of CliDef and CommandDef
84
+ # --------------------------------------------------------------------------------
85
+ class ExecutableNode(CliDefNode):
86
+ entrypoint: str|None = None
87
+ group: str|None = None
@@ -0,0 +1,84 @@
1
+ # cli_def/model.py
2
+ from __future__ import annotations
3
+ from typing import Any, Iterator, Mapping
4
+ from dataclasses import dataclass, field
5
+
6
+ from .abstract_node import CliDefNode
7
+ from .mult_def import MultDef
8
+
9
+
10
+
11
+ # --------------------------------------------------------------------------------
12
+ # ArgumentDef
13
+ # a concrete class for argument/option definition
14
+ # --------------------------------------------------------------------------------
15
+ @dataclass
16
+ class ArgumentDef(CliDefNode):
17
+ dest: str|None = None
18
+ option: str|None = None # "--<option>"
19
+ aliases: list[str]|None = None
20
+ type: str|None = None
21
+ mult: MultDef|None = None
22
+ choices: list[Any]|None = None
23
+ default: Any|None = None
24
+ help: str|None = None
25
+ is_flag: bool|None = None
26
+
27
+
28
+ def __post_init__(self):
29
+ if self.mult is None:
30
+ self.mult = MultDef(1, 1)
31
+
32
+ elif isinstance(self.mult, str):
33
+ self.mult = MultDef.from_str(self.mult)
34
+
35
+ elif not isinstance(self.mult, MultDef):
36
+ raise TypeError(f"Invalid mult type: {type(self.mult)}")
37
+
38
+ if self.is_flag:
39
+ if self.default is None:
40
+ self.default = False
41
+ if self.type is None:
42
+ self.type = "bool"
43
+
44
+
45
+ @property
46
+ def is_positional(self) -> bool:
47
+ return self.option is None
48
+
49
+
50
+ @classmethod
51
+ def from_mapping(cls, mapping: Mapping[str, Any]) -> ArgumentDef:
52
+ known = {}
53
+ extra = {}
54
+
55
+ for k, v in mapping.items():
56
+ if k in cls.__dataclass_fields__:
57
+ known[k] = v
58
+ else:
59
+ extra[k] = v
60
+
61
+ obj = cls(**known)
62
+ obj.extra_defs.update(extra)
63
+ return obj
64
+
65
+
66
+ def iter_children(self):
67
+ return iter([])
68
+
69
+
70
+ def get_dest(self) -> str | None:
71
+ if self.option is None:
72
+ # positional parameter ignores dest
73
+ return None
74
+ return self.dest or self.key
75
+
76
+ def get_action(self) -> str | None:
77
+ if self.is_flag:
78
+ if "action" in self.extra_defs:
79
+ return self.extra_defs["action"]
80
+ if self.default is not None and self.default == True:
81
+ return "store_false"
82
+ return "store_true"
83
+ return None
84
+
@@ -0,0 +1,28 @@
1
+ # cli_def/model.py
2
+ from __future__ import annotations
3
+ from typing import Sequence
4
+ from dataclasses import dataclass, field
5
+ import re
6
+
7
+ from .abstract_node import CliDefNode, ExecutableNode
8
+ from .command_def import CommandDef
9
+ from .argument_def import ArgumentDef
10
+
11
+
12
+ # --------------------------------------------------------------------------------
13
+ # CliDef
14
+ # a concrete class for root CLI definition
15
+ # --------------------------------------------------------------------------------
16
+ @dataclass
17
+ class CliDef(ExecutableNode):
18
+ help: str|None = None
19
+ arguments: list[ArgumentDef] = field(default_factory=list)
20
+ commands: list[CommandDef]|None = None
21
+ prompt: str|None = None # prompt on interactive/repl mode
22
+
23
+ def iter_children(self):
24
+ yield from self.arguments or []
25
+ yield from self.commands or []
26
+
27
+ def get_command_sequence(self) -> Sequence[str]:
28
+ return [self.key]
@@ -0,0 +1,49 @@
1
+ # cli_def/models/command_def.py
2
+ from __future__ import annotations
3
+ from typing import Iterable, Sequence
4
+ from dataclasses import dataclass, field
5
+ import re
6
+
7
+ from .abstract_node import CliDefNode, ExecutableNode
8
+ from .argument_def import ArgumentDef
9
+
10
+
11
+
12
+ # --------------------------------------------------------------------------------
13
+ # CliDef
14
+ # a concrete class for command/subcommand definition
15
+ # --------------------------------------------------------------------------------
16
+ @dataclass
17
+ class CommandDef(ExecutableNode):
18
+ # reserved keys
19
+ EARLY = "_early"
20
+ # fields
21
+ is_template: bool = False
22
+ help: str|None = None
23
+ aliases: list[str]|None = None
24
+ arguments: list[ArgumentDef] = field(default_factory=list)
25
+ subcommands: list[CommandDef]|None = None
26
+ inherit_from: list[str]|None = None
27
+
28
+ def iter_children(self):
29
+ yield from self.arguments or []
30
+ yield from self.subcommands or []
31
+
32
+ def get_templates(self) -> Iterable[CommandDef]:
33
+ templates = []
34
+ if self.parent:
35
+ for node in self.parent.iter_children():
36
+ if isinstance(node, CommandDef) and node.is_template:
37
+ templates.append(node)
38
+ if self.inherit_from is None:
39
+ return templates
40
+ inherit_set = set(self.inherit_from)
41
+ return [tmpl for tmpl in templates if tmpl.key in inherit_set]
42
+
43
+ def get_command_sequence(self) -> Sequence[str]:
44
+ key_seq = []
45
+ node = self
46
+ while node is not None:
47
+ key_seq.append(node.key)
48
+ node = node.parent
49
+ return list(reversed(key_seq))
@@ -0,0 +1,81 @@
1
+ # cli_def/models/mult_def.py
2
+ from __future__ import annotations
3
+ from typing import Optional, Any, Iterator, Mapping, Tuple
4
+ from dataclasses import dataclass, field
5
+ import re
6
+
7
+
8
+
9
+ # for multiplicty normalization
10
+ @dataclass
11
+ class MultDef:
12
+ lower: int
13
+ upper: int | None
14
+
15
+ @property
16
+ def is_fixed(self) -> bool:
17
+ return self.upper is not None and self.lower == self.upper
18
+
19
+ @property
20
+ def is_unbounded(self) -> bool:
21
+ return self.upper is None
22
+
23
+ @property
24
+ def is_optional(self) -> bool:
25
+ return self.lower == 0 and self.upper == 1
26
+
27
+
28
+ @classmethod
29
+ def from_str(cls, text: str) -> MultDef:
30
+ text = text.strip()
31
+
32
+ # 記号系
33
+ if text in ("?",):
34
+ return cls(0, 1)
35
+ if text in ("*",):
36
+ return cls(0, None)
37
+ if text in ("+",):
38
+ return cls(1, None)
39
+
40
+ # 数値(固定長)
41
+ if text.isdigit():
42
+ n = int(text)
43
+ return cls(n, n)
44
+
45
+ # 範囲系 ("0..*"も許容)
46
+ m = re.fullmatch(r"(\d+)\.\.((\d+)|\*)", text)
47
+ if m:
48
+ lower = int(m.group(1))
49
+ upper = m.group(2)
50
+ upper = None if upper == "*" else int(upper)
51
+
52
+ if upper is not None and lower > upper:
53
+ raise ValueError(f"Invalid range: {text}")
54
+
55
+ return cls(lower, upper)
56
+
57
+ raise ValueError(f"Invalid mult spec: {text}")
58
+
59
+
60
+ def to_str(self, *, span: bool=False) -> str:
61
+ lower_str = str(self.lower)
62
+ if not span:
63
+ if self.is_fixed:
64
+ return lower_str
65
+
66
+ if self.is_optional:
67
+ return "?"
68
+
69
+ if self.is_unbounded:
70
+ if self.lower == 0:
71
+ return "*"
72
+ elif self.lower == 1:
73
+ return "+"
74
+
75
+ upper_str = "*" if self.upper is None else str(self.upper)
76
+
77
+ return f"{lower_str}..{upper_str}"
78
+
79
+
80
+ def to_tuple(self) -> Tuple[int, int|None]:
81
+ return (self.lower, self.upper)
@@ -0,0 +1,24 @@
1
+ # cli_def/models/schema/cli_schema.py
2
+
3
+
4
+ CLI_SCHEMA = {
5
+ "cli": {
6
+ "type": "object",
7
+ "commands": {
8
+ "*": {
9
+ "type": "command",
10
+ "args": "list"
11
+ }
12
+ }
13
+ }
14
+ }
15
+
16
+ COMMAND_SCHEMA = {
17
+ "key": "key",
18
+ "subcommand": "COMMAND_SCHEMA*",
19
+ "argumets": "ARGUMENT_SCHEMA*"
20
+ }
21
+
22
+ ARGUMENT_SCHEMA = {
23
+ "key": "key",
24
+ }
@@ -0,0 +1,16 @@
1
+ # cli_def/ops/init.py
2
+ # package marker
3
+
4
+ from .dumper import (
5
+ CliDefDumper
6
+ )
7
+ from .loader import (
8
+ load_cli_def_beside,
9
+ load_cli_def_path,
10
+ )
11
+
12
+ __all__ = [
13
+ "CliDefDumper",
14
+ "load_cli_def_beside",
15
+ "load_cli_def_path",
16
+ ]
cli_def/ops/dumper.py ADDED
@@ -0,0 +1,216 @@
1
+ # cli_def/ops/dumper.py
2
+ from __future__ import annotations
3
+ from typing import Sequence, Any, Tuple, Iterable, Callable
4
+
5
+ from ..models import CliDef, CliDefNode, MultDef
6
+
7
+ from .utils.renderer_ops import TableBuilder
8
+ from .utils.pretty_renderer import PrettyRenderer
9
+ from .utils.renderer import (
10
+ Style,
11
+ RowRecord,
12
+ RowType,
13
+ Cell,
14
+ Table,
15
+ )
16
+
17
+
18
+ class CliDefDumper:
19
+ COL_KEY = "key"
20
+ COL_CLS = "cls"
21
+ COL_OPTION = "option"
22
+ COL_MULT = "mult"
23
+ COL_TYPE = "type"
24
+ COL_DEFAULT = "default"
25
+ COL_CHOICES = "choices"
26
+ COL_HELP = "help"
27
+ COL_ENTRYPOINT = "entrypoint"
28
+
29
+ COL_KEYS_FULL = [
30
+ COL_KEY, COL_CLS, COL_OPTION,
31
+ COL_MULT, COL_TYPE, COL_DEFAULT,
32
+ COL_CHOICES, COL_HELP, COL_ENTRYPOINT,
33
+ ]
34
+
35
+ COL_KEYS_FOR_HELP = [
36
+ COL_KEY, COL_CLS, COL_OPTION,
37
+ COL_MULT, COL_TYPE, COL_DEFAULT,
38
+ COL_CHOICES, COL_HELP,
39
+ ]
40
+
41
+
42
+ @classmethod
43
+ def to_display_text(cls, val: Any, none_expr: str|None = None) -> str:
44
+ if none_expr is None:
45
+ none_expr = ""
46
+ if val is None:
47
+ return none_expr
48
+ return str(val)
49
+
50
+
51
+ @classmethod
52
+ def to_short_cls(cls, type) -> str:
53
+ if type.__name__ == "CommandDef":
54
+ return "cmd"
55
+ if type.__name__ == "ArgumentDef":
56
+ return "arg"
57
+ if type.__name__ == "CliDef":
58
+ return "cli"
59
+ return "unk"
60
+
61
+
62
+ @classmethod
63
+ def dump_tree(
64
+ cls,
65
+ cli_def_node: CliDefNode,
66
+ *,
67
+ col_keys: Iterable[str],
68
+ ) -> Sequence[RowRecord]:
69
+
70
+ row_records: list[RowRecord] = []
71
+
72
+ for node in cli_def_node.iter_all_nodes():
73
+ cell_mapping = {}
74
+ for col_key in col_keys:
75
+ if col_key == cls.COL_KEY:
76
+ cell = " " * node.deflevel + node.key
77
+ elif col_key == cls.COL_CLS:
78
+ cell = cls.to_short_cls(type(node))
79
+ elif col_key == cls.COL_MULT:
80
+ if getattr(node, "is_flag", None):
81
+ cell = None
82
+ else:
83
+ mult: MultDef|None = getattr(node, "mult", None)
84
+ cell = mult.to_str() if mult else None
85
+ elif col_key == cls.COL_OPTION:
86
+ if opt := getattr(node, "option", None):
87
+ if aliases := getattr(node, "aliases", []):
88
+ cell = f"{opt} ({','.join(aliases)})"
89
+ else:
90
+ cell = opt
91
+ else:
92
+ cell = None
93
+ elif col_key == cls.COL_TYPE:
94
+ if getattr(node, "is_flag", None):
95
+ cell = "flag"
96
+ else:
97
+ cell = getattr(node, "type", None)
98
+ elif col_key == cls.COL_CHOICES:
99
+ choices = getattr(node, "choices", None)
100
+ if choices:
101
+ cell = f"[{", ".join([str(c) for c in choices])}]"
102
+ else:
103
+ cell = None
104
+ else:
105
+ cell = getattr(node, col_key, None)
106
+ cell_mapping[col_key] = cell
107
+ row_records.append(
108
+ RowRecord(cell_mapping, source=node)
109
+ )
110
+
111
+ return row_records
112
+
113
+
114
+ @classmethod
115
+ def dump(
116
+ cls,
117
+ cli_def: CliDef,
118
+ *,
119
+ as_help: bool=False,
120
+ ) -> Table:
121
+
122
+ if as_help:
123
+ col_keys = cls.COL_KEYS_FOR_HELP
124
+ else:
125
+ col_keys = cls.COL_KEYS_FULL
126
+
127
+ row_records = cls.dump_tree(cli_def, col_keys=col_keys)
128
+ col_keys = ["#"] + list(col_keys)
129
+ row_separator = RowRecord(row_type=RowType.SEPARATOR)
130
+ row_records = [row_separator] + list(row_records) + [row_separator]
131
+ headers = [
132
+ Cell(col_key.upper(), Style(fg_color="cyan"))
133
+ for col_key in col_keys
134
+ ]
135
+ table = TableBuilder.from_row_records(
136
+ columns=col_keys,
137
+ row_records=row_records,
138
+ display_column_keys=col_keys,
139
+ headers=headers,
140
+ )
141
+ table.row_records.insert(
142
+ 0,
143
+ RowRecord(
144
+ row_type=RowType.HEADER,
145
+ default_style=Style(bold=True)
146
+ )
147
+ )
148
+
149
+ # apply column styles
150
+ for col_key, col in table.column_mapping.items():
151
+ if col_key == "help":
152
+ col.default_style = Style(
153
+ wrap_width=30,
154
+ ).merge(col.default_style)
155
+ if col_key == "choices":
156
+ col.default_style = Style(
157
+ wrap_width=20,
158
+ ).merge(col.default_style)
159
+ if as_help:
160
+ if col_key == "option":
161
+ col.default_style = Style(
162
+ bold=True,
163
+ fg_color="green",
164
+ ).merge(col.default_style)
165
+ if col_key == "choices":
166
+ col.default_style = Style(
167
+ bold=True,
168
+ fg_color="green"
169
+ ).merge(col.default_style)
170
+
171
+ if as_help:
172
+ # apply row styles
173
+ for row in table.row_records:
174
+ if row.get_raw_value("cls", None) == "cmd":
175
+ key = row.get_raw_value("key", "")
176
+ if key is not None and not key.strip().startswith("_"):
177
+ row.default_style = Style(
178
+ fg_color="magenta",
179
+ bold=True,
180
+ #underline=True,
181
+ ).merge(row.default_style)
182
+ # if row.get_raw_value("cls", None) == "arg":
183
+ # row.default_style = Style(fg_color="cyan")
184
+ return table
185
+
186
+
187
+ @classmethod
188
+ def dump_pretty(
189
+ cls,
190
+ cli_def: CliDef,
191
+ *,
192
+ as_help: bool=False,
193
+ print_func: Callable|None = None
194
+ ) -> Table:
195
+
196
+ table = cls.dump(cli_def, as_help=as_help)
197
+
198
+ cls.print_table(table, print_func=print_func)
199
+
200
+ return table
201
+
202
+
203
+ @classmethod
204
+ def print_table(
205
+ cls,
206
+ table: Table,
207
+ *,
208
+ print_func: Callable|None = None
209
+ ):
210
+ print_func = print_func or print
211
+ renderer = PrettyRenderer()
212
+ renderer.value_formatter = lambda v: str(v) if v is not None else ""
213
+ rendered_seq = renderer.render_table(table)
214
+ if rendered_seq:
215
+ for line in rendered_seq:
216
+ print_func(line)
cli_def/ops/loader.py ADDED
@@ -0,0 +1,56 @@
1
+ # cli_def/ops/loader.py
2
+ from __future__ import annotations
3
+
4
+ from typing import Mapping, Any, Union
5
+ from pathlib import Path
6
+ import logging
7
+ import tomllib
8
+
9
+ from typing import Union
10
+ from pathlib import Path
11
+
12
+ PathLike = Union[str, Path]
13
+
14
+ from ..models import CliDef
15
+ from ..parsers import CliDefParser
16
+
17
+
18
+ def load_toml_beside(
19
+ here: Path,
20
+ *path_parts: PathLike
21
+ ) -> Mapping[str, Any]:
22
+ """
23
+ Usage:
24
+ load_toml_beside(Path(__file__), "cli_def.toml")
25
+ load_toml_beside(Path(__file__), "resources", "cli_def.toml")
26
+ """
27
+ base = here.resolve().parent
28
+ toml_path = base.joinpath(*path_parts)
29
+ with toml_path.open("rb") as f:
30
+ return tomllib.load(f)
31
+
32
+
33
+ def load_cli_def_beside(
34
+ here: Path,
35
+ *path_parts: PathLike
36
+ ) -> CliDef | None:
37
+ """
38
+ Usage:
39
+ load_cli_def_beside(Path(__file__), "cli_def.toml")
40
+ load_cli_def_beside(Path(__file__), "profiles", f"{profile}.toml")
41
+ """
42
+ base = here.resolve().parent
43
+ toml_path = base.joinpath(*path_parts)
44
+ return load_cli_def_path(toml_path)
45
+
46
+
47
+ def load_cli_def_path(path_to_toml: PathLike) -> CliDef | None:
48
+ if path_to_toml is None:
49
+ return None
50
+ if not Path(path_to_toml).exists():
51
+ logging.warning(f"cli_def file not found: {path_to_toml}")
52
+ return None
53
+
54
+ parser = CliDefParser()
55
+ cli_def = parser.parse_from_toml(path_to_toml)
56
+ return cli_def
@@ -0,0 +1,3 @@
1
+ # cli_def/ops/utils/init.py
2
+ # package marker
3
+