casconf 0.1.2__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.
- casconf/__init__.py +30 -0
- casconf/__main__.py +10 -0
- casconf/api.py +84 -0
- casconf/cli.py +162 -0
- casconf/discovery.py +224 -0
- casconf/exceptions.py +54 -0
- casconf/merger.py +129 -0
- casconf/parser.py +83 -0
- casconf/py.typed +1 -0
- casconf/registry.py +218 -0
- casconf/writer.py +60 -0
- casconf-0.1.2.dist-info/METADATA +188 -0
- casconf-0.1.2.dist-info/RECORD +19 -0
- casconf-0.1.2.dist-info/WHEEL +5 -0
- casconf-0.1.2.dist-info/entry_points.txt +2 -0
- casconf-0.1.2.dist-info/licenses/AUTHORS +1 -0
- casconf-0.1.2.dist-info/licenses/LICENSE +690 -0
- casconf-0.1.2.dist-info/pbr.json +1 -0
- casconf-0.1.2.dist-info/top_level.txt +1 -0
casconf/__init__.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
"""CasConf — cascading configuration manager.
|
|
2
|
+
|
|
3
|
+
This is the top-level package. Import the public API from here::
|
|
4
|
+
|
|
5
|
+
from casconf import merge_configs, DiscoveryConfig
|
|
6
|
+
|
|
7
|
+
The complete API reference is available in ``API.md``.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
from casconf.api import merge_configs
|
|
13
|
+
from casconf.discovery import DiscoveryConfig
|
|
14
|
+
from casconf.exceptions import (
|
|
15
|
+
CasConfConfigError,
|
|
16
|
+
CasConfError,
|
|
17
|
+
CasConfMergeError,
|
|
18
|
+
CasConfParseError,
|
|
19
|
+
CasConfWriteError,
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
__all__ = [
|
|
23
|
+
"merge_configs",
|
|
24
|
+
"DiscoveryConfig",
|
|
25
|
+
"CasConfError",
|
|
26
|
+
"CasConfConfigError",
|
|
27
|
+
"CasConfParseError",
|
|
28
|
+
"CasConfMergeError",
|
|
29
|
+
"CasConfWriteError",
|
|
30
|
+
]
|
casconf/__main__.py
ADDED
casconf/api.py
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
"""CasConf public API implementations.
|
|
2
|
+
|
|
3
|
+
:func:`merge_configs` lives here so that ``casconf/__init__.py``
|
|
4
|
+
stays thin. It is re-exported from the top-level package::
|
|
5
|
+
|
|
6
|
+
from casconf import merge_configs
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import logging
|
|
12
|
+
import os
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
from typing import Any
|
|
15
|
+
|
|
16
|
+
from casconf.discovery import DiscoveryConfig, discover
|
|
17
|
+
from casconf.merger import merge
|
|
18
|
+
from casconf.parser import parse
|
|
19
|
+
from casconf.writer import write
|
|
20
|
+
|
|
21
|
+
_ENV_DISCOVERY = "CASCONF_DISCOVERY"
|
|
22
|
+
_DEFAULT_DISCOVERY = "casconf.yaml"
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def merge_configs(
|
|
26
|
+
discovery_config: str | Path | DiscoveryConfig | None = None,
|
|
27
|
+
output: str | Path | None = None,
|
|
28
|
+
output_format: str = "json",
|
|
29
|
+
log_level: int = logging.WARNING,
|
|
30
|
+
) -> dict[str, Any] | None:
|
|
31
|
+
"""Discover, parse, and deep-merge configuration files.
|
|
32
|
+
|
|
33
|
+
Args:
|
|
34
|
+
discovery_config: Path to a discovery configuration file, a
|
|
35
|
+
:class:`DiscoveryConfig` object, or ``None`` to use the
|
|
36
|
+
value of ``$CASCONF_DISCOVERY`` (falling back to
|
|
37
|
+
``'casconf.yaml'``).
|
|
38
|
+
output: Destination file path. If ``None`` (default), the
|
|
39
|
+
merged dict is returned and nothing is written to disk.
|
|
40
|
+
output_format: Serialisation format used when *output* is not
|
|
41
|
+
``None``. One of ``'json'`` (default), ``'yaml'``,
|
|
42
|
+
``'toml'``.
|
|
43
|
+
log_level: Python :mod:`logging` level for this run. Use
|
|
44
|
+
``logging.DEBUG`` for verbose output.
|
|
45
|
+
|
|
46
|
+
Returns:
|
|
47
|
+
The merged configuration dict when *output* is ``None``;
|
|
48
|
+
``None`` when *output* is specified (result written to file).
|
|
49
|
+
|
|
50
|
+
Raises:
|
|
51
|
+
CasConfConfigError: If the discovery configuration is
|
|
52
|
+
invalid.
|
|
53
|
+
CasConfParseError: If a configuration file cannot be parsed.
|
|
54
|
+
CasConfMergeError: If configurations cannot be merged.
|
|
55
|
+
CasConfWriteError: If the output file cannot be written.
|
|
56
|
+
|
|
57
|
+
Examples::
|
|
58
|
+
|
|
59
|
+
# Return merged config as a dict
|
|
60
|
+
config = merge_configs()
|
|
61
|
+
|
|
62
|
+
# Write to a file
|
|
63
|
+
merge_configs(
|
|
64
|
+
discovery_config='./casconf.yaml',
|
|
65
|
+
output='./merged.json',
|
|
66
|
+
)
|
|
67
|
+
"""
|
|
68
|
+
logging.getLogger("casconf").setLevel(log_level)
|
|
69
|
+
|
|
70
|
+
if discovery_config is None:
|
|
71
|
+
discovery_config = os.environ.get(_ENV_DISCOVERY, _DEFAULT_DISCOVERY)
|
|
72
|
+
|
|
73
|
+
if not isinstance(discovery_config, DiscoveryConfig):
|
|
74
|
+
discovery_config = DiscoveryConfig.from_file(Path(discovery_config))
|
|
75
|
+
|
|
76
|
+
paths = discover(discovery_config)
|
|
77
|
+
configs = [parse(p) for p in paths]
|
|
78
|
+
merged = merge(configs, strategy=discovery_config.merge_strategy, list_strategy=discovery_config.list_merge_strategy)
|
|
79
|
+
|
|
80
|
+
if output is not None:
|
|
81
|
+
write(merged, output=output, fmt=output_format)
|
|
82
|
+
return None
|
|
83
|
+
|
|
84
|
+
return merged
|
casconf/cli.py
ADDED
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
"""CasConf CLI — argument parsing and orchestration.
|
|
2
|
+
|
|
3
|
+
The :func:`main` function is the entry point registered in
|
|
4
|
+
``pyproject.toml``::
|
|
5
|
+
|
|
6
|
+
[project.scripts]
|
|
7
|
+
casconf = casconf.cli:main"
|
|
8
|
+
|
|
9
|
+
It is also invoked when running ``python -m casconf``.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import argparse
|
|
15
|
+
import logging
|
|
16
|
+
import os
|
|
17
|
+
import sys
|
|
18
|
+
|
|
19
|
+
from casconf.api import (
|
|
20
|
+
_DEFAULT_DISCOVERY,
|
|
21
|
+
_ENV_DISCOVERY,
|
|
22
|
+
merge_configs,
|
|
23
|
+
)
|
|
24
|
+
from casconf.exceptions import CasConfError
|
|
25
|
+
from casconf.writer import write
|
|
26
|
+
|
|
27
|
+
_ENV_LOG_LEVEL = "CASCONF_LOG_LEVEL"
|
|
28
|
+
_ENV_OUTPUT = "CASCONF_OUTPUT"
|
|
29
|
+
_ENV_FORMAT = "CASCONF_FORMAT"
|
|
30
|
+
_ENV_VERBOSE = "CASCONF_VERBOSE"
|
|
31
|
+
_DEFAULT_FORMAT = "json"
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _build_parser() -> argparse.ArgumentParser:
|
|
35
|
+
"""Build and return the CLI argument parser."""
|
|
36
|
+
_default_verbose = os.environ.get(_ENV_VERBOSE, "").lower() in ("1", "true", "yes")
|
|
37
|
+
parser = argparse.ArgumentParser(
|
|
38
|
+
prog="casconf",
|
|
39
|
+
description="Deep-merge configuration files across multiple directories following a cascading pattern.",
|
|
40
|
+
formatter_class=argparse.RawDescriptionHelpFormatter,
|
|
41
|
+
epilog=(
|
|
42
|
+
"Output goes to stdout by default; pipe to other tools "
|
|
43
|
+
"or use --output to write to a file.\n\n"
|
|
44
|
+
"All options can also be set via environment variables:\n"
|
|
45
|
+
f" ${_ENV_DISCOVERY} -- discovery config file path\n"
|
|
46
|
+
f" ${_ENV_OUTPUT} -- output file path\n"
|
|
47
|
+
f" ${_ENV_FORMAT} -- output format (json, yaml, toml)\n"
|
|
48
|
+
f" ${_ENV_VERBOSE} -- enable verbose logging (1/true/yes)\n"
|
|
49
|
+
f" ${_ENV_LOG_LEVEL} -- log level (DEBUG/INFO/WARNING/ERROR)\n\n"
|
|
50
|
+
"Examples:\n"
|
|
51
|
+
" casconf\n"
|
|
52
|
+
" casconf --output ./merged.json\n"
|
|
53
|
+
" casconf --format yaml | grep host\n"
|
|
54
|
+
" casconf | jq '.database'\n"
|
|
55
|
+
),
|
|
56
|
+
)
|
|
57
|
+
parser.add_argument(
|
|
58
|
+
"--discovery-config",
|
|
59
|
+
metavar="FILE",
|
|
60
|
+
default=os.environ.get(_ENV_DISCOVERY, _DEFAULT_DISCOVERY),
|
|
61
|
+
help=(f"Path to the discovery configuration file (default: {_DEFAULT_DISCOVERY!r}, or ${_ENV_DISCOVERY})"),
|
|
62
|
+
)
|
|
63
|
+
parser.add_argument(
|
|
64
|
+
"--output",
|
|
65
|
+
metavar="FILE",
|
|
66
|
+
default=os.environ.get(_ENV_OUTPUT),
|
|
67
|
+
help=(f"Write merged configuration to FILE instead of stdout (or ${_ENV_OUTPUT})."),
|
|
68
|
+
)
|
|
69
|
+
parser.add_argument(
|
|
70
|
+
"--format",
|
|
71
|
+
dest="output_format",
|
|
72
|
+
metavar="FORMAT",
|
|
73
|
+
default=os.environ.get(_ENV_FORMAT, _DEFAULT_FORMAT),
|
|
74
|
+
choices=["json", "yaml", "toml"],
|
|
75
|
+
help=(f"Output format: json (default), yaml, or toml (or ${_ENV_FORMAT})."),
|
|
76
|
+
)
|
|
77
|
+
parser.add_argument(
|
|
78
|
+
"--verbose",
|
|
79
|
+
"-v",
|
|
80
|
+
action="store_true",
|
|
81
|
+
default=_default_verbose,
|
|
82
|
+
help=f"Enable verbose (DEBUG) logging (or set ${_ENV_VERBOSE}=1).",
|
|
83
|
+
)
|
|
84
|
+
parser.add_argument(
|
|
85
|
+
"--version",
|
|
86
|
+
action="version",
|
|
87
|
+
version=_get_version(),
|
|
88
|
+
)
|
|
89
|
+
return parser
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def _get_version() -> str:
|
|
93
|
+
"""Return the installed package version string.
|
|
94
|
+
|
|
95
|
+
Uses :func:`importlib.metadata.version` to read the version that
|
|
96
|
+
pbr wrote into the package metadata at install time. Falls back
|
|
97
|
+
to a placeholder string when the package is not installed (e.g.
|
|
98
|
+
when running directly from a source checkout without ``pip install
|
|
99
|
+
-e .``).
|
|
100
|
+
"""
|
|
101
|
+
try:
|
|
102
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
103
|
+
|
|
104
|
+
return f"casconf {version('casconf')}"
|
|
105
|
+
except PackageNotFoundError:
|
|
106
|
+
return "casconf (version unknown)"
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _configure_logging(verbose: bool) -> None:
|
|
110
|
+
"""Configure root logging for the CLI.
|
|
111
|
+
|
|
112
|
+
Args:
|
|
113
|
+
verbose: If ``True``, set log level to DEBUG; otherwise use
|
|
114
|
+
the value of ``$CASCONF_LOG_LEVEL`` (default WARNING).
|
|
115
|
+
"""
|
|
116
|
+
if verbose:
|
|
117
|
+
level = logging.DEBUG
|
|
118
|
+
else:
|
|
119
|
+
env_level = os.environ.get(_ENV_LOG_LEVEL, "WARNING").upper()
|
|
120
|
+
level = getattr(logging, env_level, logging.WARNING)
|
|
121
|
+
|
|
122
|
+
logging.basicConfig(
|
|
123
|
+
level=level,
|
|
124
|
+
format="[%(levelname)s] %(message)s",
|
|
125
|
+
stream=sys.stderr,
|
|
126
|
+
)
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def main(argv: list[str] | None = None) -> int:
|
|
130
|
+
"""CLI entry point.
|
|
131
|
+
|
|
132
|
+
Args:
|
|
133
|
+
argv: Argument list (defaults to ``sys.argv[1:]`` when
|
|
134
|
+
``None``).
|
|
135
|
+
|
|
136
|
+
Returns:
|
|
137
|
+
Exit code: ``0`` on success, ``1`` on error.
|
|
138
|
+
"""
|
|
139
|
+
arg_parser = _build_parser()
|
|
140
|
+
args = arg_parser.parse_args(argv)
|
|
141
|
+
_configure_logging(args.verbose)
|
|
142
|
+
|
|
143
|
+
try:
|
|
144
|
+
merged = merge_configs(
|
|
145
|
+
discovery_config=args.discovery_config,
|
|
146
|
+
output_format=args.output_format,
|
|
147
|
+
log_level=(logging.DEBUG if args.verbose else logging.WARNING),
|
|
148
|
+
)
|
|
149
|
+
assert merged is not None
|
|
150
|
+
write(merged, output=args.output, fmt=args.output_format)
|
|
151
|
+
except CasConfError as exc:
|
|
152
|
+
logging.getLogger("casconf").error("%s", exc)
|
|
153
|
+
print(f"Error: {exc}", file=sys.stderr)
|
|
154
|
+
return 1
|
|
155
|
+
except Exception as exc: # noqa: BLE001
|
|
156
|
+
print(
|
|
157
|
+
f"Unexpected error: {exc}",
|
|
158
|
+
file=sys.stderr,
|
|
159
|
+
)
|
|
160
|
+
return 1
|
|
161
|
+
|
|
162
|
+
return 0
|
casconf/discovery.py
ADDED
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
"""CasConf discovery engine.
|
|
2
|
+
|
|
3
|
+
Responsible for locating configuration files based on a
|
|
4
|
+
:class:`DiscoveryConfig` and returning an ordered list of
|
|
5
|
+
:class:`~pathlib.Path` objects ready for parsing.
|
|
6
|
+
|
|
7
|
+
The :class:`DiscoveryConfig` object is also the public data class
|
|
8
|
+
that users construct (or load from a file) to describe *where* and
|
|
9
|
+
*what* to scan.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import glob as _glob
|
|
15
|
+
import logging
|
|
16
|
+
import os
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
from typing import Any
|
|
19
|
+
|
|
20
|
+
from casconf.exceptions import CasConfConfigError
|
|
21
|
+
|
|
22
|
+
logger = logging.getLogger(__name__)
|
|
23
|
+
|
|
24
|
+
_VALID_STRATEGIES = frozenset({"deep", "shallow"})
|
|
25
|
+
_VALID_LIST_STRATEGIES = frozenset({"append", "replace"})
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class DiscoveryConfig:
|
|
29
|
+
"""Configuration for the CasConf discovery engine.
|
|
30
|
+
|
|
31
|
+
Directories are scanned in the order they are listed; later
|
|
32
|
+
entries take precedence over earlier ones during merging.
|
|
33
|
+
|
|
34
|
+
Attributes:
|
|
35
|
+
directories: Ordered list of resolved directory paths to scan.
|
|
36
|
+
patterns: File name patterns to match within each directory.
|
|
37
|
+
Supports glob wildcards (``*``, ``?``, ``[…]``).
|
|
38
|
+
merge_strategy: Merge strategy to use (``'deep'`` or
|
|
39
|
+
``'shallow'``).
|
|
40
|
+
list_merge_strategy: How lists are merged during deep merge.
|
|
41
|
+
One of ``'append'`` (default, concatenates lists) or
|
|
42
|
+
``'replace'`` (override list replaces base list).
|
|
43
|
+
"""
|
|
44
|
+
|
|
45
|
+
def __init__(
|
|
46
|
+
self,
|
|
47
|
+
directories: list[str | Path],
|
|
48
|
+
patterns: list[str],
|
|
49
|
+
merge_strategy: str = "deep",
|
|
50
|
+
list_merge_strategy: str = "append",
|
|
51
|
+
) -> None:
|
|
52
|
+
"""Initialise a DiscoveryConfig.
|
|
53
|
+
|
|
54
|
+
Args:
|
|
55
|
+
directories: Ordered list of directories to scan.
|
|
56
|
+
Supports ``~`` expansion and environment variables.
|
|
57
|
+
Glob patterns in paths are expanded at scan time.
|
|
58
|
+
patterns: File name patterns to match.
|
|
59
|
+
merge_strategy: One of ``'deep'`` (default) or
|
|
60
|
+
``'shallow'``.
|
|
61
|
+
list_merge_strategy: How lists are merged during deep
|
|
62
|
+
merge. One of ``'append'`` (default) or
|
|
63
|
+
``'replace'``.
|
|
64
|
+
|
|
65
|
+
Raises:
|
|
66
|
+
CasConfConfigError: If *merge_strategy* or
|
|
67
|
+
*list_merge_strategy* is invalid, or
|
|
68
|
+
*directories*/*patterns* are empty.
|
|
69
|
+
"""
|
|
70
|
+
if not directories:
|
|
71
|
+
raise CasConfConfigError("'directories' must contain at least one entry.")
|
|
72
|
+
if not patterns:
|
|
73
|
+
raise CasConfConfigError("'patterns' must contain at least one entry.")
|
|
74
|
+
if merge_strategy not in _VALID_STRATEGIES:
|
|
75
|
+
raise CasConfConfigError(f"Invalid merge_strategy {merge_strategy!r}. Must be one of: {sorted(_VALID_STRATEGIES)}")
|
|
76
|
+
if list_merge_strategy not in _VALID_LIST_STRATEGIES:
|
|
77
|
+
raise CasConfConfigError(
|
|
78
|
+
f"Invalid list_merge_strategy {list_merge_strategy!r}. Must be one of: {sorted(_VALID_LIST_STRATEGIES)}"
|
|
79
|
+
)
|
|
80
|
+
|
|
81
|
+
self.directories: list[Path] = [Path(os.path.expandvars(os.path.expanduser(str(d)))) for d in directories]
|
|
82
|
+
self.patterns: list[str] = list(patterns)
|
|
83
|
+
self.merge_strategy: str = merge_strategy
|
|
84
|
+
self.list_merge_strategy: str = list_merge_strategy
|
|
85
|
+
|
|
86
|
+
# ------------------------------------------------------------------
|
|
87
|
+
# Class-method constructors
|
|
88
|
+
# ------------------------------------------------------------------
|
|
89
|
+
|
|
90
|
+
@classmethod
|
|
91
|
+
def from_file(cls, path: str | Path) -> DiscoveryConfig:
|
|
92
|
+
"""Load a :class:`DiscoveryConfig` from a YAML, JSON, or TOML file.
|
|
93
|
+
|
|
94
|
+
Args:
|
|
95
|
+
path: Path to the discovery configuration file.
|
|
96
|
+
|
|
97
|
+
Returns:
|
|
98
|
+
A new :class:`DiscoveryConfig` instance.
|
|
99
|
+
|
|
100
|
+
Raises:
|
|
101
|
+
CasConfConfigError: If the file cannot be read or is
|
|
102
|
+
missing required keys.
|
|
103
|
+
"""
|
|
104
|
+
from casconf.registry import registry
|
|
105
|
+
|
|
106
|
+
resolved = Path(path).expanduser().resolve()
|
|
107
|
+
if not resolved.exists():
|
|
108
|
+
raise CasConfConfigError(f"Discovery configuration file not found: {resolved}")
|
|
109
|
+
parser = registry.get_parser(resolved.suffix)
|
|
110
|
+
if parser is None:
|
|
111
|
+
raise CasConfConfigError(f"Unsupported discovery configuration format: {resolved.suffix!r}")
|
|
112
|
+
try:
|
|
113
|
+
data: dict[str, Any] = parser(resolved)
|
|
114
|
+
except Exception as exc:
|
|
115
|
+
raise CasConfConfigError(f"Failed to read discovery configuration: {exc}") from exc
|
|
116
|
+
return cls.from_dict(data)
|
|
117
|
+
|
|
118
|
+
@classmethod
|
|
119
|
+
def from_dict(cls, data: dict[str, Any]) -> DiscoveryConfig:
|
|
120
|
+
"""Create a :class:`DiscoveryConfig` from a plain dict.
|
|
121
|
+
|
|
122
|
+
Args:
|
|
123
|
+
data: Dictionary with keys ``'directories'``,
|
|
124
|
+
``'patterns'``, and optionally ``'merge_strategy'``
|
|
125
|
+
and ``'list_merge_strategy'``.
|
|
126
|
+
|
|
127
|
+
Returns:
|
|
128
|
+
A new :class:`DiscoveryConfig` instance.
|
|
129
|
+
|
|
130
|
+
Raises:
|
|
131
|
+
CasConfConfigError: If required keys are missing.
|
|
132
|
+
"""
|
|
133
|
+
for key in ("directories", "patterns"):
|
|
134
|
+
if key not in data:
|
|
135
|
+
raise CasConfConfigError(f"Missing required key in discovery configuration: {key!r}")
|
|
136
|
+
return cls(
|
|
137
|
+
directories=data["directories"],
|
|
138
|
+
patterns=data["patterns"],
|
|
139
|
+
merge_strategy=data.get("merge_strategy", "deep"),
|
|
140
|
+
list_merge_strategy=data.get("list_merge_strategy", "append"),
|
|
141
|
+
)
|
|
142
|
+
|
|
143
|
+
# ------------------------------------------------------------------
|
|
144
|
+
# Dunder helpers
|
|
145
|
+
# ------------------------------------------------------------------
|
|
146
|
+
|
|
147
|
+
def __repr__(self) -> str:
|
|
148
|
+
return (
|
|
149
|
+
f"DiscoveryConfig("
|
|
150
|
+
f"directories={self.directories!r}, "
|
|
151
|
+
f"patterns={self.patterns!r}, "
|
|
152
|
+
f"merge_strategy={self.merge_strategy!r}, "
|
|
153
|
+
f"list_merge_strategy={self.list_merge_strategy!r})"
|
|
154
|
+
)
|
|
155
|
+
|
|
156
|
+
def __eq__(self, other: object) -> bool:
|
|
157
|
+
if not isinstance(other, DiscoveryConfig):
|
|
158
|
+
return NotImplemented
|
|
159
|
+
return (
|
|
160
|
+
self.directories == other.directories
|
|
161
|
+
and self.patterns == other.patterns
|
|
162
|
+
and self.merge_strategy == other.merge_strategy
|
|
163
|
+
and self.list_merge_strategy == other.list_merge_strategy
|
|
164
|
+
)
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
# ---------------------------------------------------------------------------
|
|
168
|
+
# Discovery engine
|
|
169
|
+
# ---------------------------------------------------------------------------
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def discover(config: DiscoveryConfig) -> list[Path]:
|
|
173
|
+
"""Scan directories and return an ordered list of matching files.
|
|
174
|
+
|
|
175
|
+
Directories are scanned in order. Within each directory every
|
|
176
|
+
pattern is checked in order. The returned list is de-duplicated
|
|
177
|
+
while preserving the first-seen order.
|
|
178
|
+
|
|
179
|
+
Missing or unreadable directories produce a warning and are
|
|
180
|
+
skipped.
|
|
181
|
+
|
|
182
|
+
Args:
|
|
183
|
+
config: A :class:`DiscoveryConfig` describing where and what
|
|
184
|
+
to scan.
|
|
185
|
+
|
|
186
|
+
Returns:
|
|
187
|
+
Ordered list of :class:`~pathlib.Path` objects, from lowest
|
|
188
|
+
to highest priority.
|
|
189
|
+
"""
|
|
190
|
+
found: list[Path] = []
|
|
191
|
+
seen: set[Path] = set()
|
|
192
|
+
|
|
193
|
+
for raw_dir in config.directories:
|
|
194
|
+
# Expand glob patterns in the directory path itself
|
|
195
|
+
expanded_dirs = sorted(_glob.glob(str(raw_dir))) or [str(raw_dir)]
|
|
196
|
+
for dir_str in expanded_dirs:
|
|
197
|
+
directory = Path(dir_str)
|
|
198
|
+
if not directory.exists():
|
|
199
|
+
logger.warning(
|
|
200
|
+
"Directory does not exist, skipping: %s",
|
|
201
|
+
directory,
|
|
202
|
+
)
|
|
203
|
+
continue
|
|
204
|
+
if not directory.is_dir():
|
|
205
|
+
logger.warning(
|
|
206
|
+
"Path is not a directory, skipping: %s",
|
|
207
|
+
directory,
|
|
208
|
+
)
|
|
209
|
+
continue
|
|
210
|
+
|
|
211
|
+
for pattern in config.patterns:
|
|
212
|
+
for match in sorted(directory.glob(pattern)):
|
|
213
|
+
if match.is_file() and match not in seen:
|
|
214
|
+
logger.debug("Discovered: %s", match)
|
|
215
|
+
found.append(match)
|
|
216
|
+
seen.add(match)
|
|
217
|
+
|
|
218
|
+
logger.info(
|
|
219
|
+
"Discovery complete: %d file(s) found across %d director(ies) using %d pattern(s)",
|
|
220
|
+
len(found),
|
|
221
|
+
len(config.directories),
|
|
222
|
+
len(config.patterns),
|
|
223
|
+
)
|
|
224
|
+
return found
|
casconf/exceptions.py
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
"""CasConf exception hierarchy.
|
|
2
|
+
|
|
3
|
+
All exceptions raised by CasConf are subclasses of :class:`CasConfError`.
|
|
4
|
+
Import from this module or from the top-level ``casconf`` package.
|
|
5
|
+
|
|
6
|
+
Example::
|
|
7
|
+
|
|
8
|
+
from casconf.exceptions import CasConfParseError
|
|
9
|
+
|
|
10
|
+
try:
|
|
11
|
+
config = merge_configs()
|
|
12
|
+
except CasConfParseError as exc:
|
|
13
|
+
print(f"Could not parse {exc.path}: {exc}")
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class CasConfError(Exception):
|
|
22
|
+
"""Base exception for all CasConf errors."""
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class CasConfConfigError(CasConfError):
|
|
26
|
+
"""Raised when the discovery configuration is invalid.
|
|
27
|
+
|
|
28
|
+
This covers missing required keys, invalid values, and
|
|
29
|
+
unreadable discovery configuration files.
|
|
30
|
+
"""
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class CasConfParseError(CasConfError):
|
|
34
|
+
"""Raised when a configuration file cannot be parsed.
|
|
35
|
+
|
|
36
|
+
Attributes:
|
|
37
|
+
path: The path to the file that failed to parse.
|
|
38
|
+
"""
|
|
39
|
+
|
|
40
|
+
def __init__(self, message: str, path: Path | str) -> None:
|
|
41
|
+
super().__init__(message)
|
|
42
|
+
self.path: Path = Path(path)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class CasConfMergeError(CasConfError):
|
|
46
|
+
"""Raised when configurations cannot be merged."""
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class CasConfWriteError(CasConfError):
|
|
50
|
+
"""Raised when the output cannot be written.
|
|
51
|
+
|
|
52
|
+
This covers permission-denied errors, invalid output paths,
|
|
53
|
+
and unsupported output formats.
|
|
54
|
+
"""
|
casconf/merger.py
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
"""CasConf merger engine.
|
|
2
|
+
|
|
3
|
+
Implements deep and shallow merge strategies for combining
|
|
4
|
+
multiple configuration dictionaries into one.
|
|
5
|
+
|
|
6
|
+
The primary public symbol is :func:`merge` which dispatches to the
|
|
7
|
+
appropriate strategy based on the ``strategy`` parameter.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import logging
|
|
13
|
+
from typing import Any
|
|
14
|
+
|
|
15
|
+
logger = logging.getLogger(__name__)
|
|
16
|
+
|
|
17
|
+
_VALID_STRATEGIES = frozenset({"deep", "shallow"})
|
|
18
|
+
_VALID_LIST_STRATEGIES = frozenset({"append", "replace"})
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def merge(
|
|
22
|
+
configs: list[dict[str, Any]],
|
|
23
|
+
strategy: str = "deep",
|
|
24
|
+
list_strategy: str = "append",
|
|
25
|
+
) -> dict[str, Any]:
|
|
26
|
+
"""Merge an ordered list of configuration dicts.
|
|
27
|
+
|
|
28
|
+
Configs are applied left-to-right; later entries take
|
|
29
|
+
precedence over earlier ones.
|
|
30
|
+
|
|
31
|
+
Args:
|
|
32
|
+
configs: Ordered list of configuration dicts to merge.
|
|
33
|
+
The first element has the lowest priority.
|
|
34
|
+
strategy: Merge strategy. One of ``'deep'`` (default)
|
|
35
|
+
or ``'shallow'``.
|
|
36
|
+
list_strategy: How lists are merged during deep merge.
|
|
37
|
+
One of ``'append'`` (default, concatenates lists) or
|
|
38
|
+
``'replace'`` (override list replaces base list).
|
|
39
|
+
Only applies when *strategy* is ``'deep'``.
|
|
40
|
+
|
|
41
|
+
Returns:
|
|
42
|
+
A new dict representing the merged configuration.
|
|
43
|
+
|
|
44
|
+
Raises:
|
|
45
|
+
ValueError: If *strategy* or *list_strategy* is not a recognised value.
|
|
46
|
+
"""
|
|
47
|
+
if strategy not in _VALID_STRATEGIES:
|
|
48
|
+
raise ValueError(f"Unknown merge strategy {strategy!r}. Must be one of: {sorted(_VALID_STRATEGIES)}")
|
|
49
|
+
if list_strategy not in _VALID_LIST_STRATEGIES:
|
|
50
|
+
raise ValueError(f"Unknown list merge strategy {list_strategy!r}. Must be one of: {sorted(_VALID_LIST_STRATEGIES)}")
|
|
51
|
+
|
|
52
|
+
if not configs:
|
|
53
|
+
return {}
|
|
54
|
+
|
|
55
|
+
result: dict[str, Any] = {}
|
|
56
|
+
if strategy == "deep":
|
|
57
|
+
|
|
58
|
+
def merge_fn(b: dict[str, Any], o: dict[str, Any]) -> dict[str, Any]:
|
|
59
|
+
return deep_merge(b, o, list_strategy=list_strategy)
|
|
60
|
+
|
|
61
|
+
else:
|
|
62
|
+
merge_fn = shallow_merge # type: ignore[assignment]
|
|
63
|
+
for config in configs:
|
|
64
|
+
result = merge_fn(result, config)
|
|
65
|
+
return result
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def deep_merge(
|
|
69
|
+
base: dict[str, Any],
|
|
70
|
+
override: dict[str, Any],
|
|
71
|
+
list_strategy: str = "append",
|
|
72
|
+
) -> dict[str, Any]:
|
|
73
|
+
"""Recursively merge *override* into *base*, returning a new dict.
|
|
74
|
+
|
|
75
|
+
- Scalar values in *override* replace those in *base*.
|
|
76
|
+
- Dict values are merged recursively.
|
|
77
|
+
- List values are concatenated when *list_strategy* is ``'append'``
|
|
78
|
+
(*override* appended to *base*), or replaced entirely when
|
|
79
|
+
*list_strategy* is ``'replace'``.
|
|
80
|
+
- Type conflicts (e.g. scalar vs dict) log a warning; the
|
|
81
|
+
*override* value wins.
|
|
82
|
+
|
|
83
|
+
Args:
|
|
84
|
+
base: The base configuration dictionary.
|
|
85
|
+
override: The overriding configuration dictionary.
|
|
86
|
+
list_strategy: How lists are merged. One of ``'append'``
|
|
87
|
+
(default) or ``'replace'``.
|
|
88
|
+
|
|
89
|
+
Returns:
|
|
90
|
+
A new dict representing the deep-merged result.
|
|
91
|
+
"""
|
|
92
|
+
result = base.copy()
|
|
93
|
+
for key, value in override.items():
|
|
94
|
+
base_value = result.get(key)
|
|
95
|
+
if isinstance(base_value, dict) and isinstance(value, dict):
|
|
96
|
+
result[key] = deep_merge(base_value, value, list_strategy=list_strategy)
|
|
97
|
+
elif isinstance(base_value, list) and isinstance(value, list):
|
|
98
|
+
result[key] = base_value + value if list_strategy == "append" else value
|
|
99
|
+
else:
|
|
100
|
+
if key in result and type(base_value) is not type(value):
|
|
101
|
+
logger.warning(
|
|
102
|
+
"Type conflict at key %r: %s overrides %s",
|
|
103
|
+
key,
|
|
104
|
+
type(value).__name__,
|
|
105
|
+
type(base_value).__name__,
|
|
106
|
+
)
|
|
107
|
+
result[key] = value
|
|
108
|
+
return result
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def shallow_merge(
|
|
112
|
+
base: dict[str, Any],
|
|
113
|
+
override: dict[str, Any],
|
|
114
|
+
) -> dict[str, Any]:
|
|
115
|
+
"""Merge *override* into *base* at the top level only.
|
|
116
|
+
|
|
117
|
+
Top-level keys from *override* replace those in *base*
|
|
118
|
+
entirely, without recursing into nested dicts or lists.
|
|
119
|
+
|
|
120
|
+
Args:
|
|
121
|
+
base: The base configuration dictionary.
|
|
122
|
+
override: The overriding configuration dictionary.
|
|
123
|
+
|
|
124
|
+
Returns:
|
|
125
|
+
A new dict representing the shallow-merged result.
|
|
126
|
+
"""
|
|
127
|
+
result = base.copy()
|
|
128
|
+
result.update(override)
|
|
129
|
+
return result
|