Coverage for src/python/ensembl/vep/config/parser/config.py: 96%

93 statements  

« 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 

15"""Reading configuration from a file. 

16 

17TOML is the native format and its tables map onto section names. A file with no TOML table is read 

18as a Perl VEP config file, the way Perl VEP's own ``read_config_from_file`` reads it, so a config 

19file from an existing VEP install works unchanged. Legacy keys are flat, and are resolved to 

20sections by looking up which one declares each option. 

21""" 

22 

23from __future__ import annotations 

24 

25import logging 

26import re 

27import tomllib 

28from pathlib import Path 

29from ensembl.vep.config.option_spec import section_options 

30from ensembl.vep.config.parser.common import resolve_option 

31from ensembl.vep.config.sections.base import ConfigSection 

32from ensembl.vep.config.sources import ConfigLayer, coerce_layer 

33 

34__all__ = ["read_config_file", "read_legacy_config_file"] 

35 

36logger = logging.getLogger(__name__) 

37 

38_TABLE_HEADER = re.compile( 

39 r"""^\s*\[\[? # Optional whitespace and one or two opening square brackets 

40 [^\[\]]+ # One or more non-square bracket characters 

41 \]\]? # One or two closing square brackets 

42 \s*(\#.*)?$ # Optional whitespace and optional comment until end of line/string""", 

43 flags=(re.VERBOSE | re.MULTILINE), 

44) 

45"""A TOML ``[table]`` header line, which no legacy config line can look like.""" 

46 

47_QUOTES = "\"'" 

48 

49 

50def _split_legacy_line(line: str) -> list[str]: 

51 """Split a legacy config line into words on whitespace, dropping quotes and keeping quoted spaces.""" 

52 words: list[str] = [] 

53 current: list[str] = [] 

54 in_word = False 

55 open_quote = "" 

56 for character in line: 

57 if open_quote: 

58 if character == open_quote: 

59 open_quote = "" 

60 else: 

61 current.append(character) 

62 elif character in _QUOTES: 

63 open_quote = character 

64 in_word = True 

65 elif character.isspace(): 

66 if in_word: 

67 words.append("".join(current)) 

68 current = [] 

69 in_word = False 

70 else: 

71 current.append(character) 

72 in_word = True 

73 if in_word: 73 ↛ 75line 73 didn't jump to line 75 because the condition on line 73 was always true

74 words.append("".join(current)) 

75 return words 

76 

77 

78def _accumulates(section_type: type[ConfigSection], field_name: str) -> bool: 

79 """Return whether repeated lines add to a field rather than replace it, as Perl's ALLOW_MULTIPLE. 

80 

81 Only an option declared ``repeatable`` qualifies -- Perl's ``custom`` and ``plugin``. Every 

82 other tuple option reads one comma-separated value, exactly as it does on the command line. 

83 """ 

84 _section_field, spec = section_options(section_type)[field_name] 

85 return spec.repeatable 

86 

87 

88def read_legacy_config_file(path: Path, section_types: tuple[type[ConfigSection], ...]) -> ConfigLayer: 

89 """Read a Perl VEP config file as Perl VEP's ``read_config_from_file`` does. 

90 

91 A line is a comment only if it starts with ``#``. The key and value are separated by any run of 

92 whitespace, a leading dash on the key is dropped, and quotes are removed from the value with the 

93 spaces inside them kept. The first occurrence of a repeated key wins, except for an option 

94 declared ``repeatable`` (Perl's ``custom`` and ``plugin``), which accumulates one item per line. 

95 ``option = value`` is accepted as well. 

96 

97 Args: 

98 path (Path): The file to read. 

99 section_types (tuple[type[ConfigSection], ...]): The sections in play. 

100 

101 Returns: 

102 ConfigLayer: The options the file sets, grouped by section and coerced. Unrecognised keys 

103 are ignored: a legacy config carries options this implementation has not grown yet. 

104 

105 Raises: 

106 ValueError: If a value is of the wrong type or not one of the option's choices. 

107 """ 

