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

146 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"""Build an argparse surface from the section declarations. 

15 

16Each action uses ``default=argparse.SUPPRESS`` so omitted flags stay absent from the parsed 

17namespace. That keeps them distinct from values read from a file or the environment. 

18""" 

19 

20from __future__ import annotations 

21 

22import argparse 

23from enum import Enum 

24from pathlib import Path 

25from typing import Any, get_args, get_origin 

26 

27from ensembl.vep.config.option_spec import OptionSpec, section_options, unwrap_optional_type 

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

29from ensembl.vep.config.parser.common import flag_for, option_spellings 

30from ensembl.vep.config.sources import ConfigLayer 

31 

32__all__ = [ 

33 "add_section_arguments", 

34 "destination", 

35 "build_parser", 

36 "check_no_flag_collisions", 

37 "parse_args", 

38] 

39 

40 

41class BooleanSwitchAction(argparse.Action): 

42 """Set a boolean to True or False according to which spelling was given. 

43 

44 One action carries both senses so ``--help`` lists them together, ``--zone_map, --no_zone_map``. 

45 """ 

46 

47 def __init__( 

48 self, 

49 option_strings: list[str], 

50 dest: str, 

51 *, 

52 false_flags: tuple[str, ...] = (), 

53 default: Any = argparse.SUPPRESS, 

54 help: str | None = None, # pylint: disable=redefined-builtin 

55 ) -> None: 

56 super().__init__(option_strings=option_strings, dest=dest, nargs=0, default=default, help=help) 

57 self.false_flags = frozenset(false_flags) 

58 

59 def __call__( 

60 self, 

61 parser: argparse.ArgumentParser, 

62 namespace: argparse.Namespace, 

63 values: Any, 

64 option_string: str | None = None, 

65 ) -> None: 

66 setattr(namespace, self.dest, option_string not in self.false_flags) 

67 

68 

69class AppendItemAction(argparse.Action): 

70 """Collect each occurrence of a repeatable option into a tuple, keeping every value whole.""" 

71 

72 def __call__( 

73 self, 

74 parser: argparse.ArgumentParser, 

75 namespace: argparse.Namespace, 

76 values: Any, 

77 option_string: str | None = None, 

78 ) -> None: 

79 collected = getattr(namespace, self.dest, ()) 

80 setattr(namespace, self.dest, (*collected, values)) 

81 

82 

83def _comma_separated(item_type: Any) -> Any: 

84 """Return a converter parsing a comma-separated string into a tuple.""" 

85 

86 def convert(value: str) -> tuple: 

87 if not value: 

88 return () 

89 pieces: list[Any] = [] 

90 for piece in value.split(","): 

91 pieces.append(item_type(piece.strip())) 

92 return tuple(pieces) 

93 

94 convert.__name__ = f"comma_separated_{getattr(item_type, '__name__', 'value')}" 

95 return convert 

96 

97 

98def _enum_converter(enum_type: type[Enum]) -> Any: 

99 """Return a converter mapping a lowercased member name to an enum member.""" 

100 

101 def convert(value: str) -> Enum: 

102 try: 

103 return enum_type[value.upper()] 

104 except KeyError as error: 

105 names: list[str] = [] 

106 for member in enum_type: 

107 names.append(member.name.lower()) 

108 names_text = ", ".join(names) 

109 raise argparse.ArgumentTypeError(f"expected one of {names_text}, got '{value}'") from error 

110 

111 convert.__name__ = enum_type.__name__.lower() 

112 return convert 

113 

114 

115def opposite_spelling(spelling: str) -> str: 

116 """Return the spelling that sets a boolean the other way: ``zone_map`` <-> ``no_zone_map``.""" 

117 if spelling.startswith("no_"): 

118 return spelling.removeprefix("no_") 

119 return f"no_{spelling}" 

120 

121 

122def destination(section_name: str, field_name: str) -> str: 

123 """Return the parsed-namespace key one section's option is read back from. 

124 

125 Namespaced by section because two sections of one command may declare the same field name -- 

126 ``format`` is the input format to ``source`` and the report format to ``stats`` -- and a bare 

127 field name would land one value in both. 

128 """ 

129 

130 return f"{section_name}__{field_name}" 

131 

132 

133def _add_argument( 

134 parser: argparse._ActionsContainer, section_name: str, section_field: Any, spec: OptionSpec 

135) -> None: 

