Coverage for src/python/ensembl/vep/config/base.py: 100%
128 statements
« prev ^ index » next coverage.py v7.17.2, created at 2026-11-18 14:41 +0000
« prev ^ index » next coverage.py v7.17.2, created at 2026-11-18 14:41 +0000
1# See the NOTICE file distributed with this work for additional information
2# regarding copyright ownership.
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14"""Configuration roots and layer loading."""
16from __future__ import annotations
18import argparse
19from pathlib import Path
20from typing import ClassVar
22from attrs import define, field, fields
24from ensembl.vep.config.option_spec import section_options
25from ensembl.vep.config.parser.common import resolve_option
26from ensembl.vep.config.parser.cli import check_no_flag_collisions
27from ensembl.vep.config.parser import build_parser, parse_args, read_config_file, read_environment
28from ensembl.vep.config.sections import (
29 AnnotationConfig,
30 BenchConfig,
31 BenchEndToEndConfig,
32 BenchMatrixConfig,
33 BenchOracleConfig,
34 BenchSweepConfig,
35 CatalogueAddConfig,
36 CatalogueConfig,
37 CatalogueCostsConfig,
38 CatalogueRemoveConfig,
39 CatalogueShowConfig,
40 CatalogueValidateConfig,
41 CatalogueWriteConfig,
42 ConfigSection,
43 CorpusConfig,
44 CorpusDescribeConfig,
45 CorpusGoldenConfig,
46 CorpusSaveConfig,
47 ExecutionConfig,
48 ExplainConfig,
49 LoggingConfig,
50 RunConfig,
51 SourceConfig,
52 StatsConfig,
53)
54from ensembl.vep.config.sources import ConfigLayer, ConfigSource, coerce_layer, merge_layers
56__all__ = ["Config", "load"]
59@define(frozen=True, kw_only=True, auto_attribs=True)
60class Config:
61 """The assembled configuration and its value sources."""
63 annotation: AnnotationConfig = field(factory=AnnotationConfig)
64 bench: BenchConfig = field(factory=BenchConfig)
65 bench_endtoend: BenchEndToEndConfig = field(factory=BenchEndToEndConfig)
66 bench_matrix: BenchMatrixConfig = field(factory=BenchMatrixConfig)
67 bench_oracle: BenchOracleConfig = field(factory=BenchOracleConfig)
68 bench_sweep: BenchSweepConfig = field(factory=BenchSweepConfig)
69 catalogue: CatalogueConfig = field(factory=CatalogueConfig)
70 catalogue_add: CatalogueAddConfig = field(factory=CatalogueAddConfig)
71 catalogue_costs: CatalogueCostsConfig = field(factory=CatalogueCostsConfig)
72 catalogue_remove: CatalogueRemoveConfig = field(factory=CatalogueRemoveConfig)
73 catalogue_show: CatalogueShowConfig = field(factory=CatalogueShowConfig)
74 catalogue_validate: CatalogueValidateConfig = field(factory=CatalogueValidateConfig)
75 catalogue_write: CatalogueWriteConfig = field(factory=CatalogueWriteConfig)
76 corpus: CorpusConfig = field(factory=CorpusConfig)
77 corpus_describe: CorpusDescribeConfig = field(factory=CorpusDescribeConfig)
78 corpus_golden: CorpusGoldenConfig = field(factory=CorpusGoldenConfig)
79 corpus_save: CorpusSaveConfig = field(factory=CorpusSaveConfig)
80 explain: ExplainConfig = field(factory=ExplainConfig)
81 execution: ExecutionConfig = field(factory=ExecutionConfig)
82 logging: LoggingConfig = field(factory=LoggingConfig)
83 run: RunConfig = field(factory=RunConfig)
84 source: SourceConfig = field(factory=SourceConfig)
85 stats: StatsConfig = field(factory=StatsConfig)
86 command: str = field(default="")
87 sources: dict[str, dict[str, ConfigSource]] = field(factory=dict)
89 section_types: ClassVar[dict[str, type[ConfigSection]]] = {
90 "annotation": AnnotationConfig,
91 "bench": BenchConfig,
92 "bench_endtoend": BenchEndToEndConfig,
93 "bench_matrix": BenchMatrixConfig,
94 "bench_oracle": BenchOracleConfig,
95 "bench_sweep": BenchSweepConfig,
96 "catalogue": CatalogueConfig,
97 "catalogue_add": CatalogueAddConfig,
98 "catalogue_costs": CatalogueCostsConfig,
99 "catalogue_remove": CatalogueRemoveConfig,
100 "catalogue_show": CatalogueShowConfig,
101 "catalogue_validate": CatalogueValidateConfig,
102 "catalogue_write": CatalogueWriteConfig,
103 "corpus": CorpusConfig,
104 "corpus_describe": CorpusDescribeConfig,
105 "corpus_golden": CorpusGoldenConfig,
106 "corpus_save": CorpusSaveConfig,
107 "explain": ExplainConfig,
108 "execution": ExecutionConfig,
109 "logging": LoggingConfig,
110 "run": RunConfig,
111 "source": SourceConfig,
112 "stats": StatsConfig,
113 }
114 """Map section attribute names to their classes."""
116 @staticmethod
117 def _command_section_names(command: str) -> tuple[str, ...]:
118 """Return the section names a registered command reads.
120 The registry is imported here rather than at module scope because importing it registers
121 the runners, and every runner module imports this one.
123 Raises:
124 ValueError: If no command is registered under the name.
125 """
127 # pylint: disable=import-outside-toplevel,import-error,no-name-in-module
128 from ensembl.vep.runner import get_runner
130 try:
131 return get_runner(command).sections
132 except KeyError as unknown:
133 raise ValueError(str(unknown).strip("\"'")) from unknown
135 @classmethod
136 def section_types_for(cls, names: tuple[str, ...]) -> tuple[type[ConfigSection], ...]:
137 """Return the section class types for the given section names."""
138 section_types: list[type[ConfigSection]] = []
139 for name in names:
140 section_types.append(cls.section_types[name])
141 return tuple(section_types)
143 @classmethod
144 def build_section(
145 cls,
146 section_type: type[ConfigSection],
147 values: dict[str, object],
148 ) -> ConfigSection:
149 """Build one section class from its merged values."""
150 options = section_options(section_type)
151 known: dict[str, object] = {}
152 for name, value in values.items():
153 if name in options:
154 known[name] = value
155 return section_type(**known) # type: ignore[call-arg]
157 @classmethod
158 def sources_for(
159 cls, layers: tuple[tuple[ConfigSource, ConfigLayer], ...]
160 ) -> dict[str, dict[str, ConfigSource]]:
161 """Return the winning source for each option given the configuration layers for different sources."""
162 sources: dict[str, dict[str, ConfigSource]] = {}
163 for source, layer in layers:
164 for section, values in layer.items():
165 for field_name in values:
166 sources.setdefault(section, {})[field_name] = source
167 return sources
169 @classmethod
170 def for_command(cls, command: str, **options: object) -> Config:
171 """Return the configuration for one command, named as the command line names its options.
173 The command's own sections decide where each option belongs, so a caller gives flat option
174 names and never has to know which section declares which. Values are coerced as the command
175 line coerces them, so a path may be given as a string.
177 Args:
178 command (str): A registered command, such as ``run.default``.
179 **options (object): Option values, named by field or by flag.
181 Returns:
182 Config: The command's sections built from these options, every other section left at
183 its defaults.
185 Raises:
186 ValueError: If the command is not registered, or an option is not one it reads.
187 """
189 section_names = cls._command_section_names(command)
190 section_types = cls.section_types_for(section_names)
191 check_no_flag_collisions(section_types)
193 given: ConfigLayer = {}
194 for key, value in options.items():
195 resolved = resolve_option(key, value, section_types)
196 if resolved is None:
197 raise ValueError(f"{key!r} is not an option of {command!r}")
198 section_name, field_name, resolved_value = resolved
199 given.setdefault(section_name, {})[field_name] = resolved_value
201 coerced = coerce_layer(given, section_types)
202 built: dict[str, ConfigSection] = {}
203 for name in section_names:
204 section_type = cls.section_types[name]
205 built[name] = cls.build_section(section_type, coerced.get(section_type.section_name, {}))
206 return cls(**built, command=command) # type: ignore[arg-type]
208 def sections(self) -> tuple[ConfigSection, ...]:
209 """Return the configured sections in declaration order."""
210 sections: list[ConfigSection] = []
211 for attribute in fields(type(self)):
212 value = getattr(self, attribute.name)
213 if isinstance(value, ConfigSection):
214 sections.append(value)
215 return tuple(sections)
217 def section(self, name: str) -> ConfigSection:
218 """Return a configured section by its declared name."""
219 for section in self.sections():
220 if section.section_name == name:
221 return section
222 raise KeyError(f"Unknown configuration section '{name}'")
224 def source_of(self, section: str, field_name: str) -> ConfigSource:
225 """Return the winning source for a given section name and field."""
226 return self.sources.get(section, {}).get(field_name, ConfigSource.DEFAULT)
228 def as_mapping(self) -> dict[str, dict[str, object]]:
229 """Return the declared options as ``section -> field -> value``."""
230 mapping: dict[str, dict[str, object]] = {}
231 for section in self.sections():
232 values: dict[str, object] = {}
233 for name in section_options(type(section)):
234 values[name] = getattr(section, name)
235 mapping[section.section_name] = values
236 return mapping
239def load(
240 argv: list[str] | None = None,
241 *,
242 command: str = "",
243 section_names: tuple[str, ...] = (),
244 config_file: Path | None = None,
245 environ: dict[str, str] | None = None,
246 parser: argparse.ArgumentParser | None = None,
247) -> Config:
248 """Load configuration from the available layers."""
249 section_names = section_names or tuple(Config.section_types)
250 section_types = Config.section_types_for(section_names)
251 check_no_flag_collisions(section_types)
253 # Read configuration layers in order of increasing precedence: file, environment, command line.
254 layers: list[tuple[ConfigSource, ConfigLayer]] = []
255 if config_file is not None:
256 layers.append((ConfigSource.FILE, read_config_file(config_file, section_types)))
257 layers.append((ConfigSource.ENVIRONMENT, read_environment(section_types, environ)))
258 if argv is not None:
259 command_line_parser = parser or build_parser(f"vep {command}".strip(), "", section_types)
260 layers.append((ConfigSource.COMMAND_LINE, parse_args(command_line_parser, argv, section_types)))
262 merged = merge_layers(*(layer for _, layer in layers))
263 built: dict[str, ConfigSection] = {}
264 for name in section_names:
265 section_type = Config.section_types[name]
266 built[name] = Config.build_section(section_type, merged.get(section_type.section_name, {}))
267 sources = Config.sources_for(tuple(layers))
268 return Config(**built, command=command, sources=sources) # type: ignore[arg-type]