108 by_name = {section_type.section_name: section_type for section_type in section_types} 

109 layer: ConfigLayer = {} 

110 accumulated: dict[tuple[str, str], list[object]] = {} 

111 for line in path.read_text(encoding="utf-8").splitlines(): 

112 if line.startswith("#") or not line.strip(): 

113 continue 

114 words = _split_legacy_line(line) 

115 key = words[0] 

116 values = words[1:] 

117 # Perl VEP writes "option value", but a hand-written file may use "option = value". 

118 if values and values[0] == "=": 

119 values = values[1:] 

120 elif values and values[0].startswith("="): 120 ↛ 121line 120 didn't jump to line 121 because the condition on line 120 was never true

121 values[0] = values[0][1:] 

122 first = values[0] if values else "1" 

123 resolved = resolve_option(key, first, section_types) 

124 if resolved is None: 

125 continue 

126 section, field_name, value = resolved 

127 if _accumulates(by_name[section], field_name): 

128 if values: 128 ↛ 111line 128 didn't jump to line 111 because the condition on line 128 was always true

129 # A constant flag resolves to its own value; anything else keeps the whole line. 

130 accumulated.setdefault((section, field_name), []).append( 

131 " ".join(values) if value is first else value 

132 ) 

133 else: 

134 layer.setdefault(section, {}).setdefault(field_name, value) 

135 for (section, field_name), tuple_values in accumulated.items(): 

136 layer.setdefault(section, {})[field_name] = tuple_values 

137 return coerce_layer(layer, section_types) 

138 

139 

140def _read_toml_tables( 

141 parsed: dict[str, object], section_types: tuple[type[ConfigSection], ...], path: Path 

142) -> ConfigLayer: 

143 """Collect the options a parsed TOML document sets, warning about keys no section declares.""" 

144 section_names = {section_type.section_name for section_type in section_types} 

145 tables: ConfigLayer = {} 

146 for section, values in parsed.items(): 

147 if not isinstance(values, dict): 147 ↛ 148line 147 didn't jump to line 148 because the condition on line 147 was never true

148 continue 

149 for key, value in values.items(): 

150 resolved = resolve_option(str(key), value, section_types) 

151 if resolved is None or resolved[0] != section: 

152 if section in section_names: 

153 logger.warning("%s: ignoring unknown option '%s' in table [%s]", path, key, section) 

154 continue 

155 resolved_section, field_name, resolved_value = resolved 

156 tables.setdefault(resolved_section, {})[field_name] = resolved_value 

157 return coerce_layer(tables, section_types) 

158 

159 

160def read_config_file(path: Path, section_types: tuple[type[ConfigSection], ...]) -> ConfigLayer: 

161 """Read a configuration file, as TOML if it is TOML-shaped and as legacy config otherwise. 

162 

163 A file is TOML if it has a ``[table]`` header or parses as TOML with at least one table. A 

164 syntax error in such a file is an error, not a cue to reread it as legacy config. 

165 

166 Args: 

167 path (Path): The file to read. 

168 section_types (tuple[type[ConfigSection], ...]): The sections in play. 

169 

170 Returns: 

171 ConfigLayer: The options the file sets, coerced to their declared types. 

172 

173 Raises: 

174 FileNotFoundError: If ``path`` does not exist. 

175 ValueError: If a TOML file has a syntax error, or a value is invalid for its option. 

176 """ 

177 text = path.read_text(encoding="utf-8") 

178 has_header = _TABLE_HEADER.search(text) is not None 

179 try: 

180 parsed = tomllib.loads(text) 

181 except tomllib.TOMLDecodeError as invalid: 

182 if has_header: 

183 raise ValueError(f"{path}: invalid TOML: {invalid}") from invalid 

184 return read_legacy_config_file(path, section_types) 

185 if not has_header and not any(isinstance(value, dict) for value in parsed.values()): 

186 return read_legacy_config_file(path, section_types) 

187 return _read_toml_tables(parsed, section_types, path)