136 """Add one declared option to a parser or argument group.""" 

137 flag = flag_for(section_field.name, spec) 

138 flags = [f"--{flag}"] 

139 for synonym in spec.synonyms: 

140 flags.append(f"--{synonym}") 

141 if spec.short: 

142 flags.insert(0, f"-{spec.short}") 

143 

144 type_annotation, _optional = unwrap_optional_type(section_field.type) 

145 if type_annotation is bool: 

146 _add_boolean_arguments(parser, section_name, section_field, spec, flags) 

147 _add_constant_arguments(parser, section_name, section_field, spec, flag) 

148 return 

149 

150 keywords: dict[str, Any] = { 

151 "dest": destination(section_name, section_field.name), 

152 "default": argparse.SUPPRESS, 

153 "help": argparse.SUPPRESS if spec.hidden else spec.help, 

154 } 

155 

156 if isinstance(type_annotation, type) and issubclass(type_annotation, Enum): 

157 keywords["type"] = _enum_converter(type_annotation) 

158 keywords["choices"] = list(type_annotation) 

159 keywords["metavar"] = "{" + ",".join(member.name.lower() for member in type_annotation) + "}" 

160 elif get_origin(type_annotation) is tuple: 

161 item_types: list[Any] = [] 

162 for argument in get_args(type_annotation): 

163 if argument is Ellipsis: 

164 continue 

165 item_types.append(argument) 

166 item_type = item_types[0] if item_types else str 

167 if spec.repeatable: 

168 keywords["action"] = AppendItemAction 

169 keywords["type"] = item_type 

170 else: 

171 keywords["type"] = _comma_separated(item_type) 

172 elif type_annotation is Path: 

173 keywords["type"] = Path 

174 else: 

175 keywords["type"] = type_annotation 

176 

177 choices = spec.resolved_choices() 

178 if choices is not None and "choices" not in keywords: 

179 keywords["choices"] = list(choices) 

180 if spec.metavar is not None: 

181 keywords["metavar"] = spec.metavar 

182 elif ( 

183 "metavar" not in keywords 

184 and "choices" not in keywords 

185 and keywords.get("action") in (None, AppendItemAction) 

186 ): 

187 # argparse would name the value after the namespaced dest otherwise. 

188 keywords["metavar"] = flag.upper() 

189 

190 parser.add_argument(*flags, **keywords) 

191 _add_constant_arguments(parser, section_name, section_field, spec, flag) 

192 

193 

194def _add_boolean_arguments( 

195 parser: argparse._ActionsContainer, 

196 section_name: str, 

197 section_field: Any, 

198 spec: OptionSpec, 

199 flags: list[str], 

200) -> None: 

201 """Add the spellings of a boolean option, in Perl VEP's underscore style. 

202 

203 A positive option (``zone_map``) takes ``--zone_map`` and ``--no_zone_map``, plus the hyphenated 

204 ``--no-zone_map`` as a hidden alias. A negative-sense option (``no_stats``) keeps ``--no_stats`` 

205 and gains a hidden ``--stats`` that turns it back off, named in the help of the first. 

206 """ 

207 dest = destination(section_name, section_field.name) 

208 flag = flag_for(section_field.name, spec) 

209 help_text = argparse.SUPPRESS if spec.hidden else spec.help 

210 opposites = [ 

211 f"--{opposite_spelling(spelling.lstrip('-'))}" for spelling in flags if spelling.startswith("--") 

212 ] 

213 

214 if flag.startswith("no_"): 

215 if not spec.hidden: 215 ↛ 217line 215 didn't jump to line 217 because the condition on line 215 was always true

216 help_text = f"{spec.help} ({', '.join(opposites)} turns it back on)" 

217 parser.add_argument(*flags, dest=dest, action="store_true", default=argparse.SUPPRESS, help=help_text) 

218 parser.add_argument( 

219 *opposites, dest=dest, action="store_false", default=argparse.SUPPRESS, help=argparse.SUPPRESS 

220 ) 

221 return 

222 

223 parser.add_argument( 

224 *flags, 

225 *opposites, 

226 dest=dest, 

227 action=BooleanSwitchAction, 

228 false_flags=tuple(opposites), 

229 default=argparse.SUPPRESS, 

230 help=help_text, 

231 ) 

232 hyphenated = [opposite.replace("no_", "no-", 1) for opposite in opposites] 

