darwin-cli 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.
darwin_cli/help.py ADDED
@@ -0,0 +1,169 @@
1
+ # src/darwin_cli/help.py
2
+
3
+ """
4
+ Context-aware help text builder.
5
+ """
6
+
7
+ from typing import Dict, List, Optional
8
+
9
+ from darwin_cli.base import Param, ParamInfo, ValidationRule
10
+
11
+
12
+ class HelpBuilder:
13
+ def __init__(self, prog: Optional[str] = None, description: Optional[str] = None):
14
+ self.prog = prog or "main.py"
15
+ self.description = description or "CLI tool"
16
+
17
+ def build_global_help(
18
+ self,
19
+ static_params: List[Param],
20
+ available_sources: Optional[List[str]] = None,
21
+ current_args: Optional[Dict[str, ParamInfo]] = None,
22
+ error: Optional[str] = None,
23
+ ) -> str:
24
+ current_args = current_args or {}
25
+ lines: List[str] = []
26
+
27
+ if error:
28
+ lines.append(f"Error: {error}")
29
+ lines.append("")
30
+
31
+ lines.append(f"Usage: {self.prog} [global options]")
32
+ lines.append("")
33
+
34
+ if self.description:
35
+ lines.append(self.description)
36
+ lines.append("")
37
+
38
+ lines.append("Global options:")
39
+ for p in static_params:
40
+ if p.name == "help":
41
+ continue
42
+ lines.append(f" --{p.name} {self._format_param(p, current_args)}")
43
+
44
+ if available_sources:
45
+ lines.append("")
46
+ lines.append("Sources:")
47
+ lines.append(f" {', '.join(available_sources)}")
48
+
49
+ lines.append(" --help Show this help message")
50
+ lines.append("")
51
+ return "\n".join(lines)
52
+
53
+ def build_scenario_help(
54
+ self,
55
+ static_params: List[Param],
56
+ dynamic_params: List[Param],
57
+ source: Optional[str] = None,
58
+ current_args: Optional[Dict[str, ParamInfo]] = None,
59
+ error: Optional[str] = None,
60
+ ) -> str:
61
+ current_args = current_args or {}
62
+ lines: List[str] = []
63
+
64
+ if error:
65
+ lines.append(f"Error: {error}")
66
+ lines.append("")
67
+
68
+ source_info = f" --source {source}" if source else ""
69
+ lines.append(f"Usage: {self.prog}{source_info} [options]")
70
+ lines.append("")
71
+
72
+ if source:
73
+ lines.append(f"Source: {source}")
74
+ lines.append("")
75
+
76
+ all_params = static_params + dynamic_params
77
+ dynamic_names = {dp.name for dp in dynamic_params}
78
+
79
+ lines.append("Options:")
80
+ for p in all_params:
81
+ if p.name in ("help", "source"):
82
+ continue
83
+ prefix = " " + ("(dynamic) " if p.name in dynamic_names else "")
84
+ lines.append(f"{prefix}--{p.name} {self._format_param(p, current_args)}")
85
+
86
+ lines.append("")
87
+ lines.append(" --help Show this help message")
88
+ return "\n".join(lines)
89
+
90
+ def build_error_help(
91
+ self,
92
+ static_params: List[Param],
93
+ dynamic_params: List[Param],
94
+ source: Optional[str] = None,
95
+ error: str = "",
96
+ available_sources: Optional[List[str]] = None,
97
+ current_args: Optional[Dict[str, ParamInfo]] = None,
98
+ ) -> str:
99
+ current_args = current_args or {}
100
+ if source is not None:
101
+ return self.build_scenario_help(
102
+ static_params=static_params,
103
+ dynamic_params=dynamic_params,
104
+ source=source,
105
+ current_args=current_args,
106
+ error=error,
107
+ )
108
+ return self.build_global_help(
109
+ static_params=static_params,
110
+ available_sources=available_sources,
111
+ current_args=current_args,
112
+ error=error,
113
+ )
114
+
115
+ def _get_help_text(self, param: Param, current_args: Dict[str, ParamInfo]) -> str:
116
+ help_value = param.help
117
+ if callable(help_value):
118
+ try:
119
+ result = help_value(current_args)
120
+ return str(result) if result is not None else ""
121
+ except Exception as e:
122
+ return f"(help generation failed: {e})"
123
+ return str(help_value) if help_value else ""
124
+
125
+ def _format_param(self, param: Param, current_args: Dict[str, ParamInfo]) -> str:
126
+ parts: List[str] = []
127
+
128
+ if isinstance(param.type, str):
129
+ parts.append("(flag)" if param.type == "bool" else f"<{param.type}>")
130
+ else:
131
+ parts.append("<str>")
132
+
133
+ if param.required:
134
+ parts.append("[required]")
135
+
136
+ if param.default is not None and not callable(param.default):
137
+ parts.append(f"(default: {param.default})")
138
+
139
+ validation = self._get_validation(param)
140
+ if validation:
141
+ if validation.choices:
142
+ parts.append(f"choices: {', '.join(str(c) for c in validation.choices)}")
143
+ if validation.min is not None and validation.max is not None:
144
+ parts.append(f"range: {validation.min}-{validation.max}")
145
+ elif validation.min is not None:
146
+ parts.append(f"min: {validation.min}")
147
+ elif validation.max is not None:
148
+ parts.append(f"max: {validation.max}")
149
+ if validation.pattern:
150
+ parts.append(f"pattern: {validation.pattern}")
151
+ if validation.min_length is not None:
152
+ parts.append(f"min length: {validation.min_length}")
153
+ if validation.max_length is not None:
154
+ parts.append(f"max length: {validation.max_length}")
155
+
156
+ help_text = self._get_help_text(param, current_args)
157
+ if help_text:
158
+ if "\n" in help_text:
159
+ indented = "\n ".join(help_text.splitlines())
160
+ parts.append(f"\n {indented}")
161
+ else:
162
+ parts.append(f"({help_text})")
163
+
164
+ return " ".join(parts)
165
+
166
+ def _get_validation(self, param: Param) -> Optional[ValidationRule]:
167
+ if isinstance(param.type, str):
168
+ return param.validation
169
+ return param.type
@@ -0,0 +1,8 @@
1
+ # src/darwin_cli/integrations/__init__.py
2
+
3
+ """
4
+ Optional third-party integrations.
5
+
6
+ These modules import external packages lazily and are never imported by
7
+ ``darwin_cli.__init__``. The core library stays dependency-free.
8
+ """
@@ -0,0 +1,89 @@
1
+ # src/darwin_cli/integrations/darwin_config.py
2
+
3
+ """
4
+ Optional adapter for darwin-config.
5
+
6
+ This module is not imported by ``darwin_cli.__init__``; import it explicitly
7
+ when you want parameter declarations to live in a darwin-config file::
8
+
9
+ from darwin_cli.integrations.darwin_config import from_config
10
+
11
+ app = from_config("config/fetch.json", mount="fetcher", prog="fetch.py")
12
+
13
+ Requires ``darwin-config`` to be installed. The core library has no dependency
14
+ on it.
15
+ """
16
+
17
+ from typing import Any, Dict, Optional
18
+
19
+ from darwin_cli.app import CliApp
20
+
21
+
22
+ def get_loader(*path: str):
23
+ """Return a loader callable bound to darwin-config's ``get_config``.
24
+
25
+ ``path`` is an optional dotted prefix prepended to the key passed to the
26
+ loader. If omitted, keys are used as-is.
27
+ """
28
+ from darwin_config import get_config as _get_config
29
+
30
+ prefix = ".".join(path)
31
+
32
+ def loader(key: str) -> Dict[str, Any]:
33
+ full = f"{prefix}.{key}" if prefix else key
34
+ return _get_config(full, {}) or {}
35
+
36
+ return loader
37
+
38
+
39
+ def from_config(
40
+ config: str,
41
+ mount: Optional[str] = None,
42
+ prog: Optional[str] = None,
43
+ help: Optional[str] = None,
44
+ **kwargs: Any,
45
+ ) -> CliApp:
46
+ """Build a CliApp from a darwin-config key.
47
+
48
+ Args:
49
+ config: dotted config key, e.g. ``"fetcher"`` or ``"fetcher.cli"``.
50
+ mount: optional additional mount prefix (rarely needed when the key
51
+ already includes the mount).
52
+ prog / help / **kwargs: forwarded to :class:`CliApp`.
53
+ """
54
+ from darwin_config import get_config as _get_config
55
+
56
+ data = _get_config(config, {})
57
+ if not data:
58
+ raise ValueError(f"Config key '{config}' is empty or missing")
59
+
60
+ return CliApp.from_config(
61
+ data,
62
+ prog=prog,
63
+ help=help,
64
+ mount=mount,
65
+ **kwargs,
66
+ )
67
+
68
+
69
+ def from_file(
70
+ path: str,
71
+ mount: Optional[str] = None,
72
+ prog: Optional[str] = None,
73
+ help: Optional[str] = None,
74
+ **kwargs: Any,
75
+ ) -> CliApp:
76
+ """Build a CliApp by first loading a config file into darwin-config.
77
+
78
+ Args:
79
+ path: filesystem path to a JSON/YAML/TOML file.
80
+ mount: mount point passed to ``init_config``.
81
+ """
82
+ from darwin_config import get_config as _get_config, init_config
83
+
84
+ init_config(files=[path], mount=mount or "")
85
+ data = _get_config(mount or "", {}) if mount else _get_config("", {})
86
+ return CliApp.from_config(data, prog=prog, help=help, **kwargs)
87
+
88
+
89
+ __all__ = ["get_loader", "from_config", "from_file"]
darwin_cli/loader.py ADDED
@@ -0,0 +1,249 @@
1
+ # src/darwin_cli/loader.py
2
+
3
+ """
4
+ Config-dict conversion helpers and constraint parsing.
5
+ """
6
+
7
+ from typing import Any, Callable, Dict, List, Optional, Union
8
+
9
+ from darwin_cli.base import Constraint, Param, ValidationRule
10
+
11
+ # ============================================================
12
+ # Helpers
13
+ # ============================================================
14
+
15
+
16
+ def _is_valid_help(value: Any) -> bool:
17
+ return isinstance(value, str) or callable(value)
18
+
19
+
20
+ def _is_valid_action(value: Any) -> bool:
21
+ return isinstance(value, str) or callable(value)
22
+
23
+
24
+ def _callable_name(func: Callable) -> str:
25
+ if hasattr(func, "__name__"):
26
+ return func.__name__
27
+ if hasattr(func, "__class__"):
28
+ return func.__class__.__name__
29
+ return "unknown"
30
+
31
+
32
+ # ============================================================
33
+ # Param conversion
34
+ # ============================================================
35
+
36
+
37
+ def parse_params_from_config(config: Dict[str, Dict[str, Any]]) -> List[Param]:
38
+ """Convert a config dict into Param objects.
39
+
40
+ Config format::
41
+
42
+ {
43
+ "param_name": {
44
+ "type": "str", # or ValidationRule, or rule dict
45
+ "required": true,
46
+ "default": "value", # or Callable
47
+ "help": "description", # or Callable
48
+ "action": "action_name", # or Callable
49
+ "depends_on": ["other"],
50
+ "validation": {"min": 1, "max": 100}
51
+ }
52
+ }
53
+ """
54
+ return [_parse_single_param(name, definition) for name, definition in config.items()]
55
+
56
+
57
+ def _parse_single_param(name: str, definition: Dict[str, Any]) -> Param:
58
+ param_type, validation = _parse_type_and_validation(definition)
59
+
60
+ help_value = definition.get("help", "")
61
+ if not _is_valid_help(help_value):
62
+ help_value = str(help_value) if help_value is not None else ""
63
+
64
+ action_value = definition.get("action")
65
+ if action_value is not None and not _is_valid_action(action_value):
66
+ raise ValueError(
67
+ f"Action of parameter '{name}' must be str or Callable, got {type(action_value)}"
68
+ )
69
+
70
+ default_value = definition.get("default")
71
+
72
+ depends_on = definition.get("depends_on")
73
+ if depends_on is not None:
74
+ if not isinstance(depends_on, list):
75
+ raise ValueError(f"depends_on of '{name}' must be a list, got {type(depends_on)}")
76
+ if not all(isinstance(d, str) for d in depends_on):
77
+ raise ValueError(f"depends_on of '{name}' must contain only strings")
78
+
79
+ return Param(
80
+ name=name,
81
+ type=param_type,
82
+ required=definition.get("required", False),
83
+ default=default_value,
84
+ help=help_value,
85
+ action=action_value,
86
+ validation=validation,
87
+ depends_on=depends_on,
88
+ )
89
+
90
+
91
+ def _parse_type_and_validation(definition: Dict[str, Any]) -> tuple:
92
+ raw_type = definition.get("type", "str")
93
+ raw_validation = definition.get("validation")
94
+
95
+ if isinstance(raw_type, dict):
96
+ return _to_validation_rule(raw_type), None
97
+ if isinstance(raw_type, ValidationRule):
98
+ return raw_type, None
99
+ if isinstance(raw_type, str):
100
+ validation_rule: Optional[ValidationRule] = None
101
+ if raw_validation is not None:
102
+ if isinstance(raw_validation, dict):
103
+ validation_rule = _to_validation_rule(raw_validation)
104
+ elif isinstance(raw_validation, ValidationRule):
105
+ validation_rule = raw_validation
106
+ return raw_type, validation_rule
107
+ return "str", None
108
+
109
+
110
+ def _to_validation_rule(data: Union[Dict[str, Any], ValidationRule]) -> ValidationRule:
111
+ if isinstance(data, ValidationRule):
112
+ return data
113
+ if not isinstance(data, dict):
114
+ raise ValueError(f"Cannot convert to ValidationRule: {data}")
115
+ return ValidationRule(
116
+ choices=data.get("choices"),
117
+ min=data.get("min"),
118
+ max=data.get("max"),
119
+ min_length=data.get("min_length"),
120
+ max_length=data.get("max_length"),
121
+ pattern=data.get("pattern"),
122
+ custom=data.get("custom"),
123
+ )
124
+
125
+
126
+ # ============================================================
127
+ # Constraint conversion
128
+ # ============================================================
129
+
130
+ KNOWN_RULES = {
131
+ "mutually_exclusive",
132
+ "together",
133
+ "requires",
134
+ "exclusive_with",
135
+ "at_least_one",
136
+ }
137
+
138
+
139
+ def parse_constraints(config: List[Union[Dict[str, Any], Constraint]]) -> List[Constraint]:
140
+ """Convert a list of constraint dicts into Constraint objects.
141
+
142
+ Supported forms::
143
+
144
+ {"rule": "mutually_exclusive", "params": ["date", "year"]}
145
+ {"rule": "together", "params": ["user", "password"]}
146
+ {"rule": "requires", "param": "type", "requires": "source"}
147
+ {"rule": "exclusive_with", "param": "date", "group": ["start_date", "end_date"]}
148
+ {"rule": "at_least_one", "params": ["source", "file"]}
149
+
150
+ An optional ``message`` overrides the default English error message.
151
+ An optional ``include_generated`` (default ``False``) also counts values
152
+ produced by Actions when checking the rule.
153
+ """
154
+ result: List[Constraint] = []
155
+ for item in config or []:
156
+ if isinstance(item, Constraint):
157
+ result.append(item)
158
+ continue
159
+ if not isinstance(item, dict):
160
+ raise ValueError(f"Constraint must be a dict or Constraint, got {type(item)}")
161
+
162
+ rule = item.get("rule")
163
+ if rule not in KNOWN_RULES:
164
+ raise ValueError(
165
+ f"Unknown constraint rule '{rule}'. Expected one of: {sorted(KNOWN_RULES)}"
166
+ )
167
+
168
+ result.append(
169
+ Constraint(
170
+ rule=rule,
171
+ params=list(item.get("params") or []),
172
+ param=item.get("param"),
173
+ group=list(item.get("group") or []),
174
+ requires=item.get("requires"),
175
+ message=item.get("message"),
176
+ include_generated=bool(item.get("include_generated", False)),
177
+ )
178
+ )
179
+ return result
180
+
181
+
182
+ # ============================================================
183
+ # Convenience helpers
184
+ # ============================================================
185
+
186
+
187
+ def get_param_by_name(params: List[Param], name: str) -> Optional[Param]:
188
+ for p in params:
189
+ if p.name == name:
190
+ return p
191
+ return None
192
+
193
+
194
+ def merge_params(base: List[Param], override: List[Param]) -> List[Param]:
195
+ """Merge two lists; same-name entries in override win."""
196
+ param_map = {p.name: p for p in base}
197
+ for p in override:
198
+ param_map[p.name] = p
199
+ return list(param_map.values())
200
+
201
+
202
+ def params_to_dict(params: List[Param]) -> Dict[str, Dict[str, Any]]:
203
+ """Serialize params for debugging. Callables become placeholder strings."""
204
+ result: Dict[str, Dict[str, Any]] = {}
205
+ for p in params:
206
+ definition: Dict[str, Any] = {}
207
+ if isinstance(p.type, ValidationRule):
208
+ definition["type"] = _validation_rule_to_dict(p.type)
209
+ else:
210
+ definition["type"] = p.type
211
+ if p.required:
212
+ definition["required"] = True
213
+ if p.default is not None:
214
+ definition["default"] = (
215
+ f"<Callable: {_callable_name(p.default)}>"
216
+ if callable(p.default)
217
+ else p.default
218
+ )
219
+ if p.help:
220
+ definition["help"] = (
221
+ f"<Callable: {_callable_name(p.help)}>" if callable(p.help) else p.help
222
+ )
223
+ if p.action:
224
+ definition["action"] = (
225
+ f"<Callable: {_callable_name(p.action)}>" if callable(p.action) else p.action
226
+ )
227
+ if p.validation:
228
+ definition["validation"] = _validation_rule_to_dict(p.validation)
229
+ if p.depends_on:
230
+ definition["depends_on"] = p.depends_on
231
+ result[p.name] = definition
232
+ return result
233
+
234
+
235
+ def _validation_rule_to_dict(rule: ValidationRule) -> Dict[str, Any]:
236
+ result: Dict[str, Any] = {}
237
+ for key in (
238
+ "choices",
239
+ "min",
240
+ "max",
241
+ "min_length",
242
+ "max_length",
243
+ "pattern",
244
+ "custom",
245
+ ):
246
+ value = getattr(rule, key)
247
+ if value is not None:
248
+ result[key] = value
249
+ return result