Coverage for src/python/ensembl/vep/config/option_spec.py: 100%
50 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"""Option declarations for configuration sections."""
16from __future__ import annotations
18from collections.abc import Callable, Mapping, Sequence
19from types import NoneType, UnionType
20from typing import TYPE_CHECKING, Any, Union, get_args, get_origin
22import attrs
23from attrs import Factory, define, fields
25if TYPE_CHECKING:
26 from ensembl.vep.config.sections.base import ConfigSection
28__all__ = ["OptionSpec", "option", "section_options", "unwrap_optional_type"]
30METADATA_KEY = "vep.option"
31"""Key the ``option()`` payload is stored under in a field's metadata."""
34@define(frozen=True, kw_only=True, auto_attribs=True)
35class OptionSpec:
36 """How one option is exposed.
38 Attributes:
39 help (str): One-line description, used as the argparse help text.
40 flag (str | None): Long flag spelling without the dashes, or None for the field name.
41 short (str | None): Single-character short flag, without the dash.
42 synonyms (tuple[str, ...]): Further long spellings that set the same option, for the names
43 Perl VEP uses. They work on the command line and in a config file; the environment
44 variable keeps the canonical name.
45 constants (Mapping[str, object]): Flags that set this option to a fixed value, such as
46 Perl VEP's ``--vcf`` for ``--output_format vcf``, as flag name -> value.
47 choices (Sequence[object] | Callable[[], Sequence[object]] | None): The permitted values,
48 or a callable returning them for a vocabulary another package owns.
49 metavar (str | None): argparse metavar override.
50 env (str | None): Environment variable name, or None to derive one.
51 hidden (bool): True to keep the option out of ``--help``.
52 repeatable (bool): True for a tuple option given once per item, as Perl VEP's
53 ``--custom`` is. Each occurrence is kept whole, with no comma splitting.
54 """
56 help: str
57 flag: str | None = None
58 short: str | None = None
59 synonyms: tuple[str, ...] = ()
60 constants: Mapping[str, object] = Factory(dict)
61 choices: Sequence[object] | Callable[[], Sequence[object]] | None = None
62 metavar: str | None = None
63 env: str | None = None
64 hidden: bool = False
65 repeatable: bool = False
67 def resolved_choices(self) -> tuple[object, ...] | None:
68 """Return the permitted values, calling ``choices`` if needed."""
69 if self.choices is None:
70 return None
71 if callable(self.choices):
72 choices = self.choices()
73 else:
74 choices = self.choices
75 return tuple(choices)
78def option(
79 help: str, # pylint: disable=redefined-builtin
80 *,
81 flag: str | None = None,
82 short: str | None = None,
83 synonyms: tuple[str, ...] = (),
84 constants: Mapping[str, object] | None = None,
85 choices: Sequence[object] | Callable[[], Sequence[object]] | None = None,
86 metavar: str | None = None,
87 env: str | None = None,
88 hidden: bool = False,
89 repeatable: bool = False,
90) -> dict[str, OptionSpec]:
91 """Return ``attrs`` field metadata for one option.
93 Args:
94 help (str): One-line description, used as the argparse help text.
95 flag (str | None): Long flag spelling without the dashes, or None for the field name.
96 short (str | None): Single-character short flag, without the dash.
97 synonyms (tuple[str, ...]): Further long spellings that set the same option.
98 constants (Mapping[str, object] | None): Flags that set this option to a fixed value, as
99 flag name -> value.
100 choices (Sequence[object] | Callable[[], Sequence[object]] | None): The permitted values,
101 or a callable returning them.
102 metavar (str | None): argparse metavar override.
103 env (str | None): Environment variable name, or None to derive one.
104 hidden (bool): True to keep the option out of ``--help``.
105 repeatable (bool): True for a tuple option given once per item, each kept whole.
107 Returns:
108 dict[str, OptionSpec]: The metadata to pass as ``field(metadata=...)``.
109 """
110 spec = OptionSpec(
111 help=help,
112 flag=flag,
113 short=short,
114 synonyms=synonyms,
115 constants={} if constants is None else dict(constants),
116 choices=choices,
117 metavar=metavar,
118 env=env,
119 hidden=hidden,
120 repeatable=repeatable,
121 )
122 return {METADATA_KEY: spec}
125def section_options(section_type: type[ConfigSection]) -> dict[str, tuple[attrs.Attribute, OptionSpec]]:
126 """Return the declared options of a section, keyed by field name.
128 Args:
129 section_type (type[ConfigSection]): The section class to inspect.
131 Returns:
132 dict[str, tuple[attrs.Attribute, OptionSpec]]: Field name -> (field, spec), in declaration
133 order, for the fields carrying ``option()`` metadata.
134 """
135 attrs.resolve_types(section_type)
136 specs: dict[str, tuple[attrs.Attribute, OptionSpec]] = {}
137 for section_field in fields(section_type):
138 spec = section_field.metadata.get(METADATA_KEY)
139 if spec is not None:
140 specs[section_field.name] = (section_field, spec)
141 return specs
144def unwrap_optional_type(type_annotation: Any) -> tuple[Any, bool]:
145 """Split ``X | None`` into ``X`` and a nullability flag.
147 Args:
148 type_annotation (Any): The resolved field type.
150 Returns:
151 tuple[Any, bool]: The non-None member and whether None was a member. A union of more than
152 one non-None type is returned unchanged and reported as not optional.
153 """
154 origin = get_origin(type_annotation)
155 if origin not in (Union, UnionType):
156 return type_annotation, False
157 members: list[Any] = []
158 for member in get_args(type_annotation):
159 if member is not NoneType:
160 members.append(member)
161 if len(members) != 1:
162 return type_annotation, False
163 return members[0], True