darwin-config 0.2.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,356 @@
1
+ Metadata-Version: 2.3
2
+ Name: darwin-config
3
+ Version: 0.2.0
4
+ Summary: Layered, recursive configuration loader for JSON and YAML with variables, refs and schema validation
5
+ Author: Hong
6
+ Author-email: Hong <sardineclub@126.com>
7
+ Requires-Dist: pytest>=7.0 ; extra == 'test'
8
+ Requires-Dist: pyyaml>=6.0 ; extra == 'yaml'
9
+ Requires-Python: >=3.12
10
+ Provides-Extra: test
11
+ Provides-Extra: yaml
12
+ Description-Content-Type: text/markdown
13
+
14
+ # darwin-config
15
+
16
+ [English](README.md) · [简体中文](README.cn.md)
17
+
18
+ A layered, recursive JSON / YAML configuration loader: declare where values come from, how they merge, how they are validated and referenced — all in one file. The library takes care of the rest.
19
+
20
+ - **Zero third-party dependencies in the core**; YAML is an optional extra
21
+ - One DSL covers everything: layered imports, template merges, environment variables, in-file / cross-file references, arithmetic expressions, and schema validation
22
+ - **A small, well-defined API**: load, read, override, alias, validate and trace — no redundant state-management helpers
23
+
24
+ ```bash
25
+ pip install darwin-config # JSON works out of the box
26
+ pip install 'darwin-config[yaml]' # add YAML support
27
+ ```
28
+
29
+ Python >= 3.12.
30
+
31
+ ---
32
+
33
+ ## 1. At a glance: what a config file looks like
34
+
35
+ The same configuration in equivalent JSON and YAML. Directives are **bare keywords**: `import` / `merge` / `mount` / `schema`:
36
+
37
+ **`settings.yaml`**
38
+
39
+ ```yaml
40
+ import: # 1) import base layers first; multiple allowed, later ones override earlier ones
41
+ - base.yaml
42
+ schema: # 2) validate + fill defaults (port is missing below, so 5432 is filled in)
43
+ database.host: { type: string, required: true }
44
+ database.port: { type: integer, default: 5432, min: 1, max: 65535 }
45
+
46
+ database:
47
+ host: ${DB_HOST:localhost} # 3) environment variable: values > env > default
48
+ # port is filled in by the schema
49
+ dsn: "postgresql://${this.database.host}:${this.database.port}/app" # 4) in-file reference
50
+ pool:
51
+ merge: ${this.defaults.pool} # 5) reuse another object in this file as a template
52
+ max: 50
53
+
54
+ # Template object (not meant to be a standalone config; used only as a merge source)
55
+ defaults:
56
+ pool: { min: 1, max: 10, timeout: 30 }
57
+
58
+ app:
59
+ retry: 3
60
+ interval: 2
61
+ budget: "%{calc: ${this.app.retry} * ${this.app.interval} }" # 6) arithmetic (quote it in YAML)
62
+ ```
63
+
64
+ ```python
65
+ from darwin_config import init_config, get_config
66
+
67
+ init_config(files=["settings.yaml"], mount="config", validate=True)
68
+
69
+ get_config("config.database.dsn") # 'postgresql://localhost:5432/app'
70
+ get_config("config.database.pool") # {'min': 1, 'max': 50, 'timeout': 30}
71
+ get_config("config.app.budget") # 6
72
+ ```
73
+
74
+ **Equivalent JSON** (`%{calc: ...}` needs no quotes here):
75
+
76
+ ```json
77
+ {
78
+ "import": ["base.json"],
79
+ "schema": {
80
+ "database.host": { "type": "string", "required": true },
81
+ "database.port": { "type": "integer", "default": 5432, "min": 1, "max": 65535 }
82
+ },
83
+ "database": {
84
+ "host": "${DB_HOST:localhost}",
85
+ "dsn": "postgresql://${this.database.host}:${this.database.port}/app",
86
+ "pool": { "merge": "${this.defaults.pool}", "max": 50 }
87
+ },
88
+ "defaults": { "pool": { "min": 1, "max": 10, "timeout": 30 } },
89
+ "app": {
90
+ "retry": 3,
91
+ "interval": 2,
92
+ "budget": "%{calc: ${this.app.retry} * ${this.app.interval} }"
93
+ }
94
+ }
95
+ ```
96
+
97
+ > `examples/` contains 8 pairs of equivalent JSON/YAML samples and a runnable demo. Run `PYTHONPATH=src py -3.12 examples/demo.py` to see every capability in action.
98
+
99
+ ---
100
+
101
+ ## 2. Syntax quick reference
102
+
103
+ | Syntax | Meaning | Resolved at |
104
+ | --- | --- | --- |
105
+ | `import: "base.yaml"` / `import: [...]` | Import other configs, resolved relative to the current file; nesting is supported. Later imports override earlier ones; the current file overrides all imports | Load time |
106
+ | `merge: ${this.templates.http}` / `[...]` | Deep-merge another object in the same file into the current one; the current object's fields win | Load time |
107
+ | `mount: adapter.tushare` | Declare the mount point of a file (top level only; used by `add_config`) | Load time |
108
+ | `schema: {...}` / `schema: "rules.json"` | Validation rules, inline or from an external file (top level only; external files may themselves use `import`) | Load time, before env substitution |
109
+ | `${this.a.b}` | In-file reference; references can chain | Load time |
110
+ | `${root.a.b}` | Global config-tree reference, works across files; **resolved on read at runtime** | Runtime |
111
+ | `${VAR}` / `${VAR:default}` | Environment variable; precedence: `values` > `os.environ` > default; missing without a default raises an error | Load time (any leftover at runtime is resolved once more by the node) |
112
+ | `%{calc: expr}` | Restricted arithmetic; only `+ - * / // % **` and whitelisted functions (`abs/min/max/round/sum/len/int/float/str/bool`) | Runtime |
113
+ | `~import` / `~schema`, etc. | The `~` prefix escapes a reserved word into an ordinary business field (unescaped at the end of the pipeline) | Load time |
114
+ | `{param}` | Business template placeholder, kept as-is and never touched by env substitution | — |
115
+
116
+ **Two YAML gotchas** (JSON does not have these):
117
+
118
+ 1. `%{calc: ...}` must be quoted: `total: "%{calc: ${this.a} * 2}"`, otherwise `: ` is treated as a mapping separator by YAML.
119
+ 2. `${...}` inside a flow sequence must be quoted: `merge: ["${this.tpl}"]`. Written bare as `[${this.tpl}]`, YAML treats `{` as the start of a mapping and parsing fails. Bare use in a plain scalar is safe: `url: ${this.host}/v1`.
120
+
121
+ ---
122
+
123
+ ## 3. Five core APIs in practice
124
+
125
+ ### `init_config(files, mount="", values=None, validate=False, base_dir=None, directives=None)`
126
+
127
+ Initialize the global configuration system: expand globs, load files in order, merge them, and build the node tree. **Every call resets all previous state.**
128
+
129
+ ```python
130
+ from darwin_config import init_config
131
+
132
+ # Multiple files: later files override earlier ones; globs and ${VAR} path variables both work
133
+ init_config(
134
+ files=["config/base.yaml", "config/env/${APP_ENV:dev}/*.json"],
135
+ mount="config", # mount everything under config.*; empty means the root
136
+ values={"APP_ENV": "prod"}, # injected variables, higher priority than env vars
137
+ validate=True, # enable schema validation and default filling
138
+ base_dir="config", # base directory for relative paths; defaults to cwd
139
+ directives={"import": "cfg_import"}, # optional: rename a reserved word
140
+ )
141
+ ```
142
+
143
+ ### `get_config(path="", default=None, raise_on_not_found=False)`
144
+
145
+ Read a value. A whole-string `${root.xxx}` expression is resolved on read, so it can reference config added **later**.
146
+
147
+ ```python
148
+ from darwin_config import get_config, ConfigPathNotFoundError
149
+
150
+ get_config("config.database.host") # 'localhost'
151
+ get_config("config.database.timeout", default=30) # fallback when missing
152
+ get_config("config.database") # whole subtree (dict)
153
+ get_config() # all resolved config
154
+ get_config("config.missing", raise_on_not_found=True) # raises ConfigPathNotFoundError
155
+ ```
156
+
157
+ ### `set_config(path, value)`
158
+
159
+ Runtime override, not written back to any file; the source is marked as `user` and `config_trace()` shows a timestamp. Note that `reload_config()` discards these overrides.
160
+
161
+ ```python
162
+ from darwin_config import set_config, get_config
163
+
164
+ set_config("config.database.host", "127.0.0.1")
165
+ assert get_config("config.database.host") == "127.0.0.1"
166
+ ```
167
+
168
+ ### `try_config(*paths, default=None)`
169
+
170
+ Return the first **non-None** value in order — handy for fallback chains; missing-path errors are swallowed.
171
+
172
+ ```python
173
+ from darwin_config import try_config
174
+
175
+ timeout = try_config(
176
+ "config.runtime.timeout", # runtime override
177
+ "config.server.timeout", # file config
178
+ "config.defaults.timeout", # fallback
179
+ default=30,
180
+ )
181
+ ```
182
+
183
+ ### `add_config(source, mount=None, values=None, validate=True)`
184
+
185
+ Append config after initialization: `source` may be a path, a glob string, or a dict. The file's own `mount` directive determines the real mount point. If the passed `mount` differs from the one declared in the file, an **alias** is registered automatically — both paths are readable, and writes go to the same node.
186
+
187
+ ```python
188
+ from darwin_config import add_config, get_config, config_trace
189
+
190
+ add_config("adapters/tushare.yaml") # uses the file's mount: adapter.tushare
191
+ add_config("adapters/extra/*.json", mount="custom.tushare") # alias -> adapter.tushare
192
+ add_config({"mount": "runtime.cache", "ttl": 60}) # pass a dict directly
193
+
194
+ assert get_config("adapter.tushare.auth.token") == get_config("custom.tushare.auth.token")
195
+ print(config_trace("adapter.tushare.auth.token")) # trace the source file and mount point
196
+ ```
197
+
198
+ ### `add_alias(alias, target)`
199
+
200
+ Give an existing path a semantic name, or a compatibility name during a migration. Reads and writes through the alias hit the target node. The target may not exist yet — it is resolved on read (same as `${root.xxx}`).
201
+
202
+ ```python
203
+ from darwin_config import add_alias, init_config, get_config, set_config
204
+
205
+ init_config(files=["settings.yaml"], mount="config")
206
+ add_alias("primary", "config.database")
207
+
208
+ get_config("primary.host") # same as config.database.host
209
+ set_config("primary.host", "x") # the original path changes too
210
+ ```
211
+
212
+ **Other APIs**: `reload_config()` (replays all `add_config` calls), `get_meta(path)`, `config_trace(path)`, `get_trace_summary()`, `get_aliases()` / `has_alias()`, `ConfigLoader` (an independent instance that avoids global state), `Schema` / `FieldRule` / `create_schema` / `validate_config` / `validate_and_fill`, and the exceptions `ConfigError` / `ConfigValidationError` / `ConfigPathNotFoundError` / `ConfigCircularReferenceError` / `ConfigMountError` — all importable directly from `darwin_config`.
213
+
214
+ Only the APIs developers actually use are exported at the top level; there are no no-op compatibility functions or environment-variable management helpers.
215
+
216
+ ---
217
+
218
+ ## 4. Features in detail
219
+
220
+ ### 4.1 Aliases
221
+
222
+ Not "a copy of the value" but a jump pointer inside the node tree: reads and writes target the same node. Supports **longest-prefix matching** and cycle detection. Use `get_aliases()` / `has_alias()` to inspect existing aliases.
223
+
224
+ Two ways to create one:
225
+
226
+ ```python
227
+ init_config(files=["settings.yaml"], mount="config")
228
+
229
+ # 1) Explicit registration (recommended): give an existing path a semantic name
230
+ add_alias("primary", "adapter.tushare")
231
+
232
+ # 2) Implicit during mounting: a passed mount differing from the file's mount registers an alias
233
+ add_config("adapter.yaml", mount="custom.tushare")
234
+
235
+ get_config("primary.auth.token") # same as adapter.tushare.auth.token
236
+ set_config("primary.auth.token", "x") # the original path becomes x as well
237
+ ```
238
+
239
+ Aliases share the same duplicate-name check as `add_config`; a circular reference raises `ConfigCircularReferenceError` on read.
240
+
241
+ ### 4.2 Schema validation and defaults
242
+
243
+ Supports `type` (string/integer/float/boolean/array/object), `required`, `default`, `choices`, `min/max`, `pattern`, custom validators, and `message`. Rules can be inline or in an external JSON/YAML file (which may itself `import` other rule files). Validation failures raise `ConfigValidationError`, whose `errors` is a field-keyed dict.
244
+
245
+ ```python
246
+ from darwin_config import Schema, create_schema, validate_and_fill
247
+
248
+ schema = create_schema({
249
+ "host": {"type": "string", "required": True},
250
+ "port": {"type": "integer", "default": 8080, "min": 1, "max": 65535},
251
+ })
252
+ cfg = validate_and_fill({"host": "localhost"}, schema)
253
+ # {'host': 'localhost', 'port': 8080}
254
+ ```
255
+
256
+ > Note the pipeline order is **schema → environment variables**: if a field is written as `"${PORT}"` but the schema declares `integer`, validation sees a string and reports a type error. Use `%{calc: ${PORT}}` when strict typing is required, or declare the field as `string` in the schema.
257
+
258
+ ### 4.3 References: `this` vs `root`
259
+
260
+ - `${this.xxx}` is an **in-file reference**, resolved at load time; references can chain (`a -> b -> c`) and can be embedded in the middle of a string.
261
+ - `${root.xxx}` is a **global reference**, resolved from the root node at runtime, so it can reference other files — even config appended later via `add_config`.
262
+ - The two can be mixed without interference; circular references raise `ConfigCircularReferenceError`.
263
+
264
+ ### 4.4 Environment variables
265
+
266
+ The library only **consumes** environment variables; it never modifies the caller's process environment. Reference them in config with `${VAR}` / `${VAR:default}`; for explicit injection use `init_config(values={...})`, which takes precedence over `os.environ`. The library provides no helpers for reading or writing environment variables.
267
+
268
+ ```python
269
+ init_config(files=["settings.yaml"], mount="config", values={"DB_HOST": "localhost"})
270
+ ```
271
+
272
+ ### 4.5 Source tracing
273
+
274
+ Every leaf node carries `source` / `mount` / `timestamp` / `overrides` metadata:
275
+
276
+ ```python
277
+ config_trace("config.database.host")
278
+ # config.database.host → settings.yaml (mount: config) (overridden by: runtime.json)
279
+ get_trace_summary() # {'settings.yaml': 12, 'runtime.json': 3, 'user': 1}
280
+ ```
281
+
282
+ ### 4.6 Three ways around reserved-word collisions
283
+
284
+ `import/merge/mount/schema` are reserved words, but they won't get in the way of normal business fields:
285
+
286
+ 1. **Scope**: `mount` / `schema` are recognized only at the top level of a file; a nested `database.schema: "public"` is an ordinary field.
287
+ 2. **Escaping**: `~import: [1, 2]` and `~schema: {name: mysql}` are unescaped into ordinary fields at the end of the pipeline.
288
+ 3. **Remapping**: `init_config(..., directives={"import": "cfg_import"})` renames a directive globally; the original `import` then becomes an ordinary field again.
289
+
290
+ ### 4.7 Standalone loader
291
+
292
+ When you don't want process-level global state:
293
+
294
+ ```python
295
+ from darwin_config import ConfigLoader
296
+
297
+ loader = ConfigLoader(config_files=["a.yaml", "b.yaml"], mount="cfg", validate=True)
298
+ data = loader.load() # {'cfg': {...}}, no global node tree involved
299
+ ```
300
+
301
+ ---
302
+
303
+ ## 5. Recursive merge rules
304
+
305
+ There are three merge points in the library, all with consistent semantics: **dicts merge recursively, non-dicts are overwritten, and the later writer wins**.
306
+
307
+ ### 5.1 The `import` directive — cross-file layering
308
+
309
+ ```
310
+ app.yaml import: [common.yaml] ┐
311
+ common.yaml import: base.yaml ├─ base first, then common, then app itself
312
+ base.yaml {server: {host, port, timeout}} ┘
313
+ ```
314
+
315
+ Result: `server = {host: <base>, port: <common>, timeout: <app>}` — only the keys that appear are overridden; the rest are inherited.
316
+ Multiple `import` entries merge in **array order** (later overrides earlier); the current file's top-level fields override everything last. This happens recursively at **any nesting level**, so `database: {import: "db.yaml"}` works too.
317
+
318
+ ### 5.2 The `merge` directive — in-file object templates
319
+
320
+ ```yaml
321
+ defaults: { timeout: 30, retry: 3, headers: { Accept: json } }
322
+ job:
323
+ merge: ${this.defaults}
324
+ timeout: 60
325
+ # -> {timeout: 60, retry: 3, headers: {Accept: json}}
326
+ ```
327
+
328
+ A `merge` source may be a string or an array (multiple sources merged in order) and must be in `${this.xxx}` form. A missing source only logs a warning. Source objects may themselves contain `merge`, which is expanded recursively first.
329
+
330
+ ### 5.3 `add_config` / multiple files — node-tree merge
331
+
332
+ - Leaf over leaf: the new value wins; the old `source` is recorded in `overrides` and the timestamp is updated
333
+ - Leaf against branch: the branch wins (it is not flattened by a scalar)
334
+ - Branch against branch: **recursive key-by-key merge**, keys that don't appear are retained
335
+ - Alias nodes are skipped and never merged
336
+ - Multiple `add_config` calls follow call order; later wins. `set_config` is the highest-priority runtime override
337
+
338
+ **Overall precedence (low → high)**:
339
+ `imported files (left → right)` → `current file's own fields` → `schema defaults (fill gaps only)` → `later files in files` → `add_config additions` → `set_config runtime settings`
340
+
341
+ > `None` is a valid value and overrides the old one rather than being ignored; `reload_config()` rebuilds from files and replays all `add_config` calls, which clears `set_config` runtime overrides.
342
+
343
+ ---
344
+
345
+ ## 6. Tests
346
+
347
+ ```bash
348
+ pip install -e '.[yaml,test]'
349
+ pytest tests -q
350
+ ```
351
+
352
+ Tests are split into `tests/unit/` (individual modules: utilities, node tree, Schema, processor, etc.) and `tests/integration/` (multi-file layering, mixed formats, end-to-end API flows), plus feature-oriented regression tests.
353
+
354
+ ## 7. License
355
+
356
+ MIT