Coverage for src/python/ensembl/vep/config/parser/env.py: 100%
20 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"""Reading configuration from the environment."""
16from __future__ import annotations
18import os
20from ensembl.vep.config.option_spec import section_options
21from ensembl.vep.config.parser.cli import check_no_flag_collisions
22from ensembl.vep.config.sections.base import ConfigSection
23from ensembl.vep.config.sources import ConfigLayer, coerce_layer
25__all__ = ["ENV_PREFIX", "default_env_name", "read_environment"]
27ENV_PREFIX = "ENSEMBL_VEP"
30def default_env_name(section: str, field_name: str) -> str:
31 """Return the environment variable an option is read from, e.g. ENSEMBL_VEP_CORPUS_FUZZ."""
32 return f"{ENV_PREFIX}_{section}_{field_name}".upper()
35def read_environment(
36 section_types: tuple[type[ConfigSection], ...], environ: dict[str, str] | None = None
37) -> ConfigLayer:
38 """Read whatever the environment sets, for the given sections.
40 Args:
41 section_types (tuple[type[ConfigSection], ...]): The sections in play.
42 environ (dict[str, str] | None): Environment to read, or None for ``os.environ``.
44 Returns:
45 ConfigLayer: The options the environment sets, coerced to their declared types.
47 Raises:
48 ValueError: If a value is not of its declared type or not one of its choices.
49 """
50 check_no_flag_collisions(section_types)
51 source = os.environ if environ is None else environ
52 layer: ConfigLayer = {}
53 for section_type in section_types:
54 for field_name, (_field, spec) in section_options(section_type).items():
55 name = spec.env or default_env_name(section_type.section_name, field_name)
56 if name in source:
57 layer.setdefault(section_type.section_name, {})[field_name] = source[name]
58 return coerce_layer(layer, section_types)