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/parser.py ADDED
@@ -0,0 +1,198 @@
1
+ # src/darwin_cli/parser.py
2
+
3
+ """
4
+ argparse builder + argument parsing with reliable source tracking.
5
+
6
+ Source tracking is done by custom argparse.Action subclasses instead of
7
+ scanning raw argv. This correctly handles ``--key value``, ``--key=value``
8
+ and boolean flags without the O(n^2) argv scan of earlier versions.
9
+ """
10
+
11
+ import argparse
12
+ from typing import Any, Dict, List, Optional
13
+
14
+ from darwin_cli.base import Param, ParamInfo
15
+
16
+ # ============================================================
17
+ # Tracking actions
18
+ # ============================================================
19
+
20
+
21
+ class _TrackingStore(argparse.Action):
22
+ def __call__(self, parser, namespace, values, option_string=None):
23
+ setattr(namespace, self.dest, values)
24
+ setattr(namespace, f"_{self.dest}_source", "cli")
25
+
26
+
27
+ class _TrackingStoreTrue(argparse.Action):
28
+ def __init__(self, option_strings, dest, **kwargs):
29
+ super().__init__(option_strings, dest, nargs=0, **kwargs)
30
+
31
+ def __call__(self, parser, namespace, values, option_string=None):
32
+ setattr(namespace, self.dest, True)
33
+ setattr(namespace, f"_{self.dest}_source", "cli")
34
+
35
+
36
+ class _TrackingStoreFalse(argparse.Action):
37
+ def __init__(self, option_strings, dest, **kwargs):
38
+ super().__init__(option_strings, dest, nargs=0, **kwargs)
39
+
40
+ def __call__(self, parser, namespace, values, option_string=None):
41
+ setattr(namespace, self.dest, False)
42
+ setattr(namespace, f"_{self.dest}_source", "cli")
43
+
44
+
45
+ # ============================================================
46
+ # Parser builder
47
+ # ============================================================
48
+
49
+
50
+ class ParserBuilder:
51
+ def __init__(
52
+ self,
53
+ params: List[Param],
54
+ prog: Optional[str] = None,
55
+ description: Optional[str] = None,
56
+ ):
57
+ self.params = params
58
+ self.prog = prog
59
+ self.description = description
60
+
61
+ def build(self) -> argparse.ArgumentParser:
62
+ parser = argparse.ArgumentParser(
63
+ prog=self.prog,
64
+ description=self.description,
65
+ formatter_class=argparse.RawDescriptionHelpFormatter,
66
+ add_help=False,
67
+ )
68
+ for param in self.params:
69
+ if param.name != "help":
70
+ self._add_argument(parser, param)
71
+ return parser
72
+
73
+ def _add_argument(self, parser: argparse.ArgumentParser, param: Param) -> None:
74
+ kwargs = self._build_kwargs(param)
75
+ parser.add_argument(f"--{param.name}", **kwargs)
76
+
77
+ def _build_kwargs(self, param: Param) -> Dict[str, Any]:
78
+ kwargs: Dict[str, Any] = {
79
+ "help": self._get_help_text(param),
80
+ "dest": param.name,
81
+ }
82
+
83
+ param_type = param.type if isinstance(param.type, str) else "str"
84
+ default = None if callable(param.default) else param.default
85
+
86
+ if param_type == "bool":
87
+ action_cls = _TrackingStoreFalse if default is True else _TrackingStoreTrue
88
+ kwargs["action"] = action_cls
89
+ # argparse's default for a flag with nargs=0 is False/True accordingly.
90
+ kwargs["default"] = default if default is not None else False
91
+ else:
92
+ kwargs["action"] = _TrackingStore
93
+ if param_type == "int":
94
+ kwargs["type"] = int
95
+ elif param_type == "float":
96
+ kwargs["type"] = float
97
+ if default is not None:
98
+ kwargs["default"] = default
99
+
100
+ return kwargs
101
+
102
+ def _get_help_text(self, param: Param) -> str:
103
+ if isinstance(param.help, str):
104
+ return param.help
105
+ if callable(param.help):
106
+ func_name = getattr(param.help, "__name__", "dynamic")
107
+ return f"[dynamic help: {func_name}]"
108
+ return ""
109
+
110
+
111
+ # ============================================================
112
+ # Parsing with metadata
113
+ # ============================================================
114
+
115
+
116
+ def _track_unknown(
117
+ unknown: List[str],
118
+ result: Dict[str, ParamInfo],
119
+ param_names: set,
120
+ ) -> None:
121
+ """Collect unknown ``--key value`` pairs (dynamic params defined later)."""
122
+ i = 0
123
+ while i < len(unknown):
124
+ arg = unknown[i]
125
+ if arg in ("-h", "--help"):
126
+ result["help"] = ParamInfo(value=True, defined=False, processed=False)
127
+ i += 1
128
+ continue
129
+ if arg.startswith("--"):
130
+ key = arg[2:]
131
+ if "=" in key:
132
+ key, value = key.split("=", 1)
133
+ i += 1
134
+ elif i + 1 < len(unknown) and not unknown[i + 1].startswith("--"):
135
+ value = unknown[i + 1]
136
+ i += 2
137
+ else:
138
+ value = True
139
+ i += 1
140
+ if key not in result:
141
+ result[key] = ParamInfo(value=value, defined=key in param_names, processed=False)
142
+ else:
143
+ i += 1
144
+
145
+
146
+ def parse_args_with_meta(
147
+ params: List[Param],
148
+ args: Optional[List[str]] = None,
149
+ prog: Optional[str] = None,
150
+ description: Optional[str] = None,
151
+ ) -> Dict[str, ParamInfo]:
152
+ """Parse arguments and return a dict of ParamInfo with reliable sources.
153
+
154
+ ``from_source`` is "cli" only when argparse's tracking action fired,
155
+ otherwise "default" when a static default exists, or "cli" for unknown
156
+ dynamic arguments that were explicitly supplied on the command line.
157
+ """
158
+ builder = ParserBuilder(params, prog=prog, description=description)
159
+ parser = builder.build()
160
+ parsed, unknown = parser.parse_known_args(args)
161
+
162
+ param_names = {p.name for p in params}
163
+ result: Dict[str, ParamInfo] = {}
164
+
165
+ namespace = vars(parsed)
166
+ for key, value in namespace.items():
167
+ if key.startswith("_"):
168
+ continue
169
+ source = namespace.get(f"_{key}_source")
170
+ if source is None:
171
+ source = "default"
172
+ result[key] = ParamInfo(
173
+ value=value,
174
+ defined=key in param_names,
175
+ from_source=source,
176
+ processed=False,
177
+ )
178
+
179
+ _track_unknown(unknown, result, param_names)
180
+
181
+ for p in params:
182
+ if p.name not in result:
183
+ result[p.name] = ParamInfo(
184
+ value=None,
185
+ defined=True,
186
+ from_source="default",
187
+ processed=False,
188
+ )
189
+
190
+ return result
191
+
192
+
193
+ def build_parser(
194
+ params: List[Param],
195
+ prog: Optional[str] = None,
196
+ description: Optional[str] = None,
197
+ ) -> argparse.ArgumentParser:
198
+ return ParserBuilder(params, prog=prog, description=description).build()
darwin_cli/py.typed ADDED
File without changes
@@ -0,0 +1,147 @@
1
+ # src/darwin_cli/validator.py
2
+
3
+ """
4
+ Value validator: type conversion, rule checks and custom validators.
5
+ """
6
+
7
+ import re
8
+ from typing import Any, Callable, Dict, List, Optional
9
+
10
+ from darwin_cli.actions import ActionError
11
+ from darwin_cli.base import Param, ValidationRule
12
+
13
+ TRUE_VALUES = ("true", "1", "yes", "on", "t")
14
+ FALSE_VALUES = ("false", "0", "no", "off", "f")
15
+
16
+
17
+ class Validator:
18
+ """Validate and coerce a single parameter value."""
19
+
20
+ def __init__(self, params: Optional[List[Param]] = None):
21
+ # ``params`` is accepted for API compatibility but intentionally not
22
+ # stored: each value is validated against the Param passed to
23
+ # validate_one, which also covers parameters discovered at runtime.
24
+ self._custom_validators: Dict[str, Callable] = {}
25
+
26
+ def register_custom(self, name: str, func: Callable) -> None:
27
+ self._custom_validators[name] = func
28
+
29
+ def validate_one(self, param: Param, value: Any) -> Any:
30
+ if value is None and not param.required:
31
+ return value
32
+
33
+ param_type, validation = self._resolve_type_and_validation(param)
34
+ value = self._validate_type(param, param_type, value)
35
+ value = self._validate_rules(param, validation, value)
36
+ value = self._validate_custom(param, validation, value)
37
+ return value
38
+
39
+ def _resolve_type_and_validation(self, param: Param) -> tuple:
40
+ if isinstance(param.type, ValidationRule):
41
+ return "str", param.type
42
+ return param.type, param.validation
43
+
44
+ def _validate_type(self, param: Param, type_name: str, value: Any) -> Any:
45
+ if value is None:
46
+ return value
47
+
48
+ type_map = {"str": str, "int": int, "float": float, "bool": bool}
49
+ expected_type = type_map.get(type_name)
50
+ if expected_type is None:
51
+ return value
52
+
53
+ if type_name == "bool":
54
+ if isinstance(value, bool):
55
+ return value
56
+ if isinstance(value, str):
57
+ lower = value.lower()
58
+ if lower in TRUE_VALUES:
59
+ return True
60
+ if lower in FALSE_VALUES:
61
+ return False
62
+ raise ActionError(
63
+ f"Parameter '{param.name}' type error: expected bool, "
64
+ f"got {type(value).__name__}, value: {value}"
65
+ )
66
+
67
+ try:
68
+ return expected_type(value)
69
+ except (ValueError, TypeError):
70
+ raise ActionError(
71
+ f"Parameter '{param.name}' type error: expected {type_name}, "
72
+ f"got {type(value).__name__}, value: {value}"
73
+ )
74
+
75
+ def _validate_rules(
76
+ self,
77
+ param: Param,
78
+ validation: Optional[ValidationRule],
79
+ value: Any,
80
+ ) -> Any:
81
+ if value is None or validation is None:
82
+ return value
83
+
84
+ if validation.choices is not None and value not in validation.choices:
85
+ choices_str = ", ".join(str(c) for c in validation.choices)
86
+ raise ActionError(
87
+ f"Parameter '{param.name}' value '{value}' is not in choices: [{choices_str}]"
88
+ )
89
+
90
+ if isinstance(value, (int, float)):
91
+ if validation.min is not None and value < validation.min:
92
+ raise ActionError(
93
+ f"Parameter '{param.name}' value {value} is below minimum {validation.min}"
94
+ )
95
+ if validation.max is not None and value > validation.max:
96
+ raise ActionError(
97
+ f"Parameter '{param.name}' value {value} is above maximum {validation.max}"
98
+ )
99
+
100
+ if isinstance(value, str):
101
+ if validation.min_length is not None and len(value) < validation.min_length:
102
+ raise ActionError(
103
+ f"Parameter '{param.name}' length {len(value)} is below minimum "
104
+ f"{validation.min_length}"
105
+ )
106
+ if validation.max_length is not None and len(value) > validation.max_length:
107
+ raise ActionError(
108
+ f"Parameter '{param.name}' length {len(value)} is above maximum "
109
+ f"{validation.max_length}"
110
+ )
111
+ if validation.pattern is not None and not re.match(validation.pattern, value):
112
+ raise ActionError(
113
+ f"Parameter '{param.name}' value '{value}' does not match pattern: "
114
+ f"{validation.pattern}"
115
+ )
116
+
117
+ return value
118
+
119
+ def _validate_custom(
120
+ self,
121
+ param: Param,
122
+ validation: Optional[ValidationRule],
123
+ value: Any,
124
+ ) -> Any:
125
+ if value is None or validation is None or validation.custom is None:
126
+ return value
127
+
128
+ name = validation.custom
129
+ if name not in self._custom_validators:
130
+ raise ActionError(f"Custom validator '{name}' is not registered (param: {param.name})")
131
+
132
+ func = self._custom_validators[name]
133
+ try:
134
+ result = func(value)
135
+ except Exception as e:
136
+ raise ActionError(f"Parameter '{param.name}' custom validation failed: {e}")
137
+ return result if result is not None else value
138
+
139
+
140
+ def create_validator(
141
+ params: Optional[List[Param]] = None,
142
+ custom_validators: Optional[Dict[str, Callable]] = None,
143
+ ) -> Validator:
144
+ validator = Validator(params)
145
+ for name, func in (custom_validators or {}).items():
146
+ validator.register_custom(name, func)
147
+ return validator