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/__init__.py ADDED
@@ -0,0 +1,99 @@
1
+ # src/darwin_cli/__init__.py
2
+
3
+ """
4
+ darwin-cli
5
+
6
+ Declaration-driven CLI engine: parameters can compute values, infer other
7
+ parameters and generate new parameter definitions at runtime. Supports
8
+ config-file driven parameter declarations and cross-parameter constraints.
9
+
10
+ Zero third-party dependencies.
11
+ """
12
+
13
+ from darwin_cli.actions import (
14
+ ACTION_REGISTRY,
15
+ GLOBAL_ACTIONS,
16
+ ActionError,
17
+ ActionRegistry,
18
+ ConflictError,
19
+ ConstraintError,
20
+ CycleDetected,
21
+ HelpRequested,
22
+ MaxIterationsExceeded,
23
+ RequiredError,
24
+ clear_actions,
25
+ get_action,
26
+ has_action,
27
+ list_actions,
28
+ load_actions_from_file,
29
+ load_actions_from_module,
30
+ register_action,
31
+ validate_before,
32
+ )
33
+ from darwin_cli.app import CliApp
34
+ from darwin_cli.base import (
35
+ ActionResult,
36
+ CliResult,
37
+ Constraint,
38
+ Param,
39
+ ParamInfo,
40
+ ValidationRule,
41
+ )
42
+ from darwin_cli.constraints import check_constraint, check_constraints
43
+ from darwin_cli.loader import (
44
+ get_param_by_name,
45
+ merge_params,
46
+ params_to_dict,
47
+ parse_constraints,
48
+ parse_params_from_config,
49
+ )
50
+ from darwin_cli.parser import build_parser, parse_args_with_meta
51
+ from darwin_cli.validator import Validator, create_validator
52
+
53
+ __version__ = "0.1.0"
54
+
55
+ __all__ = [
56
+ # core
57
+ "CliApp",
58
+ "Param",
59
+ "ParamInfo",
60
+ "ValidationRule",
61
+ "Constraint",
62
+ "ActionResult",
63
+ "CliResult",
64
+ # registry
65
+ "ActionRegistry",
66
+ "GLOBAL_ACTIONS",
67
+ "ACTION_REGISTRY",
68
+ "register_action",
69
+ "get_action",
70
+ "has_action",
71
+ "list_actions",
72
+ "clear_actions",
73
+ "validate_before",
74
+ "load_actions_from_module",
75
+ "load_actions_from_file",
76
+ # config helpers
77
+ "parse_params_from_config",
78
+ "parse_constraints",
79
+ "merge_params",
80
+ "params_to_dict",
81
+ "get_param_by_name",
82
+ # constraints
83
+ "check_constraint",
84
+ "check_constraints",
85
+ # lower-level
86
+ "parse_args_with_meta",
87
+ "build_parser",
88
+ "Validator",
89
+ "create_validator",
90
+ # exceptions
91
+ "ActionError",
92
+ "ConflictError",
93
+ "ConstraintError",
94
+ "CycleDetected",
95
+ "HelpRequested",
96
+ "MaxIterationsExceeded",
97
+ "RequiredError",
98
+ "__version__",
99
+ ]
darwin_cli/actions.py ADDED
@@ -0,0 +1,225 @@
1
+ # src/darwin_cli/actions.py
2
+
3
+ """
4
+ Action registry (global + per-app instances), built-in actions and exceptions.
5
+ """
6
+
7
+ from functools import wraps
8
+ from typing import Any, Callable, Dict, Optional
9
+
10
+ # ============================================================
11
+ # Registry
12
+ # ============================================================
13
+
14
+
15
+ class ActionRegistry:
16
+ """An isolated namespace of actions.
17
+
18
+ The library keeps a global registry for the classic decorator style::
19
+
20
+ @register_action("hello")
21
+ def hello(value, ctx): ...
22
+
23
+ Applications that need isolation can create their own and inject it::
24
+
25
+ reg = ActionRegistry()
26
+ @register_action("hello", registry=reg)
27
+ def hello(value, ctx): ...
28
+ app = CliApp(params=..., registry=reg)
29
+ """
30
+
31
+ def __init__(self) -> None:
32
+ self._actions: Dict[str, Callable] = {}
33
+
34
+ def register(self, name: str, func: Callable) -> None:
35
+ if name in self._actions:
36
+ raise ValueError(f"Action '{name}' already registered")
37
+ self._actions[name] = func
38
+
39
+ def get(self, name: str) -> Callable:
40
+ if name not in self._actions:
41
+ raise KeyError(f"Action '{name}' not registered")
42
+ return self._actions[name]
43
+
44
+ def has(self, name: str) -> bool:
45
+ return name in self._actions
46
+
47
+ def list_actions(self) -> Dict[str, Callable]:
48
+ return dict(self._actions)
49
+
50
+ def clear(self) -> None:
51
+ self._actions.clear()
52
+
53
+ # dict-like helpers for compatibility with code that inspects the registry
54
+ def __contains__(self, name: str) -> bool:
55
+ return name in self._actions
56
+
57
+ def __getitem__(self, name: str) -> Callable:
58
+ return self.get(name)
59
+
60
+ def __iter__(self):
61
+ return iter(self._actions)
62
+
63
+ def __len__(self) -> int:
64
+ return len(self._actions)
65
+
66
+
67
+ GLOBAL_ACTIONS = ActionRegistry()
68
+
69
+ # Backward-compatible alias: still points to the process-wide registry.
70
+ ACTION_REGISTRY = GLOBAL_ACTIONS
71
+
72
+
73
+ def register_action(name: str, *, registry: Optional[ActionRegistry] = None):
74
+ """Decorator: register an action function.
75
+
76
+ Args:
77
+ name: action name referenced by ``Param.action``.
78
+ registry: target registry; defaults to the global one.
79
+ """
80
+ target = registry if registry is not None else GLOBAL_ACTIONS
81
+
82
+ def decorator(func: Callable) -> Callable:
83
+ target.register(name, func)
84
+ return func
85
+
86
+ return decorator
87
+
88
+
89
+ def get_action(name: str, registry: Optional[ActionRegistry] = None) -> Callable:
90
+ target = registry if registry is not None else GLOBAL_ACTIONS
91
+ return target.get(name)
92
+
93
+
94
+ def has_action(name: str, registry: Optional[ActionRegistry] = None) -> bool:
95
+ target = registry if registry is not None else GLOBAL_ACTIONS
96
+ return target.has(name)
97
+
98
+
99
+ def list_actions(registry: Optional[ActionRegistry] = None) -> Dict[str, Callable]:
100
+ target = registry if registry is not None else GLOBAL_ACTIONS
101
+ return target.list_actions()
102
+
103
+
104
+ def clear_actions(registry: Optional[ActionRegistry] = None) -> None:
105
+ target = registry if registry is not None else GLOBAL_ACTIONS
106
+ target.clear()
107
+
108
+
109
+ def validate_before(validator: Callable):
110
+ """Decorator: call ``validator(current_args)`` before the action runs.
111
+
112
+ The validator must raise to reject the invocation.
113
+ """
114
+
115
+ def decorator(func: Callable) -> Callable:
116
+ @wraps(func)
117
+ def wrapper(value, current_args):
118
+ validator(current_args)
119
+ return func(value, current_args)
120
+
121
+ return wrapper
122
+
123
+ return decorator
124
+
125
+
126
+ # ============================================================
127
+ # Built-in actions
128
+ # ============================================================
129
+
130
+
131
+ @register_action("print_help")
132
+ def print_help(value: bool, current_args: Dict[str, Any]) -> None:
133
+ """Raise HelpRequested; CliApp turns it into formatted help output."""
134
+ raise HelpRequested()
135
+
136
+
137
+ @register_action("set_overwrite")
138
+ def set_overwrite(value: bool, current_args: Dict[str, Any]) -> Dict[str, Any]:
139
+ return {"overwrite": True} if value else {}
140
+
141
+
142
+ @register_action("set_fake")
143
+ def set_fake(value: bool, current_args: Dict[str, Any]) -> Dict[str, Any]:
144
+ return {"fake": True} if value else {}
145
+
146
+
147
+ # ============================================================
148
+ # Dynamic loading
149
+ # ============================================================
150
+
151
+
152
+ def load_actions_from_module(module_path: str, registry: Optional[ActionRegistry] = None) -> None:
153
+ """Import a module so its ``@register_action`` decorators execute.
154
+
155
+ Note: a decorator without an explicit registry always targets the global
156
+ registry. Use ``register_action(..., registry=reg)`` inside the module for
157
+ isolated registration.
158
+ """
159
+ import importlib
160
+
161
+ try:
162
+ importlib.import_module(module_path)
163
+ except ImportError as e:
164
+ raise ImportError(f"Cannot load action module '{module_path}': {e}")
165
+
166
+
167
+ def load_actions_from_file(filepath: str) -> None:
168
+ """Load action definitions from a Python file (global registry)."""
169
+ import importlib.util
170
+ import sys
171
+ from pathlib import Path
172
+
173
+ path = Path(filepath)
174
+ if not path.exists():
175
+ raise FileNotFoundError(f"Action file not found: {filepath}")
176
+
177
+ module_name = path.stem
178
+ spec = importlib.util.spec_from_file_location(module_name, path)
179
+ if spec is None or spec.loader is None:
180
+ raise ImportError(f"Cannot load action file: {filepath}")
181
+
182
+ module = importlib.util.module_from_spec(spec)
183
+ sys.modules[module_name] = module
184
+ spec.loader.exec_module(module)
185
+
186
+
187
+ # ============================================================
188
+ # Exceptions (English messages by design: for developers)
189
+ # ============================================================
190
+
191
+
192
+ class HelpRequested(Exception):
193
+ """Request help output."""
194
+
195
+
196
+ class ActionError(Exception):
197
+ """Action execution or validation failed."""
198
+
199
+
200
+ class ConflictError(ActionError):
201
+ """Parameters conflict with each other."""
202
+
203
+
204
+ class ConstraintError(ActionError):
205
+ """A cross-parameter constraint was violated.
206
+
207
+ ``violations`` carries machine-readable details:
208
+ [{"rule": ..., "params": [...], "message": ...}, ...]
209
+ """
210
+
211
+ def __init__(self, message: str, violations: Optional[list] = None):
212
+ super().__init__(message)
213
+ self.violations = violations or []
214
+
215
+
216
+ class RequiredError(Exception):
217
+ """A required parameter is missing or came from an invalid source."""
218
+
219
+
220
+ class MaxIterationsExceeded(Exception):
221
+ """The deferred-execution loop exceeded its iteration budget."""
222
+
223
+
224
+ class CycleDetected(ActionError):
225
+ """A dependency cycle was detected among parameters."""
darwin_cli/app.py ADDED
@@ -0,0 +1,277 @@
1
+ # src/darwin_cli/app.py
2
+
3
+ """
4
+ CliApp facade: ties all components together.
5
+ """
6
+
7
+ import json
8
+ import sys
9
+ from pathlib import Path
10
+ from typing import Any, Callable, Dict, List, Optional, Union
11
+
12
+ from darwin_cli.actions import (
13
+ ActionError,
14
+ ActionRegistry,
15
+ GLOBAL_ACTIONS,
16
+ HelpRequested,
17
+ MaxIterationsExceeded,
18
+ RequiredError,
19
+ load_actions_from_module,
20
+ )
21
+ from darwin_cli.base import CliResult, Constraint, Param
22
+ from darwin_cli.executor import Executor
23
+ from darwin_cli.help import HelpBuilder
24
+ from darwin_cli.loader import (
25
+ get_param_by_name,
26
+ parse_constraints,
27
+ parse_params_from_config,
28
+ )
29
+ from darwin_cli.parser import parse_args_with_meta
30
+
31
+
32
+ class CliApp:
33
+ """Unified CLI application facade.
34
+
35
+ Example::
36
+
37
+ app = CliApp(params=[Param(name="name", required=True)], prog="demo.py")
38
+ result = app.run(["--name", "Alice"])
39
+ """
40
+
41
+ def __init__(
42
+ self,
43
+ params: Union[List[Param], Dict[str, Dict[str, Any]]],
44
+ prog: Optional[str] = None,
45
+ description: Optional[str] = None,
46
+ help: Optional[str] = None,
47
+ max_iterations: int = 100,
48
+ action_modules: Optional[List[str]] = None,
49
+ custom_validators: Optional[Dict[str, Callable]] = None,
50
+ available_sources: Optional[List[str]] = None,
51
+ constraints: Optional[List[Union[Dict[str, Any], Constraint]]] = None,
52
+ registry: Optional[ActionRegistry] = None,
53
+ ):
54
+ self._initial_params = self._normalize_params(params)
55
+ self._initial_constraints = parse_constraints(constraints or [])
56
+
57
+ self.prog = prog
58
+ self.description = help or description or ""
59
+ self.max_iterations = max_iterations
60
+ self.custom_validators = custom_validators or {}
61
+ self.available_sources = available_sources or []
62
+ self.registry = registry if registry is not None else GLOBAL_ACTIONS
63
+
64
+ self._executor: Optional[Executor] = None
65
+ self._static_params: List[Param] = []
66
+ self._dynamic_params: List[Param] = []
67
+
68
+ if action_modules:
69
+ for module_path in action_modules:
70
+ load_actions_from_module(module_path, self.registry)
71
+
72
+ # ============================================================
73
+ # Alternative constructors
74
+ # ============================================================
75
+
76
+ @classmethod
77
+ def from_config(
78
+ cls,
79
+ config: Union[str, Dict[str, Any]],
80
+ prog: Optional[str] = None,
81
+ help: Optional[str] = None,
82
+ loader: Optional[Callable[[str], Dict[str, Any]]] = None,
83
+ mount: Optional[str] = None,
84
+ **kwargs: Any,
85
+ ) -> "CliApp":
86
+ """Build a CliApp from a config dict or a config file path.
87
+
88
+ Args:
89
+ config: a config dict, or a path string.
90
+ prog / help: forwarded to the constructor.
91
+ loader: optional callable that resolves a path string to a dict.
92
+ Pass ``darwin_config.get_config`` to integrate with darwin-config.
93
+ When omitted, JSON files are read with the standard library.
94
+ mount: optional dotted key path to select a sub-section of the config.
95
+ **kwargs: all other CliApp constructor arguments.
96
+ """
97
+ if isinstance(config, str):
98
+ if loader is not None:
99
+ data = loader(config)
100
+ else:
101
+ with Path(config).open("r", encoding="utf-8") as f:
102
+ data = json.load(f)
103
+ elif isinstance(config, dict):
104
+ data = config
105
+ else:
106
+ raise TypeError(f"config must be a dict or path string, got {type(config)}")
107
+
108
+ if mount:
109
+ for part in mount.split("."):
110
+ data = data.get(part, {}) if isinstance(data, dict) else {}
111
+
112
+ description = help or (data.get("help") if isinstance(data, dict) else None)
113
+ params_section = data.get("cli_args", data.get("params", {})) if isinstance(data, dict) else {}
114
+ constraints_section = data.get("constraints", []) if isinstance(data, dict) else []
115
+
116
+ return cls(
117
+ params=params_section,
118
+ prog=prog or (data.get("prog") if isinstance(data, dict) else None),
119
+ help=description,
120
+ constraints=constraints_section,
121
+ **kwargs,
122
+ )
123
+
124
+ # ============================================================
125
+ # Init helpers
126
+ # ============================================================
127
+
128
+ def _normalize_params(
129
+ self,
130
+ params: Union[List[Param], Dict[str, Dict[str, Any]]],
131
+ ) -> List[Param]:
132
+ if isinstance(params, list):
133
+ for p in params:
134
+ if not isinstance(p, Param):
135
+ raise TypeError(f"params elements must be Param, got {type(p)}")
136
+ return params
137
+ if isinstance(params, dict):
138
+ return parse_params_from_config(params)
139
+ raise TypeError(f"params must be List[Param] or dict, got {type(params)}")
140
+
141
+ # ============================================================
142
+ # Run
143
+ # ============================================================
144
+
145
+ def run(self, args: Optional[List[str]] = None) -> CliResult:
146
+ if args is None:
147
+ args = sys.argv[1:]
148
+
149
+ try:
150
+ self._static_params = self._initial_params
151
+ raw_static = parse_args_with_meta(
152
+ params=self._static_params,
153
+ args=args,
154
+ prog=self.prog,
155
+ description=self.description,
156
+ )
157
+
158
+ self._executor = Executor(
159
+ params=self._static_params,
160
+ max_iterations=self.max_iterations,
161
+ custom_validators=self.custom_validators,
162
+ constraints=self._initial_constraints,
163
+ registry=self.registry,
164
+ )
165
+
166
+ final_args = self._executor.run(raw_static)
167
+
168
+ all_params = self._executor._get_all_params()
169
+ static_names = {p.name for p in self._static_params}
170
+ self._dynamic_params = [p for p in all_params if p.name not in static_names]
171
+
172
+ return CliResult.ok(final_args)
173
+
174
+ except HelpRequested:
175
+ print(self._build_help_text())
176
+ return CliResult.help()
177
+
178
+ except RequiredError as e:
179
+ error_msg = str(e)
180
+ print(self._build_error_help_text(error_msg))
181
+ return CliResult.fail(error_msg)
182
+
183
+ except (ActionError, MaxIterationsExceeded) as e:
184
+ error_msg = str(e)
185
+ print(self._build_error_help_text(error_msg))
186
+ return CliResult.fail(error_msg)
187
+
188
+ except Exception as e:
189
+ error_msg = str(e)
190
+ print(f"Error: {error_msg}", file=sys.stderr)
191
+ return CliResult.fail(error_msg)
192
+
193
+ def run_or_exit(self, args: Optional[List[str]] = None) -> Dict[str, Any]:
194
+ result = self.run(args)
195
+ if not result.success:
196
+ if result.error:
197
+ print(f"Error: {result.error}", file=sys.stderr)
198
+ sys.exit(result.exit_code)
199
+ if result.data is None:
200
+ raise RuntimeError("Run succeeded but returned no data")
201
+ return result.data
202
+
203
+ # ============================================================
204
+ # Help building
205
+ # ============================================================
206
+
207
+ def _get_source_from_current_args(self) -> Optional[str]:
208
+ if self._executor is None or self._executor.current_args is None:
209
+ return None
210
+ info = self._executor.current_args.get("source")
211
+ if info is None:
212
+ return None
213
+ return str(info.value) if info.value is not None else None
214
+
215
+ def _build_help_text(self) -> str:
216
+ builder = HelpBuilder(prog=self.prog, description=self.description)
217
+ if self._executor is None:
218
+ return "Executor not initialized"
219
+
220
+ all_params = self._executor._get_all_params()
221
+ static_names = {p.name for p in self._static_params}
222
+ dynamic_params = [p for p in all_params if p.name not in static_names]
223
+
224
+ source = self._get_source_from_current_args()
225
+ current_args = self._executor.current_args or {}
226
+
227
+ if source and dynamic_params:
228
+ return builder.build_scenario_help(
229
+ static_params=self._static_params,
230
+ dynamic_params=dynamic_params,
231
+ source=source,
232
+ current_args=current_args,
233
+ )
234
+ return builder.build_global_help(
235
+ static_params=self._static_params,
236
+ available_sources=self.available_sources,
237
+ current_args=current_args,
238
+ )
239
+
240
+ def _build_error_help_text(self, error: str) -> str:
241
+ builder = HelpBuilder(prog=self.prog, description=self.description)
242
+ if self._executor is None:
243
+ return f"Error: {error}"
244
+
245
+ all_params = self._executor._get_all_params()
246
+ static_names = {p.name for p in self._static_params}
247
+ dynamic_params = [p for p in all_params if p.name not in static_names]
248
+
249
+ return builder.build_error_help(
250
+ static_params=self._static_params,
251
+ dynamic_params=dynamic_params,
252
+ source=self._get_source_from_current_args(),
253
+ error=error,
254
+ available_sources=self.available_sources,
255
+ current_args=self._executor.current_args or {},
256
+ )
257
+
258
+ # ============================================================
259
+ # Convenience properties
260
+ # ============================================================
261
+
262
+ @property
263
+ def params(self) -> List[Param]:
264
+ if self._executor is None:
265
+ return self._static_params
266
+ return self._executor._get_all_params()
267
+
268
+ @property
269
+ def static_params(self) -> List[Param]:
270
+ return self._static_params
271
+
272
+ @property
273
+ def dynamic_params(self) -> List[Param]:
274
+ return self._dynamic_params
275
+
276
+ def get_param(self, name: str) -> Optional[Param]:
277
+ return get_param_by_name(self.params, name)