Coverage for src/python/ensembl/vep/config/sources.py: 100%
116 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 layers (file, environment, command line etc.) and how they combine."""
16from __future__ import annotations
18import logging
19from collections.abc import Callable, Iterable
20from enum import Enum
21from pathlib import Path
22from typing import Any, get_args, get_origin
24from ensembl.vep.config.option_spec import OptionSpec, section_options, unwrap_optional_type
25from ensembl.vep.config.sections.base import ConfigSection
27__all__ = [
28 "ConfigLayer",
29 "ConfigSource",
30 "coerce_layer",
31 "coerce_value",
32 "merge_layers",
33]
35logger = logging.getLogger(__name__)
37ConfigLayer = dict[str, dict[str, object]]
38"""One layer of configuration: section name -> field name -> value, carrying only what it sets."""
40TRUE_VALUES = frozenset({"1", "true", "yes", "on"})
41FALSE_VALUES = frozenset({"0", "false", "no", "off"})
44class ConfigSource(Enum):
45 """Where a configuration value came from."""
47 DEFAULT = "default"
48 FILE = "file"
49 ENVIRONMENT = "environment"
50 COMMAND_LINE = "command line"
53def _to_bool(raw: object) -> bool:
54 """Read a boolean from a value that may have arrived as text.
56 Raises:
57 ValueError: If the text is not a recognised truth value.
58 """
59 if isinstance(raw, bool):
60 return raw
61 text = str(raw).strip().lower()
62 if text in TRUE_VALUES:
63 return True
64 if text in FALSE_VALUES:
65 return False
66 raise ValueError(f"expected a boolean, got '{raw}'")
69def _to_tuple(raw: object, type_annotation: Any) -> tuple:
70 """Read a tuple from a comma-separated string or an existing sequence."""
71 item_types: list[Any] = []
72 for argument in get_args(type_annotation):
73 if argument is Ellipsis:
74 continue
75 item_types.append(argument)
76 item_type = item_types[0] if item_types else str
77 pieces: list[object] = []
78 if isinstance(raw, str):
79 for piece in raw.split(","):
80 stripped = piece.strip()
81 if stripped:
82 pieces.append(stripped)
83 elif isinstance(raw, Iterable):
84 pieces = list(raw)
85 else:
86 # One value for a field that takes several: a TOML "distance = 5000", or an int from a
87 # Python caller. Perl VEP's own comma options accept the single form the same way.
88 pieces = [raw]
89 converted: list[Any] = []
90 for value in pieces:
91 converted.append(item_type(value))
92 return tuple(converted)
95def _to_enum(raw: object, enum_type: type[Enum]) -> Enum:
96 """Read an enum member from itself or from its name, in any case.
98 Raises:
99 ValueError: If the text names no member.
100 """
101 if isinstance(raw, enum_type):
102 return raw
103 try:
104 return enum_type[str(raw).upper()]
105 except KeyError:
106 accepted = ", ".join(member.name.lower() for member in enum_type)
107 raise ValueError(f"{str(raw)!r} is not one of {accepted}") from None
110def _converter_for(type_annotation: Any) -> Callable[[object], object]:
111 """Return the converter that reads one declared type.
113 Anything unrecognised is passed through untouched: coercion is best-effort, not a validator.
114 """
115 if type_annotation is bool:
116 return _to_bool
117 if type_annotation is Path:
118 return lambda raw: Path(str(raw))
119 if isinstance(type_annotation, type) and issubclass(type_annotation, Enum):
120 return lambda raw: _to_enum(raw, type_annotation)
121 if get_origin(type_annotation) is tuple:
122 return lambda raw: _to_tuple(raw, type_annotation)
123 if type_annotation in (int, float, str):
124 return type_annotation
125 return lambda raw: raw
128def coerce_value(raw: object, type_annotation: Any) -> object:
129 """Coerce a value read from a file or the environment to a field's declared type.
131 Command-line values have already been converted by argparse. These have not: TOML gives real
132 ints and bools but strings for paths, and the environment gives strings for everything.
134 Args:
135 raw (object): The value as read.
136 type_annotation (Any): The field's resolved type.
138 Returns:
139 object: The coerced value.
141 Raises:
142 ValueError: If a string cannot be read as the declared type.
143 """
144 type_annotation, optional = unwrap_optional_type(type_annotation)
145 if optional and (raw is None or raw == ""):
146 return None
147 return _converter_for(type_annotation)(raw)
150def _coerce_repeatable(raw: object, type_annotation: Any) -> tuple:
151 """Coerce a repeatable option's value without splitting an item on its commas.
153 One ``custom`` spec is itself comma-separated, so a lone string is one item, and a list or
154 tuple is one item per element -- the TOML spelling of giving the option twice.
155 """
156 item_type, _optional = unwrap_optional_type(type_annotation)
157 arguments = [argument for argument in get_args(item_type) if argument is not Ellipsis]
158 converter = _converter_for(arguments[0] if arguments else str)
159 items = raw if isinstance(raw, (list, tuple)) else [raw]
160 return tuple(converter(item) for item in items)
163def _check_choices(section: str, field_name: str, value: object, spec: OptionSpec) -> None:
164 """Check a coerced value against the option's declared choices, if it has any.
166 Raises:
167 ValueError: If the value, or any member of a tuple value, is not a permitted choice.
168 """
169 choices = spec.resolved_choices()
170 if choices is None or value is None or isinstance(value, Enum):
171 return
172 members = value if isinstance(value, tuple) else (value,)
173 for member in members:
174 if member not in choices:
175 accepted = ", ".join(str(choice) for choice in choices)
176 raise ValueError(f"{section}.{field_name}: {member!r} is not one of {accepted}")
179def coerce_layer(layer: ConfigLayer, section_types: tuple[type[ConfigSection], ...]) -> ConfigLayer:
180 """Coerce every value in a layer to its declared type and check it against its choices.
182 Unknown sections are dropped silently, since a layer may cover sections the command does not
183 read. An unknown field in a known section is dropped with a warning.
185 Raises:
186 ValueError: If a value cannot be read as its declared type or is not a permitted choice. The
187 message names the section and field.
188 """
189 by_name = {section_type.section_name: section_type for section_type in section_types}
190 coerced: ConfigLayer = {}
191 for section, values in layer.items():
192 section_type = by_name.get(section)
193 if section_type is None:
194 continue
195 options = section_options(section_type)
196 for field_name, raw in values.items():
197 if field_name not in options:
198 logger.warning("Ignoring unknown option '%s' in section '%s'", field_name, section)
199 continue
200 section_field, spec = options[field_name]
201 try:
202 if spec.repeatable:
203 value: object = _coerce_repeatable(raw, section_field.type)
204 else:
205 value = coerce_value(raw, section_field.type)
206 except ValueError as invalid:
207 raise ValueError(f"{section}.{field_name}: {invalid}") from invalid
208 _check_choices(section, field_name, value, spec)
209 coerced.setdefault(section, {})[field_name] = value
210 return coerced
213def merge_layers(*layers: ConfigLayer) -> ConfigLayer:
214 """Merge configuration layers in increasing precedence order."""
215 merged: ConfigLayer = {}
216 for layer in layers:
217 for section, values in layer.items():
218 merged.setdefault(section, {}).update(values)
219 return merged