darwin-config 0.2.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_config/__init__.py +77 -0
- darwin_config/alias.py +96 -0
- darwin_config/exceptions.py +58 -0
- darwin_config/loader.py +378 -0
- darwin_config/logging.py +25 -0
- darwin_config/node.py +358 -0
- darwin_config/processor.py +314 -0
- darwin_config/py.typed +0 -0
- darwin_config/schema.py +255 -0
- darwin_config/substitute.py +88 -0
- darwin_config/types.py +20 -0
- darwin_config/utils.py +278 -0
- darwin_config-0.2.0.dist-info/METADATA +356 -0
- darwin_config-0.2.0.dist-info/RECORD +15 -0
- darwin_config-0.2.0.dist-info/WHEEL +4 -0
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
"""
|
|
2
|
+
darwin-config
|
|
3
|
+
|
|
4
|
+
A layered, recursive JSON / YAML configuration loader.
|
|
5
|
+
|
|
6
|
+
Zero third-party dependencies in the core; YAML support is provided by the
|
|
7
|
+
optional PyYAML extra:
|
|
8
|
+
pip install darwin-config[yaml]
|
|
9
|
+
|
|
10
|
+
Configuration syntax:
|
|
11
|
+
import / merge / mount / schema bare-keyword directives (~ escapes them into plain fields)
|
|
12
|
+
${this.xxx} in-file reference
|
|
13
|
+
${root.xxx} global config-tree reference
|
|
14
|
+
${VAR:default} environment variable
|
|
15
|
+
%{calc: expr} restricted arithmetic (quote it in YAML)
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
from darwin_config.alias import add_alias, get_aliases, has_alias
|
|
19
|
+
from darwin_config.exceptions import (
|
|
20
|
+
ConfigCircularReferenceError,
|
|
21
|
+
ConfigError,
|
|
22
|
+
ConfigMountError,
|
|
23
|
+
ConfigPathNotFoundError,
|
|
24
|
+
ConfigValidationError,
|
|
25
|
+
)
|
|
26
|
+
from darwin_config.loader import (
|
|
27
|
+
ConfigLoader,
|
|
28
|
+
add_config,
|
|
29
|
+
config_trace,
|
|
30
|
+
get_config,
|
|
31
|
+
get_meta,
|
|
32
|
+
get_trace_summary,
|
|
33
|
+
init_config,
|
|
34
|
+
reload_config,
|
|
35
|
+
set_config,
|
|
36
|
+
try_config,
|
|
37
|
+
)
|
|
38
|
+
from darwin_config.schema import (
|
|
39
|
+
FieldRule,
|
|
40
|
+
Schema,
|
|
41
|
+
create_schema,
|
|
42
|
+
validate_and_fill,
|
|
43
|
+
validate_config,
|
|
44
|
+
)
|
|
45
|
+
|
|
46
|
+
__version__ = "0.2.0"
|
|
47
|
+
|
|
48
|
+
__all__ = [
|
|
49
|
+
# Loading and access
|
|
50
|
+
"ConfigLoader",
|
|
51
|
+
"init_config",
|
|
52
|
+
"add_config",
|
|
53
|
+
"get_config",
|
|
54
|
+
"set_config",
|
|
55
|
+
"try_config",
|
|
56
|
+
"reload_config",
|
|
57
|
+
# Aliases
|
|
58
|
+
"add_alias",
|
|
59
|
+
"get_aliases",
|
|
60
|
+
"has_alias",
|
|
61
|
+
# Validation
|
|
62
|
+
"Schema",
|
|
63
|
+
"FieldRule",
|
|
64
|
+
"create_schema",
|
|
65
|
+
"validate_config",
|
|
66
|
+
"validate_and_fill",
|
|
67
|
+
# Tracing
|
|
68
|
+
"get_meta",
|
|
69
|
+
"config_trace",
|
|
70
|
+
"get_trace_summary",
|
|
71
|
+
# Exceptions
|
|
72
|
+
"ConfigError",
|
|
73
|
+
"ConfigValidationError",
|
|
74
|
+
"ConfigPathNotFoundError",
|
|
75
|
+
"ConfigCircularReferenceError",
|
|
76
|
+
"ConfigMountError",
|
|
77
|
+
]
|
darwin_config/alias.py
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Alias management: an alias is a special node in the tree (is_alias=True, value is the target path).
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
from typing import Dict, Optional
|
|
6
|
+
|
|
7
|
+
from darwin_config.exceptions import ConfigMountError
|
|
8
|
+
from darwin_config.logging import get_logger
|
|
9
|
+
from darwin_config.node import Node
|
|
10
|
+
|
|
11
|
+
_root_node: Optional[Node] = None
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _get_logger():
|
|
15
|
+
return get_logger(__name__)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def set_root_node(node: Node) -> None:
|
|
19
|
+
global _root_node
|
|
20
|
+
_root_node = node
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def add_alias(alias: str, target: str) -> None:
|
|
24
|
+
"""Register an alias: alias and target read and write the same node.
|
|
25
|
+
|
|
26
|
+
The target path need not exist yet; it is resolved on read (same as the lazy
|
|
27
|
+
resolution of ${root.xxx}).
|
|
28
|
+
"""
|
|
29
|
+
if _root_node is None:
|
|
30
|
+
raise ConfigMountError("Root node is not initialized")
|
|
31
|
+
if alias == target:
|
|
32
|
+
raise ConfigMountError(f"Alias cannot be the same as target: {alias}")
|
|
33
|
+
if _root_node.has_alias(alias):
|
|
34
|
+
raise ConfigMountError(f"Alias '{alias}' already exists")
|
|
35
|
+
_get_logger().debug("Register alias: %s -> %s", alias, target)
|
|
36
|
+
_root_node.set_alias(alias, target)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def resolve_path(path: str) -> str:
|
|
40
|
+
"""Resolve aliases in a path (whole string + longest prefix, recursively)."""
|
|
41
|
+
if _root_node is None:
|
|
42
|
+
return path
|
|
43
|
+
if _root_node.is_alias(path):
|
|
44
|
+
node = _root_node.get_child(path)
|
|
45
|
+
if node and isinstance(node.value, str):
|
|
46
|
+
return resolve_path(node.value)
|
|
47
|
+
|
|
48
|
+
parts = path.split(".")
|
|
49
|
+
for index in range(len(parts), 0, -1):
|
|
50
|
+
prefix = ".".join(parts[:index])
|
|
51
|
+
if _root_node.is_alias(prefix):
|
|
52
|
+
node = _root_node.get_child(prefix)
|
|
53
|
+
if node and isinstance(node.value, str):
|
|
54
|
+
remaining = ".".join(parts[index:])
|
|
55
|
+
resolved = resolve_path(node.value)
|
|
56
|
+
return f"{resolved}.{remaining}" if remaining else resolved
|
|
57
|
+
return path
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def has_alias(path: str) -> bool:
|
|
61
|
+
return _root_node is not None and _root_node.has_alias(path)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def get_aliases() -> Dict[str, str]:
|
|
65
|
+
result: Dict[str, str] = {}
|
|
66
|
+
if _root_node is None:
|
|
67
|
+
return result
|
|
68
|
+
|
|
69
|
+
def traverse(node: Node, current: str = "") -> None:
|
|
70
|
+
if node.meta.get("is_alias", False) and isinstance(node.value, str):
|
|
71
|
+
result[current] = node.value
|
|
72
|
+
if node.children is not None:
|
|
73
|
+
for key, child in node.children.items():
|
|
74
|
+
traverse(child, f"{current}.{key}" if current else key)
|
|
75
|
+
|
|
76
|
+
traverse(_root_node)
|
|
77
|
+
return result
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def get_alias_target(alias: str) -> Optional[str]:
|
|
81
|
+
if _root_node is None:
|
|
82
|
+
return None
|
|
83
|
+
node = _root_node.get_child(alias)
|
|
84
|
+
if node is None or not node.meta.get("is_alias", False):
|
|
85
|
+
return None
|
|
86
|
+
return node.value if isinstance(node.value, str) else None
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
__all__ = [
|
|
90
|
+
"set_root_node",
|
|
91
|
+
"add_alias",
|
|
92
|
+
"resolve_path",
|
|
93
|
+
"has_alias",
|
|
94
|
+
"get_aliases",
|
|
95
|
+
"get_alias_target",
|
|
96
|
+
]
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
"""
|
|
2
|
+
darwin-config exception hierarchy.
|
|
3
|
+
|
|
4
|
+
All exceptions are defined internally and depend on no external packages.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from typing import Any, Dict, Optional
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class ConfigError(Exception):
|
|
11
|
+
"""Base class for configuration errors."""
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class ConfigNotFoundError(ConfigError):
|
|
15
|
+
"""Configuration not found."""
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class ConfigValidationError(ConfigError):
|
|
19
|
+
"""Validation failure, carrying a dict of field-level errors."""
|
|
20
|
+
|
|
21
|
+
def __init__(self, message: str, errors: Optional[Dict[str, Any]] = None):
|
|
22
|
+
super().__init__(message)
|
|
23
|
+
self.errors = errors or {}
|
|
24
|
+
|
|
25
|
+
def __str__(self) -> str:
|
|
26
|
+
if self.errors:
|
|
27
|
+
details = "\n".join(
|
|
28
|
+
f" {path}: {', '.join(messages)}" for path, messages in self.errors.items()
|
|
29
|
+
)
|
|
30
|
+
return f"{super().__str__()}\n{details}"
|
|
31
|
+
return super().__str__()
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class ConfigCircularReferenceError(ConfigError):
|
|
35
|
+
"""Circular reference error."""
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class ConfigPathNotFoundError(ConfigError):
|
|
39
|
+
"""Configuration path does not exist."""
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class ConfigEnvVarError(ConfigError):
|
|
43
|
+
"""Missing environment variable."""
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class ConfigMountError(ConfigError):
|
|
47
|
+
"""Mount or alias error."""
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
__all__ = [
|
|
51
|
+
"ConfigError",
|
|
52
|
+
"ConfigNotFoundError",
|
|
53
|
+
"ConfigValidationError",
|
|
54
|
+
"ConfigCircularReferenceError",
|
|
55
|
+
"ConfigPathNotFoundError",
|
|
56
|
+
"ConfigEnvVarError",
|
|
57
|
+
"ConfigMountError",
|
|
58
|
+
]
|
darwin_config/loader.py
ADDED
|
@@ -0,0 +1,378 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Configuration loader core and global public API.
|
|
3
|
+
|
|
4
|
+
Syntax:
|
|
5
|
+
- directives: import / merge / mount / schema (bare keywords, remappable)
|
|
6
|
+
- references: ${this.xxx} (in-file), ${root.xxx} (global)
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from datetime import datetime
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from typing import Any, Dict, List, Optional, Union
|
|
12
|
+
|
|
13
|
+
from darwin_config.alias import add_alias, resolve_path, set_root_node
|
|
14
|
+
from darwin_config.exceptions import ConfigError, ConfigPathNotFoundError
|
|
15
|
+
from darwin_config.logging import get_logger
|
|
16
|
+
from darwin_config.node import Node, dict_to_node, merge_node
|
|
17
|
+
from darwin_config.processor import (
|
|
18
|
+
process_file_import,
|
|
19
|
+
process_file_merge,
|
|
20
|
+
process_file_schema,
|
|
21
|
+
process_file_this_refs,
|
|
22
|
+
)
|
|
23
|
+
from darwin_config.substitute import replace_env_vars
|
|
24
|
+
from darwin_config.utils import (
|
|
25
|
+
Directives,
|
|
26
|
+
expand_glob_patterns,
|
|
27
|
+
load_config_file,
|
|
28
|
+
split_directives,
|
|
29
|
+
unescape_all,
|
|
30
|
+
)
|
|
31
|
+
|
|
32
|
+
logger = get_logger(__name__)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
# ============================================================
|
|
36
|
+
# Global state
|
|
37
|
+
# ============================================================
|
|
38
|
+
|
|
39
|
+
_root_node: Node = Node()
|
|
40
|
+
_initialized: bool = False
|
|
41
|
+
_mount_point: str = ""
|
|
42
|
+
_business_values: Dict[str, str] = {}
|
|
43
|
+
_validate_on_load: bool = False
|
|
44
|
+
_base_dir: Optional[Path] = None
|
|
45
|
+
_add_config_calls: List[Dict[str, Any]] = []
|
|
46
|
+
_config_files: List[str] = []
|
|
47
|
+
_directives: Directives = Directives()
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _mount_node(root: Node, mount_path: str, node: Node) -> None:
|
|
51
|
+
if not mount_path:
|
|
52
|
+
merge_node(root, node)
|
|
53
|
+
return
|
|
54
|
+
current = root
|
|
55
|
+
parts = mount_path.split(".")
|
|
56
|
+
for part in parts[:-1]:
|
|
57
|
+
if current.children is None:
|
|
58
|
+
current.children = {}
|
|
59
|
+
if part not in current.children:
|
|
60
|
+
current.children[part] = Node()
|
|
61
|
+
current = current.children[part]
|
|
62
|
+
if current.children is None:
|
|
63
|
+
current.children = {}
|
|
64
|
+
last = parts[-1]
|
|
65
|
+
if last in current.children:
|
|
66
|
+
merge_node(current.children[last], node)
|
|
67
|
+
else:
|
|
68
|
+
current.children[last] = node
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
# ============================================================
|
|
72
|
+
# ConfigLoader class
|
|
73
|
+
# ============================================================
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
class ConfigLoader:
|
|
77
|
+
"""A standalone configuration loader."""
|
|
78
|
+
|
|
79
|
+
def __init__(
|
|
80
|
+
self,
|
|
81
|
+
config_files: List[str],
|
|
82
|
+
mount: str = "",
|
|
83
|
+
variables: Optional[Dict[str, str]] = None,
|
|
84
|
+
validate: bool = False,
|
|
85
|
+
base_dir: Optional[Path] = None,
|
|
86
|
+
directives: Optional[Directives] = None,
|
|
87
|
+
):
|
|
88
|
+
self.config_files = config_files
|
|
89
|
+
self.mount = mount
|
|
90
|
+
self.variables = variables or {}
|
|
91
|
+
self.validate = validate
|
|
92
|
+
self.base_dir = base_dir or Path.cwd()
|
|
93
|
+
self.directives = directives or Directives()
|
|
94
|
+
|
|
95
|
+
def load(self) -> Dict[str, Any]:
|
|
96
|
+
"""Load all configuration files and return the merged dict."""
|
|
97
|
+
file_paths = expand_glob_patterns(self.config_files, self.variables)
|
|
98
|
+
if not file_paths:
|
|
99
|
+
logger.warning("No config files found: %s", self.config_files)
|
|
100
|
+
return {self.mount: {}} if self.mount else {}
|
|
101
|
+
|
|
102
|
+
processed = [self.process_file(path) for path in file_paths]
|
|
103
|
+
final_config: Dict[str, Any] = {}
|
|
104
|
+
for config in processed:
|
|
105
|
+
final_config = _deep_merge_dicts(final_config, config)
|
|
106
|
+
return {self.mount: final_config} if self.mount else final_config
|
|
107
|
+
|
|
108
|
+
def process_file(self, filepath: Path) -> Dict[str, Any]:
|
|
109
|
+
"""Process one file: load -> import -> schema -> env -> merge -> this."""
|
|
110
|
+
config = load_config_file(filepath)
|
|
111
|
+
return self.process_config(config, filepath.parent, source=str(filepath))
|
|
112
|
+
|
|
113
|
+
def process_config(self, config: Dict[str, Any], base_dir: Path, source: str = "memory") -> Dict[str, Any]:
|
|
114
|
+
"""Run the full pipeline on a config dict (reused by add_config)."""
|
|
115
|
+
directives = self.directives
|
|
116
|
+
|
|
117
|
+
# 1. import
|
|
118
|
+
config = process_file_import(config, base_dir, self.variables, self.mount, directives)
|
|
119
|
+
|
|
120
|
+
# 2. mount / schema (top-level directives)
|
|
121
|
+
config, top_directives = split_directives(config, directives, {"mount", "schema"})
|
|
122
|
+
schema_source = top_directives.get("schema")
|
|
123
|
+
|
|
124
|
+
# 3. schema validation + default filling
|
|
125
|
+
if self.validate and schema_source is not None:
|
|
126
|
+
from darwin_config.schema import Schema
|
|
127
|
+
|
|
128
|
+
config = Schema.load(schema_source, base_dir).validate_and_fill(config)
|
|
129
|
+
|
|
130
|
+
# 4. environment variable substitution
|
|
131
|
+
config = replace_env_vars(config, self.variables)
|
|
132
|
+
|
|
133
|
+
# 5. merge
|
|
134
|
+
config = process_file_merge(config, directives=directives)
|
|
135
|
+
|
|
136
|
+
# 6. this references
|
|
137
|
+
config = process_file_this_refs(config)
|
|
138
|
+
|
|
139
|
+
# 7. unescape all ~ prefixed keys at the end of the pipeline
|
|
140
|
+
return unescape_all(config, directives)
|
|
141
|
+
|
|
142
|
+
@property
|
|
143
|
+
def actual_mount(self) -> str:
|
|
144
|
+
return self.mount
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def _deep_merge_dicts(base: Dict[str, Any], override: Dict[str, Any]) -> Dict[str, Any]:
|
|
148
|
+
from darwin_config.utils import deep_merge
|
|
149
|
+
|
|
150
|
+
return deep_merge(base, override)
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
# ============================================================
|
|
154
|
+
# Public API
|
|
155
|
+
# ============================================================
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def init_config(
|
|
159
|
+
files: List[str],
|
|
160
|
+
mount: str = "",
|
|
161
|
+
values: Optional[Dict[str, str]] = None,
|
|
162
|
+
validate: bool = False,
|
|
163
|
+
base_dir: Optional[Path] = None,
|
|
164
|
+
directives: Optional[Dict[str, str]] = None,
|
|
165
|
+
) -> None:
|
|
166
|
+
"""Initialize the configuration system."""
|
|
167
|
+
global _root_node, _initialized, _mount_point, _business_values
|
|
168
|
+
global _validate_on_load, _base_dir, _config_files, _add_config_calls, _directives
|
|
169
|
+
|
|
170
|
+
_mount_point = mount
|
|
171
|
+
_business_values = values or {}
|
|
172
|
+
_config_files = files
|
|
173
|
+
_initialized = True
|
|
174
|
+
_validate_on_load = validate
|
|
175
|
+
_base_dir = base_dir or Path.cwd()
|
|
176
|
+
_add_config_calls = []
|
|
177
|
+
_directives = Directives(directives)
|
|
178
|
+
|
|
179
|
+
_root_node = Node()
|
|
180
|
+
set_root_node(_root_node)
|
|
181
|
+
|
|
182
|
+
loader = ConfigLoader(
|
|
183
|
+
config_files=files,
|
|
184
|
+
mount=mount,
|
|
185
|
+
variables=_business_values,
|
|
186
|
+
validate=validate,
|
|
187
|
+
base_dir=_base_dir,
|
|
188
|
+
directives=_directives,
|
|
189
|
+
)
|
|
190
|
+
result = loader.load()
|
|
191
|
+
source = str(files[0]) if files else "unknown"
|
|
192
|
+
|
|
193
|
+
if mount:
|
|
194
|
+
config_data = result.get(mount) or {}
|
|
195
|
+
node = dict_to_node(config_data, meta={"source": source, "mount": mount})
|
|
196
|
+
_mount_node(_root_node, mount, node)
|
|
197
|
+
else:
|
|
198
|
+
node = dict_to_node(result, meta={"source": source, "mount": ""})
|
|
199
|
+
_root_node.children = node.children
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def add_config(
|
|
203
|
+
source: Union[str, Path, Dict[str, Any]],
|
|
204
|
+
mount: Optional[str] = None,
|
|
205
|
+
values: Optional[Dict[str, str]] = None,
|
|
206
|
+
validate: bool = True,
|
|
207
|
+
) -> None:
|
|
208
|
+
"""Append configuration (from a file or a dict)."""
|
|
209
|
+
global _root_node, _add_config_calls
|
|
210
|
+
|
|
211
|
+
if not _initialized:
|
|
212
|
+
raise RuntimeError("Please call init_config() to initialize the configuration system first")
|
|
213
|
+
|
|
214
|
+
_add_config_calls.append(
|
|
215
|
+
{"source": source, "mount": mount, "values": values, "validate": validate}
|
|
216
|
+
)
|
|
217
|
+
merged_values = {**_business_values, **(values or {})}
|
|
218
|
+
|
|
219
|
+
loader = ConfigLoader(
|
|
220
|
+
config_files=[],
|
|
221
|
+
variables=merged_values,
|
|
222
|
+
validate=validate if validate is not None else _validate_on_load,
|
|
223
|
+
base_dir=_base_dir or Path.cwd(),
|
|
224
|
+
directives=_directives,
|
|
225
|
+
)
|
|
226
|
+
|
|
227
|
+
if isinstance(source, (str, Path)):
|
|
228
|
+
filepath = Path(source)
|
|
229
|
+
if not filepath.exists():
|
|
230
|
+
raise ConfigError(f"Config file not found: {filepath}")
|
|
231
|
+
raw = load_config_file(filepath)
|
|
232
|
+
_, top = split_directives(raw, _directives, {"mount"})
|
|
233
|
+
final_mount = top.get("mount", "")
|
|
234
|
+
if mount is not None and mount != final_mount:
|
|
235
|
+
add_alias(mount, final_mount)
|
|
236
|
+
processed = loader.process_config(raw, filepath.parent, source=str(filepath))
|
|
237
|
+
meta = {"source": str(filepath), "mount": final_mount}
|
|
238
|
+
else:
|
|
239
|
+
raw = source
|
|
240
|
+
_, top = split_directives(raw, _directives, {"mount"})
|
|
241
|
+
final_mount = top.get("mount", "")
|
|
242
|
+
if mount is not None and mount != final_mount:
|
|
243
|
+
add_alias(mount, final_mount)
|
|
244
|
+
processed = loader.process_config(raw, _base_dir or Path.cwd(), source="memory")
|
|
245
|
+
meta = {"source": "memory", "mount": final_mount}
|
|
246
|
+
|
|
247
|
+
_mount_node(_root_node, final_mount, dict_to_node(processed, meta=meta))
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
def _require_initialized() -> None:
|
|
251
|
+
if not _initialized:
|
|
252
|
+
raise RuntimeError("Please call init_config() to initialize the configuration system first")
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
def get_config(path: str = "", default: Any = None, raise_on_not_found: bool = False) -> Any:
|
|
256
|
+
"""Read a configuration value."""
|
|
257
|
+
_require_initialized()
|
|
258
|
+
if not path:
|
|
259
|
+
return _root_node.to_dict(resolved=True)
|
|
260
|
+
actual_path = resolve_path(path)
|
|
261
|
+
node = _root_node.get_child_resolved(actual_path, _root_node)
|
|
262
|
+
if node is None:
|
|
263
|
+
if raise_on_not_found:
|
|
264
|
+
raise ConfigPathNotFoundError(f"Path not found: {path}")
|
|
265
|
+
return default
|
|
266
|
+
return node.resolve(_root_node)
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
def try_config(*paths: str, default: Any = None) -> Any:
|
|
270
|
+
"""Try paths in order and return the first non-None value."""
|
|
271
|
+
for path in paths:
|
|
272
|
+
try:
|
|
273
|
+
value = get_config(path)
|
|
274
|
+
if value is not None:
|
|
275
|
+
return value
|
|
276
|
+
except (ConfigError, KeyError, RuntimeError):
|
|
277
|
+
continue
|
|
278
|
+
return default
|
|
279
|
+
|
|
280
|
+
|
|
281
|
+
def set_config(path: str, value: Any) -> None:
|
|
282
|
+
"""Set a configuration value at runtime."""
|
|
283
|
+
_require_initialized()
|
|
284
|
+
actual_path = resolve_path(path)
|
|
285
|
+
_root_node.set_child(
|
|
286
|
+
actual_path,
|
|
287
|
+
value,
|
|
288
|
+
meta={"source": "user", "timestamp": datetime.now().isoformat(), "resolved": False},
|
|
289
|
+
)
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
def get_meta(path: str) -> Dict[str, Any]:
|
|
293
|
+
_require_initialized()
|
|
294
|
+
return _root_node.get_meta(resolve_path(path))
|
|
295
|
+
|
|
296
|
+
|
|
297
|
+
def reload_config() -> Dict[str, Any]:
|
|
298
|
+
"""Reload configuration and replay all add_config calls."""
|
|
299
|
+
_require_initialized()
|
|
300
|
+
global _root_node, _add_config_calls
|
|
301
|
+
|
|
302
|
+
calls = _add_config_calls.copy()
|
|
303
|
+
_root_node = Node()
|
|
304
|
+
set_root_node(_root_node)
|
|
305
|
+
|
|
306
|
+
loader = ConfigLoader(
|
|
307
|
+
config_files=_config_files,
|
|
308
|
+
mount=_mount_point,
|
|
309
|
+
variables=_business_values,
|
|
310
|
+
validate=_validate_on_load,
|
|
311
|
+
base_dir=_base_dir or Path.cwd(),
|
|
312
|
+
directives=_directives,
|
|
313
|
+
)
|
|
314
|
+
result = loader.load()
|
|
315
|
+
source = str(_config_files[0]) if _config_files else "unknown"
|
|
316
|
+
|
|
317
|
+
if _mount_point:
|
|
318
|
+
config_data = result.get(_mount_point) or {}
|
|
319
|
+
node = dict_to_node(config_data, meta={"source": source, "mount": _mount_point})
|
|
320
|
+
_mount_node(_root_node, _mount_point, node)
|
|
321
|
+
else:
|
|
322
|
+
node = dict_to_node(result, meta={"source": source, "mount": ""})
|
|
323
|
+
_root_node.children = node.children
|
|
324
|
+
|
|
325
|
+
_add_config_calls = []
|
|
326
|
+
for call in calls:
|
|
327
|
+
add_config(**call)
|
|
328
|
+
return get_config()
|
|
329
|
+
|
|
330
|
+
|
|
331
|
+
def config_trace(path: str) -> str:
|
|
332
|
+
"""Return a human-readable source-trace string for a config path."""
|
|
333
|
+
if not _initialized:
|
|
334
|
+
return "Configuration system is not initialized"
|
|
335
|
+
meta = get_meta(resolve_path(path))
|
|
336
|
+
if not meta:
|
|
337
|
+
return f"Path '{path}' not found"
|
|
338
|
+
source = meta.get("source", "unknown")
|
|
339
|
+
mount = meta.get("mount", "")
|
|
340
|
+
overrides = meta.get("overrides", [])
|
|
341
|
+
result = f"{path} → {source}"
|
|
342
|
+
if mount:
|
|
343
|
+
result += f" (mount: {mount})"
|
|
344
|
+
if overrides:
|
|
345
|
+
result += f" (overridden by: {', '.join(overrides)})"
|
|
346
|
+
return result
|
|
347
|
+
|
|
348
|
+
|
|
349
|
+
def get_trace_summary() -> Dict[str, int]:
|
|
350
|
+
"""Count configuration items grouped by source."""
|
|
351
|
+
summary: Dict[str, int] = {}
|
|
352
|
+
|
|
353
|
+
def traverse(node: Node) -> None:
|
|
354
|
+
if node.meta.get("is_alias"):
|
|
355
|
+
return
|
|
356
|
+
source = node.meta.get("source")
|
|
357
|
+
if source:
|
|
358
|
+
summary[source] = summary.get(source, 0) + 1
|
|
359
|
+
if node.children:
|
|
360
|
+
for child in node.children.values():
|
|
361
|
+
traverse(child)
|
|
362
|
+
|
|
363
|
+
traverse(_root_node)
|
|
364
|
+
return summary
|
|
365
|
+
|
|
366
|
+
|
|
367
|
+
__all__ = [
|
|
368
|
+
"ConfigLoader",
|
|
369
|
+
"init_config",
|
|
370
|
+
"add_config",
|
|
371
|
+
"get_config",
|
|
372
|
+
"try_config",
|
|
373
|
+
"set_config",
|
|
374
|
+
"get_meta",
|
|
375
|
+
"reload_config",
|
|
376
|
+
"config_trace",
|
|
377
|
+
"get_trace_summary",
|
|
378
|
+
]
|
darwin_config/logging.py
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Logging helpers.
|
|
3
|
+
|
|
4
|
+
Built on the standard-library logging module; zero external dependencies.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import logging
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
_LOGGER_CACHE: dict[str, logging.Logger] = {}
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def get_logger(name: str) -> logging.Logger:
|
|
14
|
+
"""Return a named logger (cached)."""
|
|
15
|
+
if name not in _LOGGER_CACHE:
|
|
16
|
+
_LOGGER_CACHE[name] = logging.getLogger(name)
|
|
17
|
+
return _LOGGER_CACHE[name]
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def configure(level: int | str = logging.WARNING, **kwargs: Any) -> None:
|
|
21
|
+
"""Optional: configure the root logger. If not called, the host app's logging config applies."""
|
|
22
|
+
logging.basicConfig(level=level, **kwargs)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
__all__ = ["get_logger", "configure"]
|