Coverage for src/python/ensembl/vep/cli.py: 100%
102 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"""The ``vep`` command line.
16The first argument selects the command; when it is not a registered one the default is used, so
17``vep --input_file x.vcf`` still parses. ``--config FILE`` may stand anywhere and is taken off
18first, so ``vep --config f.toml corpus describe`` reaches ``corpus describe``. ``vep -h`` lists
19every command and ``vep <group> -h`` the verbs of one group, laid out the way ``git -h`` lays out
20its commands.
21"""
23from __future__ import annotations
25import sys
26from pathlib import Path
28from ensembl.vep.common import setup_logging
29from ensembl.vep.config import Config, load
30from ensembl.vep.config.parser import build_parser
31from ensembl.vep.runner import ExitCode, available_runners, get_runner, runner_default, runner_groups
33# Importing ensembl.vep.runner above is what registers the built-in runners.
35__all__ = ["main", "resolve_command"]
37DEFAULT_COMMAND = "run.default"
38CONFIG_FLAG = "--config"
39HELP_FLAGS = frozenset({"-h", "--help"})
41COMMAND_SECTIONS: tuple[tuple[str, tuple[str, ...]], ...] = (
42 ("annotate variants", ("run",)),
43 ("explain and summarise annotation", ("explain", "stats")),
44 ("build and check the synthetic corpus", ("corpus",)),
45 ("measure annotation speed", ("bench",)),
46 ("maintain the consequence catalogue", ("catalogue",)),
47)
48"""Headings for the help listing, each over the command groups it covers, in display order."""
50OTHER_SECTION = "other commands"
51"""The heading for a registered group no entry in ``COMMAND_SECTIONS`` covers."""
54def _is_verb_group(token: str) -> bool:
55 """Return whether a word names a group of verbs rather than a command of its own."""
56 return token in runner_groups() and token not in available_runners()
59def _section_of(group: str) -> str:
60 """Return the help heading a command group is listed under."""
61 for heading, groups in COMMAND_SECTIONS:
62 if group in groups:
63 return heading
64 return OTHER_SECTION
67def _command_listing(entries: list[tuple[str, str, str]]) -> list[str]:
68 """Return ``(heading, name, description)`` entries as headed, aligned blocks.
70 Headings keep the order they first appear in; names are indented three spaces and padded to
71 the longest, as ``git -h`` lays out its commands.
72 """
73 width = max((len(name) for _heading, name, _description in entries), default=0) + 3
74 by_heading: dict[str, list[str]] = {}
75 for heading, name, description in entries:
76 by_heading.setdefault(heading, []).append(f" {name:<{width}}{description}")
78 lines: list[str] = []
79 for heading, commands in by_heading.items():
80 lines.extend(["", heading, *commands])
81 return lines
84def _usage() -> str:
85 """Return the top-level help, listing every command under the heading of what it is for."""
86 groups = runner_groups()
87 ordered_groups: list[str] = []
88 for _heading, section_groups in COMMAND_SECTIONS:
89 ordered_groups.extend(group for group in section_groups if group in groups)
90 ordered_groups.extend(group for group in groups if group not in ordered_groups)
92 entries = []
93 for group in ordered_groups:
94 for name in groups[group]:
95 entries.append((_section_of(group), name.replace(".", " ", 1), get_runner(name).description))
97 default_invocation = DEFAULT_COMMAND.replace(".", " ", 1)
98 lines = [
99 "usage: vep [-h | --help] [--config <file>] <command> [<verb>] [<options>]",
100 "",
101 "These are the vep commands, grouped by what they are for:",
102 *_command_listing(entries),
103 "",
104 f"Without a command vep runs '{default_invocation}', so 'vep --input_file x.vcf' annotates x.vcf.",
105 "See 'vep <command> -h' for a command's options, or 'vep <group> -h' for a group's verbs.",
106 ]
107 return "\n".join(lines)
110def _group_usage(group: str) -> str:
111 """Return the help for one group of verbs, laid out like the top-level help."""
112 entries = []
113 for name in runner_groups()[group]:
114 entries.append((_section_of(group), name.split(".", 1)[1], get_runner(name).description))
116 lines = [
117 f"usage: vep {group} <verb> [<options>]",
118 "",
119 f"These are the 'vep {group}' verbs:",
120 *_command_listing(entries),
121 "",
122 ]
123 default = runner_default(group)
124 if default is not None:
125 lines.append(f"Without a verb 'vep {group}' runs 'vep {default.replace('.', ' ', 1)}'.")
126 lines.append(f"See 'vep {group} <verb> -h' for a verb's options.")
127 return "\n".join(lines)
130def _help_requested(argv: list[str]) -> str | None:
131 """Return the help page a leading ``-h`` asks for, or None when it belongs to a command.
133 ``vep -h`` and ``vep <group> -h`` are the only two. ``vep --input_file x.vcf -h`` and
134 ``vep run default -h`` still reach the command's own options.
135 """
136 if argv and argv[0] in HELP_FLAGS:
137 return _usage()
138 if len(argv) >= 2 and argv[1] in HELP_FLAGS and _is_verb_group(argv[0]):
139 return _group_usage(argv[0])
140 return None
143def _unknown_command(token: str) -> str:
144 """Return the error and help page for a leading word that is not a command."""
145 if token in runner_groups():
146 return f"vep {token}: needs a verb.\n\n{_group_usage(token)}"
147 return f"vep: '{token}' is not a vep command. See 'vep --help'.\n\n{_usage()}"
150def resolve_command(argv: list[str]) -> tuple[str, list[str]]:
151 """Split arguments into a command name and the arguments that belong to it.
153 A bare group name resolves to that group's single runner if it has one, otherwise stays
154 unresolved so the caller can list its verbs.
156 Only a leading flag, or no arguments at all, means the default command. ``vep`` takes no
157 positional arguments, so a leading bare word can only be a command, and one that is not
158 registered is an error rather than something to pass to the default.
160 Args:
161 argv (list[str]): Arguments without the program name.
163 Returns:
164 tuple[str, list[str]]: The command name and the remaining arguments. The name is empty when
165 the leading word is not a command, or names a group without one of its verbs.
166 """
167 registered = set(available_runners())
168 if not argv or argv[0].startswith("-"):
169 return DEFAULT_COMMAND, argv
170 if argv[0] in registered:
171 return argv[0], argv[1:]
173 groups = runner_groups()
174 if argv[0] in groups:
175 names = groups[argv[0]]
176 if len(argv) > 1 and f"{argv[0]}.{argv[1]}" in registered:
177 return f"{argv[0]}.{argv[1]}", argv[2:]
178 default = runner_default(argv[0])
179 if default is not None:
180 return default, argv[1:]
181 if len(names) == 1:
182 return names[0], argv[1:]
183 return "", argv
186def _take_config_flag(argv: list[str]) -> tuple[list[str], str | None]:
187 """Remove ``--config FILE`` or ``--config=FILE`` from the arguments, if present.
189 Handled here rather than as a declared option: it is read before the command is resolved, so
190 it may stand before or after it, and belongs to no one section. The last occurrence wins.
192 Args:
193 argv (list[str]): Every argument, without the program name.
195 Returns:
196 tuple[list[str], str | None]: The arguments without the flag, and the file it named.
198 Raises:
199 ValueError: If the flag has no file after it.
200 """
201 remaining_args: list[str] = []
202 config_file: str | None = None
203 index = 0
204 while index < len(argv):
205 argument = argv[index]
206 if argument == CONFIG_FLAG:
207 if index + 1 >= len(argv):
208 raise ValueError(f"argument {CONFIG_FLAG}: expected one argument")
209 config_file = argv[index + 1]
210 index += 2
211 continue
212 if argument.startswith(f"{CONFIG_FLAG}="):
213 config_file = argument.split("=", 1)[1]
214 if not config_file:
215 raise ValueError(f"argument {CONFIG_FLAG}: expected one argument")
216 index += 1
217 continue
218 remaining_args.append(argument)
219 index += 1
220 return remaining_args, config_file
223def main(argv: list[str] | None = None) -> ExitCode:
224 """Run a command and return its exit code.
226 Args:
227 argv (list[str] | None): Arguments without the program name, or None for ``sys.argv[1:]``.
229 Returns:
230 ExitCode: The runner's exit code, ``OK`` after printing a help page, or ``USAGE`` if no
231 command could be resolved, ``--config`` is malformed, or the configuration is invalid
232 or unreadable.
233 """
234 try:
235 arguments, config_file = _take_config_flag(list(sys.argv[1:] if argv is None else argv))
236 except ValueError as invalid:
237 print(f"vep: error: {invalid}", file=sys.stderr)
238 return ExitCode.USAGE
240 help_page = _help_requested(arguments)
241 if help_page is not None:
242 print(help_page)
243 return ExitCode.OK
245 command, remaining_args = resolve_command(arguments)
246 if not command:
247 print(_unknown_command(arguments[0]), file=sys.stderr)
248 return ExitCode.USAGE
250 runner_type = get_runner(command)
251 section_types = Config.section_types_for(runner_type.sections)
252 parser = build_parser(f"vep {command.replace('.', ' ', 1)}", runner_type.description, section_types)
253 parser.add_argument(
254 CONFIG_FLAG, metavar="FILE", default=None, help="read options from a TOML or Perl VEP config file"
255 )
257 try:
258 config = load(
259 remaining_args,
260 command=command,
261 section_names=runner_type.sections,
262 parser=parser,
263 config_file=Path(config_file) if config_file else None,
264 )
265 except OSError as unreadable:
266 if config_file is None:
267 # Nothing else in load() reads a file, so an OSError here is not ours to explain away.
268 raise
269 parser.print_usage(sys.stderr)
270 reason = unreadable.strerror or unreadable
271 print(f"{parser.prog}: error: cannot read config file '{config_file}': {reason}", file=sys.stderr)
272 return ExitCode.USAGE
273 except ValueError as invalid:
274 parser.print_usage(sys.stderr)
275 print(f"{parser.prog}: error: {invalid}", file=sys.stderr)
276 return ExitCode.USAGE
277 setup_logging(config.logging.effective_level().upper(), config.logging.log_file)
278 return runner_type(config).run()
281if __name__ == "__main__":
282 raise SystemExit(main())