233 parser.add_argument( 

234 *hyphenated, dest=dest, action="store_false", default=argparse.SUPPRESS, help=argparse.SUPPRESS 

235 ) 

236 

237 

238def _add_constant_arguments( 

239 parser: argparse._ActionsContainer, 

240 section_name: str, 

241 section_field: Any, 

242 spec: OptionSpec, 

243 flag: str, 

244) -> None: 

245 """Add the flags that set one option to a fixed value, as Perl VEP's ``--vcf`` does.""" 

246 

247 for constant_flag, constant in spec.constants.items(): 

248 parser.add_argument( 

249 f"--{constant_flag}", 

250 dest=destination(section_name, section_field.name), 

251 action="store_const", 

252 const=constant, 

253 default=argparse.SUPPRESS, 

254 help=argparse.SUPPRESS if spec.hidden else f"shorthand for --{flag} {constant}", 

255 ) 

256 

257 

258def add_section_arguments(parser: argparse.ArgumentParser, section_type: type[ConfigSection]) -> None: 

259 """Add every option a section declares to a parser, as its own argument group.""" 

260 group = parser.add_argument_group(f"{section_type.section_name} options") 

261 for section_field, spec in section_options(section_type).values(): 

262 _add_argument(group, section_type.section_name, section_field, spec) 

263 

264 

265def check_no_flag_collisions(section_types: tuple[type[ConfigSection], ...]) -> None: 

266 """Raise if two of the given sections declare the same flag. 

267 

268 ``output_file`` means the annotation output to ``run``, the report to ``stats`` and the 

269 explanation to ``explain``; that only matters when one command reads two such sections. 

270 Reported here because argparse's own message names neither section. 

271 

272 Raises: 

273 ValueError: If a flag is declared by more than one of them. 

274 """ 

275 owners: dict[str, list[str]] = {} 

276 for section_type in section_types: 

277 for field_name, (section_field, spec) in section_options(section_type).items(): 

278 for spelling in option_spellings(field_name, spec): 

279 if spelling == field_name and spelling != flag_for(field_name, spec): 

280 # The field name is not a flag when the option renames itself. 

281 continue 

282 owners.setdefault(spelling, []).append(section_type.section_name) 

283 if unwrap_optional_type(section_field.type)[0] is bool: 

284 for spelling in (flag_for(field_name, spec), *spec.synonyms): 

285 owners.setdefault(opposite_spelling(spelling), []).append(section_type.section_name) 

286 for constant_flag in spec.constants: 

287 owners.setdefault(constant_flag, []).append(section_type.section_name) 

288 collisions = {flag: sections for flag, sections in owners.items() if len(sections) > 1} 

289 if collisions: 

290 details: list[str] = [] 

291 for flag, sections in sorted(collisions.items()): 

292 details.append(f"--{flag} in {', '.join(sections)}") 

293 detail = "; ".join(details) 

294 raise ValueError(f"Sections declare colliding flags: {detail}") 

295 

296 

297def build_parser( 

298 prog: str, description: str, section_types: tuple[type[ConfigSection], ...] 

299) -> argparse.ArgumentParser: 

300 """Return a parser exposing exactly the options the given sections declare. 

301 

302 Raises: 

303 ValueError: If two of the sections declare the same flag. 

304 """ 

305 parser = argparse.ArgumentParser( 

306 prog=prog, description=description, formatter_class=argparse.RawDescriptionHelpFormatter 

307 ) 

308 for section_type in section_types: 

309 add_section_arguments(parser, section_type) 

310 return parser 

311 

312 

313def parse_args( 

314 parser: argparse.ArgumentParser, argv: list[str], section_types: tuple[type[ConfigSection], ...] 

315) -> ConfigLayer: 

316 """Parse command-line arguments into a sparse section -> field -> value mapping. 

317 

318 Returns: 

319 ConfigLayer: Only the options actually present on the command line, so a caller can 

320 distinguish "not given" from "given the default value". 

321 """ 

322 given = vars(parser.parse_args(argv)) 

323 layer: ConfigLayer = {} 

324 for section_type in section_types: 

325 values: dict[str, object] = {} 

326 for name in section_options(section_type): 

327 key = destination(section_type.section_name, name) 

328 if key in given: 

329 values[name] = given[key] 

330 if values: 

331 layer[section_type.section_name] = values 

332 return layer