darwin-cli 0.1.0__tar.gz

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.
@@ -0,0 +1,503 @@
1
+ Metadata-Version: 2.3
2
+ Name: darwin-cli
3
+ Version: 0.1.0
4
+ Summary: Declaration-driven CLI engine with dynamic params, dependency inference and config-file constraints
5
+ Author: darwinalpha
6
+ Author-email: darwinalpha <13301807038@126.com>
7
+ Requires-Dist: pytest>=7.0 ; extra == 'test'
8
+ Requires-Python: >=3.10
9
+ Provides-Extra: test
10
+ Description-Content-Type: text/markdown
11
+
12
+ # darwin-cli
13
+
14
+ [English](README.md) · [简体中文](README.cn.md)
15
+
16
+ A **declaration-driven CLI engine**: parameters are not passive slots waiting
17
+ for a value. They can compute values, infer other parameters, declare new
18
+ parameters at runtime, and enforce relationships with each other — all from a
19
+ config file if you want.
20
+
21
+ - **Zero third-party dependencies in the core** — only the Python standard library
22
+ - One DSL for everything: static params, Actions, dynamic params, dependency
23
+ ordering, validation, and cross-parameter constraints
24
+ - **Config-file driven**: `CliApp.from_config()` reads `cli_args` / `constraints`
25
+ from JSON, a dict, or any loader callback
26
+ - **Optional darwin-config adapter** for keeping params in a layered config file
27
+ (see section 6)
28
+ - A **small, stable API**: `CliApp`, `Param`, `ActionResult`, `CliResult`,
29
+ `register_action`, plus a handful of helpers
30
+
31
+ ```bash
32
+ pip install darwin-cli
33
+ ```
34
+
35
+ Python >= 3.10.
36
+
37
+ ---
38
+
39
+ ## 1. At a glance: what an app looks like
40
+
41
+ The same parameter declaration in three equivalent forms.
42
+
43
+ **`fetch.json`** — everything in a config file:
44
+
45
+ ```json
46
+ {
47
+ "prog": "fetch.py",
48
+ "help": "Fetch market data",
49
+ "cli_args": {
50
+ "type": {
51
+ "type": "str",
52
+ "required": true,
53
+ "action": "load_dynamic_params",
54
+ "depends_on": ["source"],
55
+ "help": "Data type"
56
+ },
57
+ "source": { "type": "str", "action": "guess_source" },
58
+ "date": { "type": "str" },
59
+ "year": { "type": "str" }
60
+ },
61
+ "constraints": [
62
+ { "rule": "mutually_exclusive", "params": ["date", "year"] }
63
+ ]
64
+ }
65
+ ```
66
+
67
+ **Python dict** — callables allowed:
68
+
69
+ ```python
70
+ from darwin_cli import CliApp
71
+
72
+ app = CliApp.from_config({
73
+ "cli_args": {
74
+ "type": {"required": True, "action": load_dynamic_params, "depends_on": ["source"]},
75
+ "source": {"action": guess_source},
76
+ "date": {},
77
+ "year": {},
78
+ },
79
+ "constraints": [{"rule": "mutually_exclusive", "params": ["date", "year"]}],
80
+ })
81
+ ```
82
+
83
+ **Param objects** — full control:
84
+
85
+ ```python
86
+ from darwin_cli import CliApp, Param
87
+
88
+ app = CliApp(
89
+ params=[
90
+ Param(name="type", required=True, action=load_dynamic_params, depends_on=["source"]),
91
+ Param(name="source", action=guess_source),
92
+ Param(name="date"),
93
+ Param(name="year"),
94
+ ],
95
+ constraints=[{"rule": "mutually_exclusive", "params": ["date", "year"]}],
96
+ prog="fetch.py",
97
+ )
98
+ ```
99
+
100
+ What the engine does for you:
101
+
102
+ ```python
103
+ @register_action("guess_source")
104
+ def guess_source(value, ctx):
105
+ if value is not None: # user supplied --source: do not interfere
106
+ return {}
107
+ return {"source": "tushare"} # otherwise infer it
108
+
109
+ @register_action("load_dynamic_params")
110
+ def load_dynamic_params(value, ctx):
111
+ return ActionResult(params=[ # declare params that did not exist at startup
112
+ Param(name="symbol", type=ValidationRule(pattern=r"^\d{6}\.(SH|SZ)$"), required=True),
113
+ Param(name="fields", default="close"),
114
+ ])
115
+
116
+ result = app.run(["--type", "stock_daily", "--symbol", "600000.SH"])
117
+ print(result.outcome, result.data)
118
+ # ok {'type': 'stock_daily', 'source': 'tushare', 'symbol': '600000.SH', 'fields': 'close'}
119
+ ```
120
+
121
+ `--source` was inferred, `symbol` / `fields` did not exist when parsing started,
122
+ and `--date` / `--year` cannot both be used — none of that required an
123
+ `if/else` in `main()`.
124
+
125
+ > `examples/` contains 8 runnable scenarios with a demo script. Run
126
+ > `python examples/demo.py` from the repository root.
127
+
128
+ ---
129
+
130
+ ## 2. Syntax quick reference
131
+
132
+ ### `Param` fields
133
+
134
+ | Field | Type | Meaning |
135
+ | --- | --- | --- |
136
+ | `name` | `str` | CLI name (`--name`); also the key in `cli_args` |
137
+ | `type` | `"str" \| "int" \| "float" \| "bool"` or `ValidationRule` | A rule object implies `str` |
138
+ | `required` | `bool` | Must come from the CLI or an Action — **not** from a default |
139
+ | `default` | value or `Callable(ctx)` | Static value, or a function evaluated during execution |
140
+ | `help` | `str` or `Callable(ctx)` | Static text, or help generated from the current context |
141
+ | `action` | name or `Callable(value, ctx)` | Registered Action name, or a function directly |
142
+ | `validation` | `ValidationRule` | Extra rules when `type` is a string |
143
+ | `depends_on` | `list[str]` | Parameters that must be processed before this one |
144
+
145
+ ### `ValidationRule` fields
146
+
147
+ | Field | Applies to | Check |
148
+ | --- | --- | --- |
149
+ | `choices` | any | value must be in the list |
150
+ | `min` / `max` | numbers | inclusive numeric bounds |
151
+ | `min_length` / `max_length` | strings | inclusive length bounds |
152
+ | `pattern` | strings | `re.match` (prefix match — anchor with `$` for exact match) |
153
+ | `custom` | any | name of a validator registered via `custom_validators=...` |
154
+
155
+ Type coercion happens before rules: `str` casts with `str()`, `int` / `float`
156
+ with their constructors, and `bool` accepts `true/1/yes/on/t` and
157
+ `false/0/no/off/f` (lowercase strings only). `None` is returned unchanged for
158
+ optional params — required checks live in the executor, not the validator.
159
+
160
+ ### `Constraint` rules (config top-level `constraints`)
161
+
162
+ | Rule | Config | Meaning |
163
+ | --- | --- | --- |
164
+ | `mutually_exclusive` | `{"rule":"mutually_exclusive","params":["date","year"]}` | at most one |
165
+ | `together` | `{"rule":"together","params":["user","token"]}` | all or none |
166
+ | `requires` | `{"rule":"requires","param":"type","requires":"source"}` | A present implies B present |
167
+ | `exclusive_with` | `{"rule":"exclusive_with","param":"date","group":["start_date","end_date"]}` | A excludes a whole group |
168
+ | `at_least_one` | `{"rule":"at_least_one","params":["source","file"]}` | at least one must be present |
169
+
170
+ Optional keys on any rule: `"message"` (override the default English error) and
171
+ `"include_generated": true` (also count Action-produced values, not just CLI
172
+ args). By default **only explicitly supplied CLI arguments are checked**, so an
173
+ Action expanding `date → start_date/end_date` never triggers a false conflict.
174
+
175
+ ### `ActionResult` and `CliResult`
176
+
177
+ | Type | Fields | Purpose |
178
+ | --- | --- | --- |
179
+ | `ActionResult` | `values: dict`, `params: list[Param]` | backfill values and/or declare new parameters |
180
+ | `CliResult` | `success`, `data`, `error`, `exit_code`, `outcome` | result of `run()`; `outcome` is `ok` / `help` / `error` |
181
+
182
+ `ParamInfo.from_source` is the decision key throughout: `"cli"` (explicit user
183
+ argument), `"default"` (static/callable default), or `"action"` (produced by an
184
+ Action).
185
+
186
+ ---
187
+
188
+ ## 3. Core APIs in practice
189
+
190
+ ### `CliApp(params, ..., constraints=..., registry=...)`
191
+
192
+ The facade. `params` accepts `list[Param]` or a dict of declarations.
193
+ Other constructor arguments:
194
+
195
+ ```python
196
+ app = CliApp(
197
+ params=[...],
198
+ prog="fetch.py", # program name in help
199
+ help="Fetch market data", # also accepts description=
200
+ max_iterations=100, # safety net for the deferred loop
201
+ action_modules=["myapp.actions"], # import modules that register Actions
202
+ custom_validators={"even": lambda v: ...},
203
+ available_sources=["tushare", "yahoo"], # listed in global help
204
+ constraints=[...],
205
+ registry=ActionRegistry(), # omit for the global registry
206
+ )
207
+ ```
208
+
209
+ Useful attributes after a run: `app.params` (static + dynamic),
210
+ `app.static_params`, `app.dynamic_params`, `app.get_param(name)`.
211
+
212
+ ### `CliApp.from_config(config, prog=None, help=None, loader=None, mount=None, **kwargs)`
213
+
214
+ ```python
215
+ app = CliApp.from_config("config/fetch.json") # JSON, stdlib only
216
+ app = CliApp.from_config({"cli_args": {...}}) # dict
217
+ app = CliApp.from_config("fetcher.cli", loader=my_loader) # custom source
218
+ app = CliApp.from_config("settings.json", mount="fetcher.cli") # nested section
219
+ ```
220
+
221
+ `mount` walks a dotted path into the loaded dict before extracting `cli_args`
222
+ (or `params`), `constraints`, `prog` and `help`. `loader` is any callable that
223
+ turns the string into a dict; without one, the string is treated as a JSON path.
224
+
225
+ ### `run(args=None)` and `run_or_exit(args=None)`
226
+
227
+ ```python
228
+ result = app.run(["--type", "stock_daily"])
229
+ if result.outcome == "ok":
230
+ handle(result.data)
231
+ elif result.outcome == "help":
232
+ pass # help text already printed; exit_code == 0
233
+ else:
234
+ log(result.error) # exit_code == 1
235
+
236
+ data = app.run_or_exit() # reads sys.argv[1:]; exits on any non-ok outcome
237
+ ```
238
+
239
+ `run()` **never exits the process** — it returns a `CliResult`, which makes the
240
+ app easy to embed and test. `CliResult.ok(data)`, `CliResult.help()` and
241
+ `CliResult.fail(error, exit_code=1)` are the factory helpers.
242
+
243
+ ### `register_action(name, *, registry=None)` and `ActionRegistry`
244
+
245
+ ```python
246
+ from darwin_cli import ActionRegistry, register_action
247
+
248
+ @register_action("guess_source") # global registry
249
+ def guess_source(value, ctx): ...
250
+
251
+ reg = ActionRegistry() # isolated registry for one app
252
+ @register_action("guess_source", registry=reg)
253
+ def isolated(value, ctx): ...
254
+
255
+ app = CliApp(params=[...], registry=reg)
256
+ ```
257
+
258
+ `has_action` / `get_action` / `list_actions` / `clear_actions` all accept the
259
+ same optional `registry`. `ACTION_REGISTRY` and `GLOBAL_ACTIONS` both point to
260
+ the process-wide registry. `load_actions_from_module(path)` imports a module so
261
+ its decorators run; `validate_before(fn)` wraps an Action with a pre-check.
262
+
263
+ ### `ActionResult` — the return value of an Action
264
+
265
+ ```python
266
+ @register_action("expand_year")
267
+ def expand_year(value, ctx):
268
+ if value is None:
269
+ return {}
270
+ return ActionResult(
271
+ values={"start_date": f"{value}-01-01", "end_date": f"{value}-12-31"},
272
+ params=[Param(name="start_date"), Param(name="end_date")],
273
+ )
274
+ ```
275
+
276
+ Returning a plain dict is shorthand for `ActionResult(values=that_dict)`.
277
+ `values` fills or overwrites values; `params` gives the new names a formal
278
+ definition so they take part in validation, help, and further processing.
279
+
280
+ ### Validation helpers
281
+
282
+ ```python
283
+ from darwin_cli import Validator, create_validator, parse_args_with_meta, build_parser
284
+
285
+ validator = create_validator(custom_validators={"even": lambda v: v if v % 2 == 0 else None})
286
+ validator.validate_one(Param(name="n", type="int"), "4") # -> 4
287
+
288
+ meta = parse_args_with_meta(params, ["--type=stock_daily", "--count", "3"])
289
+ meta["type"].from_source # 'cli'
290
+ meta["count"].from_source # 'cli'
291
+ parser = build_parser(params, prog="fetch.py")
292
+ ```
293
+
294
+ `parse_params_from_config`, `parse_constraints`, `merge_params`,
295
+ `params_to_dict`, `get_param_by_name`, `check_constraint` and
296
+ `check_constraints` are also exported for building custom front-ends.
297
+
298
+ ### Exceptions
299
+
300
+ `ActionError`, `ConflictError` (subclass), `ConstraintError` (subclass, with
301
+ `.violations`), `CycleDetected` (subclass), `HelpRequested`,
302
+ `MaxIterationsExceeded`, `RequiredError`. All error messages are English;
303
+ `CliApp.run()` converts them into a `CliResult` and prints contextual help.
304
+
305
+ ---
306
+
307
+ ## 4. Features in detail
308
+
309
+ ### 4.1 Exact source tracking
310
+
311
+ `--key value`, `--key=value` and bare `--flag` are all recorded by custom
312
+ `argparse.Action` subclasses, not by scanning raw `argv`. So
313
+ `from_source == "cli"` is reliable — the earlier O(n²) argv scan used to
314
+ mislabel `--key=value`. This matters for three decisions: required checks,
315
+ constraint checks, and whether an Action may overwrite a value.
316
+
317
+ ### 4.2 Dynamic parameters
318
+
319
+ An Action can return `ActionResult(params=[...])`. The executor registers the
320
+ new definitions in the middle of a run. A value supplied on the command line for
321
+ a not-yet-declared name is captured as an unknown argument, then formally
322
+ validated once the definition appears. This is the capability `argparse` cannot
323
+ offer: its parameter set is frozen before parsing starts.
324
+
325
+ ```python
326
+ r = app.run(["--type", "stock_daily", "--symbol", "600000.SH"])
327
+ # tushare branch declares symbol+fields; yahoo branch declares symbol+interval
328
+ ```
329
+
330
+ ### 4.3 `depends_on` and real cycle detection
331
+
332
+ When a parameter's dependencies are not yet processed, it is put back into the
333
+ queue behind them. Declaration order does not matter. Cycles are found by a DFS
334
+ over the `depends_on` graph (three-color marking) and reported with the actual
335
+ path, e.g. `Dependency cycle detected: a -> b -> c -> a` → `CycleDetected`.
336
+ `max_iterations` remains as a safety net for runaway chains.
337
+
338
+ ### 4.4 Value expansion and chaining
339
+
340
+ Values written by an Action are marked dirty and re-queued, so `A` producing `B`
341
+ producing `C` converges automatically. Write Actions idempotently
342
+ (`if value is not None: return {}`) because a parameter may be revisited.
343
+
344
+ ### 4.5 Validation
345
+
346
+ Coercion → `ValidationRule` checks → custom validator, in that order. A rule
347
+ object used as `type` implies `str` coercion first. `pattern` uses `re.match`,
348
+ so `"^\\d{6}\\.SH$"` matches exactly while `"^\\d{6}\\.SH"` also allows a
349
+ suffix. Custom validators are registered with
350
+ `CliApp(custom_validators={...})` and referenced by name from `ValidationRule.custom`.
351
+
352
+ ### 4.6 Cross-parameter constraints
353
+
354
+ Relationships between parameters are declared in config rather than written as
355
+ Actions. Constraints run **after** the deferred loop (so all generated values
356
+ exist) but **before** required checks, and by default inspect only `cli`-sourced
357
+ values:
358
+
359
+ ```python
360
+ r = app.run(["--date", "2026-01-01", "--year", "2026"])
361
+ # CliResult(outcome='error', error="Parameters ['date', 'year'] are mutually exclusive; ...")
362
+ ```
363
+
364
+ Use `"include_generated": true` on a rule when Action-produced values must
365
+ count. Complex, business-specific conditions (lookups, multi-step computation)
366
+ still belong in Actions; the two mechanisms coexist.
367
+
368
+ ### 4.7 Context-aware help
369
+
370
+ `--help` is moved to the **end** of the queue. With `--help` alone the engine
371
+ shows global help immediately; combined with other arguments it first runs
372
+ inference and dynamic-param discovery, then shows scenario help:
373
+
374
+ ```text
375
+ $ python fetch.py --help
376
+ Usage: fetch.py [global options]
377
+ Global options:
378
+ --type <str> [required]
379
+ --source <str>
380
+ --help Show this help message
381
+
382
+ $ python fetch.py --type stock_daily --help
383
+ Usage: fetch.py --source tushare [options]
384
+ Source: tushare
385
+ Options:
386
+ --type <str> [required]
387
+ (dynamic) --symbol <str> [required] pattern: ^\d{6}\.(SH|SZ)$
388
+ --help Show this help message
389
+ ```
390
+
391
+ A `help` value may be a `Callable(ctx)`; if it raises, the line degrades to
392
+ `(help generation failed: ...)` instead of breaking the whole run. Note that a
393
+ help request returns `success=False` with `exit_code=0` — use `outcome == "help"`
394
+ to distinguish it from an error.
395
+
396
+ ### 4.8 Isolated Action registries
397
+
398
+ The global registry is convenient but process-wide. Pass `registry=ActionRegistry()`
399
+ to `CliApp` and `register_action(..., registry=reg)` to keep multiple apps in one
400
+ process from colliding on Action names. Omitting it keeps the classic
401
+ `@register_action("name")` behaviour.
402
+
403
+ ---
404
+
405
+ ## 5. Execution pipeline and precedence
406
+
407
+ `Executor.run()` is a deferred loop, not a one-pass parse.
408
+
409
+ | # | Phase | What happens |
410
+ | --- | --- | --- |
411
+ | 1 | Help short-circuit | `--help` with no other actionable input → global help immediately |
412
+ | 2 | Defaults | apply static / callable defaults; source becomes `default` |
413
+ | 3 | Pending queue | every declared parameter is queued |
414
+ | 4 | Help goes last | `--help` is moved to the tail so inference runs first |
415
+ | 5 | Deferred loop | pop → dependency check (requeue or raise `CycleDetected`) → validate → Action → merge `ActionResult` (new `params` are queued too) → mark processed |
416
+ | 6 | Unknown args | CLI args that never received a definition → `ActionError: Unknown parameter: --x` |
417
+ | 7 | Re-validation | re-check only values touched by Actions |
418
+ | 8 | Constraints | evaluate cross-parameter rules (explicit CLI args by default) |
419
+ | 9 | Required | value must exist and come from `cli` or `action` |
420
+ | — | Return | `{name: value}` wrapped in `CliResult` |
421
+
422
+ **Value precedence (high → low)**: an existing CLI or Action-produced value is
423
+ never overwritten by a later Action → a new Action value → static / callable
424
+ default. When an Action declares a parameter that already holds a CLI value, the
425
+ value is kept and the definition is attached.
426
+
427
+ **Gotchas worth knowing**
428
+
429
+ 1. `required=True` together with a static `default` still fails: defaults are not
430
+ a valid source for required values ("must come from CLI or an Action").
431
+ 2. A plain dict returned by an Action is treated as `values`; only
432
+ `ActionResult(params=...)` declares new parameters.
433
+ 3. `pattern` is a prefix match (`re.match`); anchor with `$`.
434
+ 4. Bool flags: `default=True` makes `--flag` set `False`, otherwise `--flag`
435
+ sets `True`.
436
+ 5. `CliApp.run()` prints help / error help to stdout; capture it if you embed
437
+ the app in another program.
438
+ 6. `constraints` are checked before `required`, so a missing required param can
439
+ also surface as an `at_least_one` violation.
440
+
441
+ ---
442
+
443
+ ## 6. Ecosystem integration
444
+
445
+ ### darwin-config (optional adapter)
446
+
447
+ Keep parameter declarations in a JSON / YAML / TOML config managed by
448
+ [darwin-config](https://github.com/darwinalpha/darwin-config). The adapter lives
449
+ in `darwin_cli.integrations.darwin_config` and is **not imported by the core**:
450
+ importing it is what pulls in darwin-config, so `darwin-cli` itself stays
451
+ dependency-free.
452
+
453
+ ```python
454
+ from darwin_cli.integrations.darwin_config import from_config, from_file, get_loader
455
+
456
+ app = from_config("fetcher.cli", prog="fetch.py") # dotted key
457
+ app = from_file("config/settings.yaml", mount="fetcher", prog="fetch.py")
458
+ app = CliApp.from_config("cli", loader=get_loader("fetcher"), prog="fetch.py")
459
+ ```
460
+
461
+ `from_config` reads a dotted key via `get_config`, `from_file` initialises
462
+ darwin-config from a file first, and `get_loader` returns a loader callback for
463
+ `CliApp.from_config`. Any of these can be combined with `mount` to select a
464
+ sub-tree.
465
+
466
+ ### Other consumers
467
+
468
+ `darwin-fetch` consumes this library to build data-fetching CLIs. When
469
+ migrating from `darwin_common.cli`, the API names are unchanged — only the
470
+ package name differs. New capabilities (`constraints`, `from_config`,
471
+ `outcome`, instance registries) require importing `darwin_cli`.
472
+
473
+ ### When not to use it
474
+
475
+ This is **not** a general-purpose CLI framework competitor. For a script with a
476
+ few fixed options, `argparse` or `click` is simpler; for subcommands, shell
477
+ completion and coloured help, use `click` / `typer`. darwin-cli targets tools
478
+ whose parameter set changes with context: swappable data sources, dynamic
479
+ parameter discovery, inference and chained dependencies between parameters.
480
+ See `docs/by-example.md` for a scenario-by-scenario comparison.
481
+
482
+ ---
483
+
484
+ ## 7. Tests
485
+
486
+ ```bash
487
+ pip install -e '.[test]'
488
+ pytest tests -q
489
+ # or: uv run --extra test python -m pytest tests -q
490
+ ```
491
+
492
+ Tests are split into `tests/unit/` (one file per module: base, actions, loader,
493
+ parser, validator, executor, help, app, constraints, registry, source tracking,
494
+ cycle detection, config integration) and `tests/integration/` (end-to-end fetch
495
+ workflows, complex chains, and `test_examples.py`, which executes every config
496
+ under `examples/`). All error-message assertions are in English.
497
+
498
+ Samples in `examples/` are covered by integration tests, so they stay
499
+ executable documentation.
500
+
501
+ ## 8. License
502
+
503
+ MIT