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 +99 -0
- darwin_cli/actions.py +225 -0
- darwin_cli/app.py +277 -0
- darwin_cli/base.py +119 -0
- darwin_cli/constraints.py +127 -0
- darwin_cli/executor.py +428 -0
- darwin_cli/help.py +169 -0
- darwin_cli/integrations/__init__.py +8 -0
- darwin_cli/integrations/darwin_config.py +89 -0
- darwin_cli/loader.py +249 -0
- darwin_cli/parser.py +198 -0
- darwin_cli/py.typed +0 -0
- darwin_cli/validator.py +147 -0
- darwin_cli-0.1.0.dist-info/METADATA +503 -0
- darwin_cli-0.1.0.dist-info/RECORD +16 -0
- darwin_cli-0.1.0.dist-info/WHEEL +4 -0
darwin_cli/base.py
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
# src/darwin_cli/base.py
|
|
2
|
+
|
|
3
|
+
"""
|
|
4
|
+
Core data types for darwin-cli.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from dataclasses import dataclass, field
|
|
8
|
+
from typing import Any, Callable, Dict, List, Optional, Union
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
@dataclass
|
|
12
|
+
class ValidationRule:
|
|
13
|
+
"""Validation constraints for a parameter value."""
|
|
14
|
+
|
|
15
|
+
choices: Optional[List[Any]] = None
|
|
16
|
+
min: Optional[float] = None
|
|
17
|
+
max: Optional[float] = None
|
|
18
|
+
min_length: Optional[int] = None
|
|
19
|
+
max_length: Optional[int] = None
|
|
20
|
+
pattern: Optional[str] = None
|
|
21
|
+
custom: Optional[str] = None
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@dataclass
|
|
25
|
+
class Constraint:
|
|
26
|
+
"""A cross-parameter relationship rule.
|
|
27
|
+
|
|
28
|
+
Supported rules (see constraints.py):
|
|
29
|
+
mutually_exclusive - at most one of ``params`` may be an explicit CLI arg
|
|
30
|
+
together - all of ``params`` must appear together, or none
|
|
31
|
+
requires - if ``param`` is explicit, ``requires`` must be explicit too
|
|
32
|
+
exclusive_with - ``param`` excludes every name in ``group``
|
|
33
|
+
at_least_one - at least one of ``params`` must be explicit
|
|
34
|
+
"""
|
|
35
|
+
|
|
36
|
+
rule: str
|
|
37
|
+
params: List[str] = field(default_factory=list)
|
|
38
|
+
param: Optional[str] = None
|
|
39
|
+
group: List[str] = field(default_factory=list)
|
|
40
|
+
requires: Optional[str] = None
|
|
41
|
+
message: Optional[str] = None
|
|
42
|
+
include_generated: bool = False
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
@dataclass
|
|
46
|
+
class Param:
|
|
47
|
+
"""Static parameter declaration.
|
|
48
|
+
|
|
49
|
+
Fields:
|
|
50
|
+
name: parameter name, used on the command line as ``--name``
|
|
51
|
+
type: "str" | "int" | "float" | "bool", or a ValidationRule (implies str)
|
|
52
|
+
required: must be provided by the user or produced by an Action
|
|
53
|
+
default: static value, or Callable[current_args] -> value
|
|
54
|
+
help: static text, or Callable[current_args] -> text
|
|
55
|
+
action: registered action name, or Callable(value, current_args) -> result
|
|
56
|
+
validation: rule object when ``type`` is a string
|
|
57
|
+
depends_on: names that must be processed before this parameter
|
|
58
|
+
"""
|
|
59
|
+
|
|
60
|
+
name: str
|
|
61
|
+
type: Union[str, ValidationRule] = "str"
|
|
62
|
+
required: bool = False
|
|
63
|
+
default: Any = None
|
|
64
|
+
help: Union[str, Callable] = ""
|
|
65
|
+
action: Optional[Union[str, Callable]] = None
|
|
66
|
+
validation: Optional[ValidationRule] = None
|
|
67
|
+
depends_on: Optional[List[str]] = None
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
@dataclass
|
|
71
|
+
class ParamInfo:
|
|
72
|
+
"""Runtime information for a parameter."""
|
|
73
|
+
|
|
74
|
+
value: Any
|
|
75
|
+
defined: bool = False
|
|
76
|
+
from_source: str = "cli" # cli | default | action
|
|
77
|
+
processed: bool = False
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
@dataclass
|
|
81
|
+
class ActionResult:
|
|
82
|
+
"""Return value of an Action.
|
|
83
|
+
|
|
84
|
+
values: values to add or overwrite
|
|
85
|
+
params: new parameter definitions discovered at runtime
|
|
86
|
+
"""
|
|
87
|
+
|
|
88
|
+
values: Dict[str, Any] = field(default_factory=dict)
|
|
89
|
+
params: List[Param] = field(default_factory=list)
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
@dataclass
|
|
93
|
+
class CliResult:
|
|
94
|
+
"""Result of a CLI run.
|
|
95
|
+
|
|
96
|
+
``success``, ``error`` and ``exit_code`` are kept for backward compatibility.
|
|
97
|
+
``outcome`` gives an unambiguous three-way classification:
|
|
98
|
+
"ok" - parsed successfully
|
|
99
|
+
"help" - help was requested (exit_code 0, success False)
|
|
100
|
+
"error" - validation / action / required failure (exit_code 1)
|
|
101
|
+
"""
|
|
102
|
+
|
|
103
|
+
success: bool
|
|
104
|
+
data: Optional[Dict[str, Any]] = None
|
|
105
|
+
error: Optional[str] = None
|
|
106
|
+
exit_code: int = 0
|
|
107
|
+
outcome: str = "ok"
|
|
108
|
+
|
|
109
|
+
@classmethod
|
|
110
|
+
def ok(cls, data: Dict[str, Any]) -> "CliResult":
|
|
111
|
+
return cls(success=True, data=data, outcome="ok")
|
|
112
|
+
|
|
113
|
+
@classmethod
|
|
114
|
+
def help(cls) -> "CliResult":
|
|
115
|
+
return cls(success=False, exit_code=0, outcome="help")
|
|
116
|
+
|
|
117
|
+
@classmethod
|
|
118
|
+
def fail(cls, error: str, exit_code: int = 1) -> "CliResult":
|
|
119
|
+
return cls(success=False, error=error, exit_code=exit_code, outcome="error")
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
# src/darwin_cli/constraints.py
|
|
2
|
+
|
|
3
|
+
"""
|
|
4
|
+
Cross-parameter constraint engine.
|
|
5
|
+
|
|
6
|
+
Rules are checked against CLI-provided parameters only (``from_source == "cli"``)
|
|
7
|
+
by default, so values produced by Actions (e.g. date -> start_date/end_date)
|
|
8
|
+
never trigger a false conflict. Pass ``include_generated=True`` on a Constraint
|
|
9
|
+
via config if a rule must also consider Action-produced values.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from typing import Any, Dict, Iterable, List
|
|
13
|
+
|
|
14
|
+
from darwin_cli.actions import ConstraintError
|
|
15
|
+
from darwin_cli.base import Constraint, ParamInfo
|
|
16
|
+
|
|
17
|
+
# ============================================================
|
|
18
|
+
# Source selection
|
|
19
|
+
# ============================================================
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _is_explicit(info: ParamInfo, include_generated: bool = False) -> bool:
|
|
23
|
+
"""Whether a value counts as user-provided for constraint checking."""
|
|
24
|
+
if info is None or info.value is None:
|
|
25
|
+
return False
|
|
26
|
+
if info.from_source == "cli":
|
|
27
|
+
return True
|
|
28
|
+
if include_generated and info.from_source == "action":
|
|
29
|
+
return True
|
|
30
|
+
return False
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _names_in(
|
|
34
|
+
names: Iterable[str],
|
|
35
|
+
current_args: Dict[str, ParamInfo],
|
|
36
|
+
include_generated: bool = False,
|
|
37
|
+
) -> List[str]:
|
|
38
|
+
return [name for name in names if _is_explicit(current_args.get(name), include_generated)]
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
# ============================================================
|
|
42
|
+
# Default English messages
|
|
43
|
+
# ============================================================
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _default_message(constraint: Constraint, given: List[str], missing: List[str]) -> str:
|
|
47
|
+
rule = constraint.rule
|
|
48
|
+
if rule == "mutually_exclusive":
|
|
49
|
+
return f"Parameters {given} are mutually exclusive; provide at most one"
|
|
50
|
+
if rule == "together":
|
|
51
|
+
return f"Parameters {missing} must be provided together with {constraint.params}"
|
|
52
|
+
if rule == "requires":
|
|
53
|
+
return f"Parameter --{constraint.param} requires --{constraint.requires}"
|
|
54
|
+
if rule == "exclusive_with":
|
|
55
|
+
return f"Parameter --{constraint.param} is exclusive with {given}"
|
|
56
|
+
if rule == "at_least_one":
|
|
57
|
+
return f"At least one of {constraint.params} must be provided"
|
|
58
|
+
return f"Constraint '{rule}' violated"
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
# ============================================================
|
|
62
|
+
# Single rule evaluation
|
|
63
|
+
# ============================================================
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def check_constraint(
|
|
67
|
+
constraint: Constraint,
|
|
68
|
+
current_args: Dict[str, ParamInfo],
|
|
69
|
+
) -> None:
|
|
70
|
+
"""Raise ConstraintError if ``constraint`` is violated."""
|
|
71
|
+
include_generated = bool(getattr(constraint, "include_generated", False))
|
|
72
|
+
|
|
73
|
+
given = _names_in(constraint.params, current_args, include_generated)
|
|
74
|
+
violation: List[str] = []
|
|
75
|
+
missing: List[str] = []
|
|
76
|
+
|
|
77
|
+
if constraint.rule == "mutually_exclusive":
|
|
78
|
+
if len(given) > 1:
|
|
79
|
+
violation = given
|
|
80
|
+
|
|
81
|
+
elif constraint.rule == "together":
|
|
82
|
+
if given and len(given) < len(constraint.params):
|
|
83
|
+
missing = [p for p in constraint.params if p not in given]
|
|
84
|
+
|
|
85
|
+
elif constraint.rule == "requires":
|
|
86
|
+
if (
|
|
87
|
+
constraint.param
|
|
88
|
+
and _is_explicit(current_args.get(constraint.param), include_generated)
|
|
89
|
+
and not _is_explicit(current_args.get(constraint.requires), include_generated)
|
|
90
|
+
):
|
|
91
|
+
missing = [constraint.requires]
|
|
92
|
+
|
|
93
|
+
elif constraint.rule == "exclusive_with":
|
|
94
|
+
if constraint.param and _is_explicit(
|
|
95
|
+
current_args.get(constraint.param), include_generated
|
|
96
|
+
):
|
|
97
|
+
others = _names_in(constraint.group, current_args, include_generated)
|
|
98
|
+
if others:
|
|
99
|
+
violation = [constraint.param] + others
|
|
100
|
+
|
|
101
|
+
elif constraint.rule == "at_least_one":
|
|
102
|
+
if not given:
|
|
103
|
+
missing = list(constraint.params)
|
|
104
|
+
|
|
105
|
+
if violation or missing:
|
|
106
|
+
message = constraint.message or _default_message(constraint, violation, missing)
|
|
107
|
+
raise ConstraintError(
|
|
108
|
+
message,
|
|
109
|
+
violations=[
|
|
110
|
+
{
|
|
111
|
+
"rule": constraint.rule,
|
|
112
|
+
"params": constraint.params,
|
|
113
|
+
"given": violation,
|
|
114
|
+
"missing": missing,
|
|
115
|
+
"message": message,
|
|
116
|
+
}
|
|
117
|
+
],
|
|
118
|
+
)
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def check_constraints(
|
|
122
|
+
constraints: List[Constraint],
|
|
123
|
+
current_args: Dict[str, ParamInfo],
|
|
124
|
+
) -> None:
|
|
125
|
+
"""Evaluate all constraints; the first violation raises ConstraintError."""
|
|
126
|
+
for constraint in constraints or []:
|
|
127
|
+
check_constraint(constraint, current_args)
|
darwin_cli/executor.py
ADDED
|
@@ -0,0 +1,428 @@
|
|
|
1
|
+
# src/darwin_cli/executor.py
|
|
2
|
+
|
|
3
|
+
"""
|
|
4
|
+
Deferred execution engine with dependency ordering, dynamic parameters,
|
|
5
|
+
true cycle detection and constraint checking.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from typing import Any, Callable, Dict, List, Optional
|
|
9
|
+
|
|
10
|
+
from darwin_cli.actions import (
|
|
11
|
+
ActionError,
|
|
12
|
+
ActionRegistry,
|
|
13
|
+
CycleDetected,
|
|
14
|
+
GLOBAL_ACTIONS,
|
|
15
|
+
HelpRequested,
|
|
16
|
+
MaxIterationsExceeded,
|
|
17
|
+
RequiredError,
|
|
18
|
+
get_action,
|
|
19
|
+
)
|
|
20
|
+
from darwin_cli.base import ActionResult, Constraint, Param, ParamInfo
|
|
21
|
+
from darwin_cli.constraints import check_constraints
|
|
22
|
+
from darwin_cli.loader import get_param_by_name
|
|
23
|
+
from darwin_cli.validator import Validator
|
|
24
|
+
|
|
25
|
+
USER_SOURCES = ("cli", "action")
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class Executor:
|
|
29
|
+
"""Deferred parameter-processing engine.
|
|
30
|
+
|
|
31
|
+
Responsibilities:
|
|
32
|
+
1. value validation
|
|
33
|
+
2. action execution
|
|
34
|
+
3. dependency ordering with re-queueing
|
|
35
|
+
4. dynamic parameter generation
|
|
36
|
+
5. iteration control and true cycle detection
|
|
37
|
+
6. cross-parameter constraint checking
|
|
38
|
+
"""
|
|
39
|
+
|
|
40
|
+
def __init__(
|
|
41
|
+
self,
|
|
42
|
+
params: List[Param],
|
|
43
|
+
max_iterations: int = 100,
|
|
44
|
+
custom_validators: Optional[Dict[str, Callable]] = None,
|
|
45
|
+
constraints: Optional[List[Constraint]] = None,
|
|
46
|
+
registry: Optional[ActionRegistry] = None,
|
|
47
|
+
):
|
|
48
|
+
self.params = params
|
|
49
|
+
self.max_iterations = max_iterations
|
|
50
|
+
self.custom_validators = custom_validators or {}
|
|
51
|
+
self.constraints = constraints or []
|
|
52
|
+
self.registry = registry if registry is not None else GLOBAL_ACTIONS
|
|
53
|
+
|
|
54
|
+
self._validator: Optional[Validator] = None
|
|
55
|
+
self._dynamic_params: Dict[str, Param] = {}
|
|
56
|
+
self._current_args: Optional[Dict[str, ParamInfo]] = None
|
|
57
|
+
self._dirty_values: set = set()
|
|
58
|
+
self._iteration: int = 0
|
|
59
|
+
|
|
60
|
+
@property
|
|
61
|
+
def current_args(self) -> Optional[Dict[str, ParamInfo]]:
|
|
62
|
+
return self._current_args
|
|
63
|
+
|
|
64
|
+
def _get_validator(self) -> Validator:
|
|
65
|
+
if self._validator is None:
|
|
66
|
+
self._validator = Validator()
|
|
67
|
+
for name, func in self.custom_validators.items():
|
|
68
|
+
self._validator.register_custom(name, func)
|
|
69
|
+
return self._validator
|
|
70
|
+
|
|
71
|
+
def _find_param(self, name: str) -> Optional[Param]:
|
|
72
|
+
if name in self._dynamic_params:
|
|
73
|
+
return self._dynamic_params[name]
|
|
74
|
+
return get_param_by_name(self.params, name)
|
|
75
|
+
|
|
76
|
+
def _get_all_params(self) -> List[Param]:
|
|
77
|
+
return self.params + list(self._dynamic_params.values())
|
|
78
|
+
|
|
79
|
+
def _has_action(self, name: str) -> bool:
|
|
80
|
+
param = self._find_param(name)
|
|
81
|
+
return param is not None and param.action is not None
|
|
82
|
+
|
|
83
|
+
def _is_required(self, name: str) -> bool:
|
|
84
|
+
param = self._find_param(name)
|
|
85
|
+
return param is not None and param.required
|
|
86
|
+
|
|
87
|
+
def _check_required_from_user(
|
|
88
|
+
self,
|
|
89
|
+
param: Param,
|
|
90
|
+
current_args: Dict[str, ParamInfo],
|
|
91
|
+
) -> None:
|
|
92
|
+
if not param.required:
|
|
93
|
+
return
|
|
94
|
+
info = current_args.get(param.name)
|
|
95
|
+
if info is None or info.value is None:
|
|
96
|
+
raise RequiredError(f"Missing required parameter: --{param.name}")
|
|
97
|
+
if info.from_source not in USER_SOURCES:
|
|
98
|
+
raise RequiredError(
|
|
99
|
+
f"Parameter --{param.name} must come from CLI or an Action, "
|
|
100
|
+
f"got source: {info.from_source}"
|
|
101
|
+
)
|
|
102
|
+
|
|
103
|
+
def _resolve_default_value(
|
|
104
|
+
self,
|
|
105
|
+
param: Param,
|
|
106
|
+
current_args: Dict[str, ParamInfo],
|
|
107
|
+
) -> Any:
|
|
108
|
+
if callable(param.default):
|
|
109
|
+
try:
|
|
110
|
+
return param.default(current_args)
|
|
111
|
+
except Exception as e:
|
|
112
|
+
raise ActionError(f"Default value function for '{param.name}' failed: {e}")
|
|
113
|
+
return param.default
|
|
114
|
+
|
|
115
|
+
def _resolve_action(self, param: Param) -> Optional[Callable]:
|
|
116
|
+
if param.action is None:
|
|
117
|
+
return None
|
|
118
|
+
if callable(param.action):
|
|
119
|
+
return param.action
|
|
120
|
+
if self.registry.has(param.action):
|
|
121
|
+
return get_action(param.action, self.registry)
|
|
122
|
+
raise ActionError(f"Action '{param.action}' is not registered (param: {param.name})")
|
|
123
|
+
|
|
124
|
+
# ============================================================
|
|
125
|
+
# True cycle detection over the dependency graph
|
|
126
|
+
# ============================================================
|
|
127
|
+
|
|
128
|
+
def _find_cycle(self, start: str) -> Optional[List[str]]:
|
|
129
|
+
"""DFS from ``start`` following depends_on; return a cycle path if found."""
|
|
130
|
+
WHITE, GRAY, BLACK = 0, 1, 2
|
|
131
|
+
color: Dict[str, int] = {}
|
|
132
|
+
path: List[str] = []
|
|
133
|
+
|
|
134
|
+
def dfs(node: str) -> Optional[List[str]]:
|
|
135
|
+
color[node] = GRAY
|
|
136
|
+
path.append(node)
|
|
137
|
+
param = self._find_param(node)
|
|
138
|
+
deps = param.depends_on if param else None
|
|
139
|
+
for dep in deps or []:
|
|
140
|
+
state = color.get(dep, WHITE)
|
|
141
|
+
if state == GRAY:
|
|
142
|
+
idx = path.index(dep)
|
|
143
|
+
return path[idx:] + [dep]
|
|
144
|
+
if state == WHITE:
|
|
145
|
+
found = dfs(dep)
|
|
146
|
+
if found:
|
|
147
|
+
return found
|
|
148
|
+
path.pop()
|
|
149
|
+
color[node] = BLACK
|
|
150
|
+
return None
|
|
151
|
+
|
|
152
|
+
return dfs(start)
|
|
153
|
+
|
|
154
|
+
# ============================================================
|
|
155
|
+
# Main loop
|
|
156
|
+
# ============================================================
|
|
157
|
+
|
|
158
|
+
def run(self, raw_params: Dict[str, ParamInfo]) -> Dict[str, Any]:
|
|
159
|
+
current_args = raw_params.copy()
|
|
160
|
+
self._current_args = current_args
|
|
161
|
+
self._dirty_values = set()
|
|
162
|
+
self._iteration = 0
|
|
163
|
+
|
|
164
|
+
# Phase 1: help short-circuit
|
|
165
|
+
help_name = "help"
|
|
166
|
+
has_help = help_name in current_args and current_args[help_name].value is True
|
|
167
|
+
has_other_action = False
|
|
168
|
+
for p in self._get_all_params():
|
|
169
|
+
if p.action and p.name != help_name:
|
|
170
|
+
info = current_args.get(p.name)
|
|
171
|
+
if info is not None and info.value is not None:
|
|
172
|
+
has_other_action = True
|
|
173
|
+
break
|
|
174
|
+
|
|
175
|
+
if has_help and not has_other_action:
|
|
176
|
+
self._current_args = current_args
|
|
177
|
+
raise HelpRequested()
|
|
178
|
+
|
|
179
|
+
# Phase 2: default values
|
|
180
|
+
for p in self._get_all_params():
|
|
181
|
+
if p.name == help_name:
|
|
182
|
+
continue
|
|
183
|
+
info = current_args.get(p.name)
|
|
184
|
+
if info is None or (info.value is None and p.default is not None):
|
|
185
|
+
default_value = self._resolve_default_value(p, current_args)
|
|
186
|
+
if default_value is not None:
|
|
187
|
+
if info is None:
|
|
188
|
+
current_args[p.name] = ParamInfo(
|
|
189
|
+
value=default_value,
|
|
190
|
+
defined=True,
|
|
191
|
+
from_source="default",
|
|
192
|
+
)
|
|
193
|
+
else:
|
|
194
|
+
info.value = default_value
|
|
195
|
+
info.from_source = "default"
|
|
196
|
+
|
|
197
|
+
# Phase 3: initial pending queue
|
|
198
|
+
pending = self._build_initial_pending(current_args)
|
|
199
|
+
|
|
200
|
+
# Phase 4: help goes last
|
|
201
|
+
if has_help and help_name in pending:
|
|
202
|
+
pending.remove(help_name)
|
|
203
|
+
pending.append(help_name)
|
|
204
|
+
|
|
205
|
+
# Phase 5: deferred loop
|
|
206
|
+
while pending:
|
|
207
|
+
self._iteration += 1
|
|
208
|
+
if self._iteration > self.max_iterations:
|
|
209
|
+
raise MaxIterationsExceeded(
|
|
210
|
+
f"Exceeded max iterations ({self.max_iterations})"
|
|
211
|
+
)
|
|
212
|
+
|
|
213
|
+
name = pending.pop(0)
|
|
214
|
+
|
|
215
|
+
if name == help_name:
|
|
216
|
+
self._current_args = current_args
|
|
217
|
+
raise HelpRequested()
|
|
218
|
+
|
|
219
|
+
param_info = current_args.get(name)
|
|
220
|
+
if param_info is None or param_info.processed:
|
|
221
|
+
continue
|
|
222
|
+
|
|
223
|
+
param = self._find_param(name)
|
|
224
|
+
if param is None:
|
|
225
|
+
param_info.processed = True
|
|
226
|
+
continue
|
|
227
|
+
|
|
228
|
+
# Step 1: dependencies
|
|
229
|
+
if param.depends_on:
|
|
230
|
+
unsatisfied = self._get_unsatisfied_dependencies(
|
|
231
|
+
name, param.depends_on, current_args
|
|
232
|
+
)
|
|
233
|
+
if unsatisfied:
|
|
234
|
+
cycle = self._find_cycle(name)
|
|
235
|
+
if cycle:
|
|
236
|
+
raise CycleDetected(
|
|
237
|
+
f"Dependency cycle detected: {' -> '.join(cycle)}"
|
|
238
|
+
)
|
|
239
|
+
self._reorder_pending(name, unsatisfied, pending)
|
|
240
|
+
continue
|
|
241
|
+
|
|
242
|
+
# Step 2: validation
|
|
243
|
+
if param_info.value is not None:
|
|
244
|
+
validated = self._get_validator().validate_one(param, param_info.value)
|
|
245
|
+
if validated != param_info.value:
|
|
246
|
+
param_info.value = validated
|
|
247
|
+
|
|
248
|
+
# Step 3: action
|
|
249
|
+
if param.action:
|
|
250
|
+
if param.required and param_info.value is None:
|
|
251
|
+
param_info.processed = True
|
|
252
|
+
continue
|
|
253
|
+
|
|
254
|
+
action_func = self._resolve_action(param)
|
|
255
|
+
if action_func:
|
|
256
|
+
try:
|
|
257
|
+
result = action_func(param_info.value, current_args)
|
|
258
|
+
except HelpRequested:
|
|
259
|
+
raise
|
|
260
|
+
except Exception as e:
|
|
261
|
+
raise ActionError(
|
|
262
|
+
f"Action for parameter '{param.name}' failed: {e}"
|
|
263
|
+
) from e
|
|
264
|
+
|
|
265
|
+
if result is not None:
|
|
266
|
+
if not isinstance(result, ActionResult):
|
|
267
|
+
if isinstance(result, dict):
|
|
268
|
+
result = ActionResult(values=result)
|
|
269
|
+
else:
|
|
270
|
+
raise ActionError(
|
|
271
|
+
f"Action '{param.name}' returned {type(result).__name__}, "
|
|
272
|
+
f"expected ActionResult or dict"
|
|
273
|
+
)
|
|
274
|
+
self._merge_action_result(current_args, result, pending)
|
|
275
|
+
|
|
276
|
+
# Step 4: mark processed
|
|
277
|
+
param_info.processed = True
|
|
278
|
+
|
|
279
|
+
# Phase 5.5: unknown CLI parameters
|
|
280
|
+
valid_names = {p.name for p in self._get_all_params()}
|
|
281
|
+
for key, info in current_args.items():
|
|
282
|
+
if info.from_source == "cli" and key not in valid_names and key != "help":
|
|
283
|
+
raise ActionError(f"Unknown parameter: --{key}")
|
|
284
|
+
|
|
285
|
+
# Phase 6: re-validate only values touched by actions
|
|
286
|
+
for name in self._dirty_values:
|
|
287
|
+
info = current_args.get(name)
|
|
288
|
+
param = self._find_param(name)
|
|
289
|
+
if info is not None and param is not None and info.value is not None:
|
|
290
|
+
validated = self._get_validator().validate_one(param, info.value)
|
|
291
|
+
if validated != info.value:
|
|
292
|
+
info.value = validated
|
|
293
|
+
|
|
294
|
+
# Phase 7: constraints (explicit CLI args only)
|
|
295
|
+
check_constraints(self.constraints, current_args)
|
|
296
|
+
|
|
297
|
+
# Phase 8: required parameters
|
|
298
|
+
for p in self._get_all_params():
|
|
299
|
+
self._check_required_from_user(p, current_args)
|
|
300
|
+
|
|
301
|
+
# Phase 9: return
|
|
302
|
+
self._current_args = current_args
|
|
303
|
+
return {key: info.value for key, info in current_args.items()}
|
|
304
|
+
|
|
305
|
+
# ============================================================
|
|
306
|
+
# Helpers
|
|
307
|
+
# ============================================================
|
|
308
|
+
|
|
309
|
+
def _build_initial_pending(self, current_args: Dict[str, ParamInfo]) -> List[str]:
|
|
310
|
+
pending: List[str] = []
|
|
311
|
+
for p in self._get_all_params():
|
|
312
|
+
if p.name == "help":
|
|
313
|
+
continue
|
|
314
|
+
if p.name not in current_args:
|
|
315
|
+
current_args[p.name] = ParamInfo(value=None, defined=True, from_source="default")
|
|
316
|
+
pending.append(p.name)
|
|
317
|
+
|
|
318
|
+
help_info = current_args.get("help")
|
|
319
|
+
if help_info is not None and help_info.value is True:
|
|
320
|
+
pending.append("help")
|
|
321
|
+
return pending
|
|
322
|
+
|
|
323
|
+
def _get_unsatisfied_dependencies(
|
|
324
|
+
self,
|
|
325
|
+
name: str,
|
|
326
|
+
depends_on: List[str],
|
|
327
|
+
current_args: Dict[str, ParamInfo],
|
|
328
|
+
) -> List[str]:
|
|
329
|
+
unsatisfied: List[str] = []
|
|
330
|
+
for dep in depends_on:
|
|
331
|
+
info = current_args.get(dep)
|
|
332
|
+
if info is None:
|
|
333
|
+
unsatisfied.append(dep)
|
|
334
|
+
continue
|
|
335
|
+
if info.processed:
|
|
336
|
+
continue
|
|
337
|
+
if info.value is not None:
|
|
338
|
+
unsatisfied.append(dep)
|
|
339
|
+
continue
|
|
340
|
+
if info.value is None and self._is_required(dep):
|
|
341
|
+
unsatisfied.append(dep)
|
|
342
|
+
continue
|
|
343
|
+
if info.from_source == "default" and self._has_action(dep):
|
|
344
|
+
unsatisfied.append(dep)
|
|
345
|
+
continue
|
|
346
|
+
if info.value is None and self._has_action(dep):
|
|
347
|
+
unsatisfied.append(dep)
|
|
348
|
+
return unsatisfied
|
|
349
|
+
|
|
350
|
+
def _reorder_pending(self, name, unsatisfied, pending):
|
|
351
|
+
if name in pending:
|
|
352
|
+
pending.remove(name)
|
|
353
|
+
for dep in unsatisfied:
|
|
354
|
+
if dep in pending:
|
|
355
|
+
pending.remove(dep)
|
|
356
|
+
for dep in reversed(unsatisfied):
|
|
357
|
+
pending.insert(0, dep)
|
|
358
|
+
|
|
359
|
+
help_index = next((i for i, p in enumerate(pending) if p == "help"), -1)
|
|
360
|
+
if help_index >= 0:
|
|
361
|
+
pending.insert(help_index, name)
|
|
362
|
+
else:
|
|
363
|
+
pending.insert(len(unsatisfied), name)
|
|
364
|
+
|
|
365
|
+
def _merge_action_result(
|
|
366
|
+
self,
|
|
367
|
+
current_args: Dict[str, ParamInfo],
|
|
368
|
+
result: ActionResult,
|
|
369
|
+
pending: List[str],
|
|
370
|
+
) -> None:
|
|
371
|
+
for key, value in result.values.items():
|
|
372
|
+
if key in current_args:
|
|
373
|
+
existing = current_args[key]
|
|
374
|
+
if existing.value is not None and existing.from_source in ("cli", "action"):
|
|
375
|
+
continue
|
|
376
|
+
if existing.from_source != "cli":
|
|
377
|
+
existing.from_source = "action"
|
|
378
|
+
existing.value = value
|
|
379
|
+
existing.processed = False
|
|
380
|
+
self._dirty_values.add(key)
|
|
381
|
+
if key not in pending:
|
|
382
|
+
pending.append(key)
|
|
383
|
+
else:
|
|
384
|
+
current_args[key] = ParamInfo(
|
|
385
|
+
value=value,
|
|
386
|
+
defined=False,
|
|
387
|
+
from_source="action",
|
|
388
|
+
)
|
|
389
|
+
self._dirty_values.add(key)
|
|
390
|
+
if key not in pending:
|
|
391
|
+
pending.append(key)
|
|
392
|
+
|
|
393
|
+
for new_param in result.params:
|
|
394
|
+
self._dynamic_params[new_param.name] = new_param
|
|
395
|
+
if new_param.name not in current_args:
|
|
396
|
+
default_value = new_param.default
|
|
397
|
+
if callable(default_value):
|
|
398
|
+
try:
|
|
399
|
+
default_value = default_value(current_args)
|
|
400
|
+
except Exception:
|
|
401
|
+
default_value = None
|
|
402
|
+
current_args[new_param.name] = ParamInfo(
|
|
403
|
+
value=default_value,
|
|
404
|
+
defined=True,
|
|
405
|
+
from_source="default",
|
|
406
|
+
)
|
|
407
|
+
else:
|
|
408
|
+
current_args[new_param.name].defined = True
|
|
409
|
+
|
|
410
|
+
# A dynamically discovered parameter may already hold a CLI-provided
|
|
411
|
+
# value (captured as an unknown arg). It must be processed so that
|
|
412
|
+
# validation and actions are applied to it.
|
|
413
|
+
info = current_args[new_param.name]
|
|
414
|
+
if not info.processed:
|
|
415
|
+
self._dirty_values.add(new_param.name)
|
|
416
|
+
if new_param.name not in pending:
|
|
417
|
+
pending.append(new_param.name)
|
|
418
|
+
|
|
419
|
+
if new_param.action:
|
|
420
|
+
if "help" in pending:
|
|
421
|
+
pending.remove("help")
|
|
422
|
+
if new_param.name not in pending:
|
|
423
|
+
pending.append(new_param.name)
|
|
424
|
+
help_info = current_args.get("help")
|
|
425
|
+
if help_info is not None and help_info.value is True:
|
|
426
|
+
pending.append("help")
|
|
427
|
+
|
|
428
|
+
self._current_args = current_args
|