Debian Codegraph @

src/_pytest/config/argparsing.py

raw
1 # mypy: allow-untyped-defs
2 from __future__ import annotations
3
4 import argparse
5 from collections.abc import Callable
6 from collections.abc import Sequence
7 import os
8 import sys
9 import textwrap
10 from typing import Any
11 from typing import final
12 from typing import Literal
13 from typing import NoReturn
14
15 from .exceptions import UsageError
16 import _pytest._io
17 from _pytest.compat import NOTSET
18 from _pytest.deprecated import check_ispytest
19
20
21 FILE_OR_DIR = "file_or_dir"
22
23
24 @final
25 class Parser:
26 """Parser for command line arguments and config-file values.
27
28 :ivar extra_info: Dict of generic param -> value to display in case
29 there's an error processing the command line arguments.
30 """
31
32 def __init__(
33 self,
34 usage: str | None = None,
35 processopt: Callable[[Argument], None] | None = None,
36 *,
37 prog: str | None = None,
38 _ispytest: bool = False,
39 ) -> None:
40 check_ispytest(_ispytest)
41
42 from _pytest._argcomplete import filescompleter
43
44 self._processopt = processopt
45 self.extra_info: dict[str, Any] = {}
46 self.optparser = PytestArgumentParser(usage, self.extra_info, prog=prog)
47 anonymous_arggroup = self.optparser.add_argument_group("Custom options")
48 self._anonymous = OptionGroup(
49 anonymous_arggroup, "_anonymous", self, _ispytest=True
50 )
51 self._groups = [self._anonymous]
52 # Maps option strings -> dest, e.g. "-V" and "--version" to "version".
53 self._opt2dest: dict[str, str] = {}
54 file_or_dir_arg = self.optparser.add_argument(FILE_OR_DIR, nargs="*")
55 file_or_dir_arg.completer = filescompleter # type: ignore
56
57 self._inidict: dict[str, tuple[str, str, Any]] = {}
58 # Maps alias -> canonical name.
59 self._ini_aliases: dict[str, str] = {}
60
61 @property
62 def prog(self) -> str:
63 return self.optparser.prog
64
65 @prog.setter
66 def prog(self, value: str) -> None:
67 self.optparser.prog = value
68
69 def processoption(self, option: Argument) -> None:
70 if self._processopt:
71 if option.dest:
72 self._processopt(option)
73
74 def getgroup(
75 self, name: str, description: str = "", after: str | None = None
76 ) -> OptionGroup:
77 """Get (or create) a named option Group.
78
79 :param name: Name of the option group.
80 :param description: Long description for --help output.
81 :param after: Name of another group, used for ordering --help output.
82 :returns: The option group.
83
84 The returned group object has an ``addoption`` method with the same
85 signature as :func:`parser.addoption <pytest.Parser.addoption>` but
86 will be shown in the respective group in the output of
87 ``pytest --help``.
88 """
89 for group in self._groups:
90 if group.name == name:
91 return group
92
93 arggroup = self.optparser.add_argument_group(description or name)
94 group = OptionGroup(arggroup, name, self, _ispytest=True)
95 i = 0
96 for i, grp in enumerate(self._groups):
97 if grp.name == after:
98 break
99 self._groups.insert(i + 1, group)
100 # argparse doesn't provide a way to control `--help` order, so must
101 # access its internals ☹.
102 self.optparser._action_groups.insert(i + 1, self.optparser._action_groups.pop())
103 return group
104
105 def addoption(self, *opts: str, **attrs: Any) -> None:
106 """Register a command line option.
107
108 :param opts:
109 Option names, can be short or long options.
110 :param attrs:
111 Same attributes as the argparse library's :meth:`add_argument()
112 <argparse.ArgumentParser.add_argument>` function accepts.
113
114 After command line parsing, options are available on the pytest config
115 object via ``config.option.NAME`` where ``NAME`` is usually set
116 by passing a ``dest`` attribute, for example
117 ``addoption("--long", dest="NAME", ...)``.
118 """
119 self._anonymous.addoption(*opts, **attrs)
120
121 def parse(
122 self,
123 args: Sequence[str | os.PathLike[str]],
124 namespace: argparse.Namespace | None = None,
125 ) -> argparse.Namespace:
126 """Parse the arguments.
127
128 Unlike ``parse_known_args`` and ``parse_known_and_unknown_args``,
129 raises PrintHelp on `--help` and UsageError on unknown flags
130
131 :meta private:
132 """
133 from _pytest._argcomplete import try_argcomplete
134
135 try_argcomplete(self.optparser)
136 strargs = [os.fspath(x) for x in args]
137 if namespace is None:
138 namespace = argparse.Namespace()
139 try:
140 namespace._raise_print_help = True
141 return self.optparser.parse_intermixed_args(strargs, namespace=namespace)
142 finally:
143 del namespace._raise_print_help
144
145 def parse_known_args(
146 self,
147 args: Sequence[str | os.PathLike[str]],
148 namespace: argparse.Namespace | None = None,
149 ) -> argparse.Namespace:
150 """Parse the known arguments at this point.
151
152 :returns: An argparse namespace object.
153 """
154 return self.parse_known_and_unknown_args(args, namespace=namespace)[0]
155
156 def parse_known_and_unknown_args(
157 self,
158 args: Sequence[str | os.PathLike[str]],
159 namespace: argparse.Namespace | None = None,
160 ) -> tuple[argparse.Namespace, list[str]]:
161 """Parse the known arguments at this point, and also return the
162 remaining unknown flag arguments.
163
164 :returns:
165 A tuple containing an argparse namespace object for the known
166 arguments, and a list of unknown flag arguments.
167 """
168 strargs = [os.fspath(x) for x in args]
169 if sys.version_info < (3, 12, 8) or (3, 13) <= sys.version_info < (3, 13, 1):
170 # Older argparse have a bugged parse_known_intermixed_args.
171 namespace, unknown = self.optparser.parse_known_args(strargs, namespace)
172 assert namespace is not None
173 file_or_dir = getattr(namespace, FILE_OR_DIR)
174 unknown_flags: list[str] = []
175 for arg in unknown:
176 (unknown_flags if arg.startswith("-") else file_or_dir).append(arg)
177 return namespace, unknown_flags
178 else:
179 return self.optparser.parse_known_intermixed_args(strargs, namespace)
180
181 def addini(
182 self,
183 name: str,
184 help: str,
185 type: Literal[
186 "string", "paths", "pathlist", "args", "linelist", "bool", "int", "float"
187 ]
188 | None = None,
189 default: Any = NOTSET,
190 *,
191 aliases: Sequence[str] = (),
192 ) -> None:
193 """Register a configuration file option.
194
195 :param name:
196 Name of the configuration.
197 :param type:
198 Type of the configuration. Can be:
199
200 * ``string``: a string
201 * ``bool``: a boolean
202 * ``args``: a list of strings, separated as in a shell
203 * ``linelist``: a list of strings, separated by line breaks
204 * ``paths``: a list of :class:`pathlib.Path`, separated as in a shell
205 * ``pathlist``: a list of ``py.path``, separated as in a shell
206 * ``int``: an integer
207 * ``float``: a floating-point number
208
209 .. versionadded:: 8.4
210
211 The ``float`` and ``int`` types.
212
213 For ``paths`` and ``pathlist`` types, they are considered relative to the config-file.
214 In case the execution is happening without a config-file defined,
215 they will be considered relative to the current working directory (for example with ``--override-ini``).
216
217 .. versionadded:: 7.0
218 The ``paths`` variable type.
219
220 .. versionadded:: 8.1
221 Use the current working directory to resolve ``paths`` and ``pathlist`` in the absence of a config-file.
222
223 Defaults to ``string`` if ``None`` or not passed.
224 :param default:
225 Default value if no config-file option exists but is queried.
226 :param aliases:
227 Additional names by which this option can be referenced.
228 Aliases resolve to the canonical name.
229
230 .. versionadded:: 9.0
231 The ``aliases`` parameter.
232
233 The value of configuration keys can be retrieved via a call to
234 :py:func:`config.getini(name) <pytest.Config.getini>`.
235 """
236 assert type in (
237 None,
238 "string",
239 "paths",
240 "pathlist",
241 "args",
242 "linelist",
243 "bool",
244 "int",
245 "float",
246 )
247 if type is None:
248 type = "string"
249 if default is NOTSET:
250 default = get_ini_default_for_type(type)
251
252 self._inidict[name] = (help, type, default)
253
254 for alias in aliases:
255 if alias in self._inidict:
256 raise ValueError(
257 f"alias {alias!r} conflicts with existing configuration option"
258 )
259 if (already := self._ini_aliases.get(alias)) is not None:
260 raise ValueError(f"{alias!r} is already an alias of {already!r}")
261 self._ini_aliases[alias] = name
262
263
264 def get_ini_default_for_type(
265 type: Literal[
266 "string", "paths", "pathlist", "args", "linelist", "bool", "int", "float"
267 ],
268 ) -> Any:
269 """
270 Used by addini to get the default value for a given config option type, when
271 default is not supplied.
272 """
273 if type in ("paths", "pathlist", "args", "linelist"):
274 return []
275 elif type == "bool":
276 return False
277 elif type == "int":
278 return 0
279 elif type == "float":
280 return 0.0
281 else:
282 return ""
283
284
285 class Argument:
286 """An option defined in an OptionGroup."""
287
288 def __init__(self, action: argparse.Action) -> None:
289 self._action = action
290
291 def attrs(self) -> dict[str, Any]:
292 return self._action.__dict__
293
294 def names(self) -> Sequence[str]:
295 return self._action.option_strings
296
297 @property
298 def dest(self) -> str:
299 return self._action.dest
300
301 @property
302 def default(self) -> Any:
303 return self._action.default
304
305 @property
306 def type(self) -> Any | None:
307 return self._action.type
308
309 def __repr__(self) -> str:
310 action = getattr(self, "_action", None)
311 if action is None:
312 return "Argument(<uninitialized>)"
313 args: list[str] = []
314 args += ["opts: " + repr(self.names())]
315 args += ["dest: " + repr(self.dest)]
316 if action.type:
317 args += ["type: " + repr(self.type)]
318 args += ["default: " + repr(self.default)]
319 return "Argument({})".format(", ".join(args))
320
321
322 class OptionGroup:
323 """A group of options shown in its own section."""
324
325 def __init__(
326 self,
327 arggroup: argparse._ArgumentGroup,
328 name: str,
329 parser: Parser | None,
330 _ispytest: bool = False,
331 ) -> None:
332 check_ispytest(_ispytest)
333 self._arggroup = arggroup
334 self.name = name
335 self.options: list[Argument] = []
336 self.parser = parser
337
338 def addoption(self, *opts: str, **attrs: Any) -> None:
339 """Add an option to this group.
340
341 If a shortened version of a long option is specified, it will
342 be suppressed in the help. ``addoption('--twowords', '--two-words')``
343 results in help showing ``--two-words`` only, but ``--twowords`` gets
344 accepted **and** the automatic destination is in ``args.twowords``.
345
346 :param opts:
347 Option names, can be short or long options.
348 Note that lower-case short options (e.g. `-x`) are reserved.
349 :param attrs:
350 Same attributes as the argparse library's :meth:`add_argument()
351 <argparse.ArgumentParser.add_argument>` function accepts.
352 """
353 conflict = set(opts).intersection(
354 name for opt in self.options for name in opt.names()
355 )
356 if conflict:
357 raise ValueError(f"option names {conflict} already added")
358 self._addoption_inner(opts, attrs, allow_reserved=False)
359
360 def _addoption(self, *opts: str, **attrs: Any) -> None:
361 """Like addoption(), but also allows registering short lower case options (e.g. -x),
362 which are reserved for pytest core."""
363 self._addoption_inner(opts, attrs, allow_reserved=True)
364
365 def _addoption_inner(
366 self, opts: tuple[str, ...], attrs: dict[str, Any], allow_reserved: bool
367 ) -> None:
368 if not allow_reserved:
369 for opt in opts:
370 if len(opt) >= 2 and opt[0] == "-" and opt[1].islower():
371 raise ValueError("lowercase short options are reserved")
372
373 action = self._arggroup.add_argument(*opts, **attrs)
374 option = Argument(action)
375 self.options.append(option)
376 if self.parser:
377 for name in option.names():
378 self.parser._opt2dest[name] = option.dest
379 self.parser.processoption(option)
380
381
382 class PytestArgumentParser(argparse.ArgumentParser):
383 def __init__(
384 self,
385 usage: str | None,
386 extra_info: dict[str, str],
387 *,
388 prog: str | None = None,
389 ) -> None:
390 super().__init__(
391 usage=usage,
392 prog=prog,
393 add_help=False,
394 formatter_class=DropShorterLongHelpFormatter,
395 allow_abbrev=False,
396 fromfile_prefix_chars="@",
397 )
398 # extra_info is a dict of (param -> value) to display if there's
399 # an usage error to provide more contextual information to the user.
400 self.extra_info = extra_info
401
402 def error(self, message: str) -> NoReturn:
403 """Transform argparse error message into UsageError."""
404 # TODO(py313): Replace with `exit_on_error=False`. Note that while it
405 # was added in Python 3.9, it was broken until 3.13 (cpython#121018).
406 msg = f"{self.prog}: error: {message}"
407 if self.extra_info:
408 msg += "\n" + "\n".join(
409 f" {k}: {v}" for k, v in sorted(self.extra_info.items())
410 )
411 raise UsageError(self.format_usage() + msg)
412
413
414 class DropShorterLongHelpFormatter(argparse.HelpFormatter):
415 """Shorten help for long options that differ only in extra hyphens.
416
417 - Collapse **long** options that are the same except for extra hyphens.
418 - Shortcut if there are only two options and one of them is a short one.
419 """
420
421 def __init__(self, *args: Any, **kwargs: Any) -> None:
422 # Use more accurate terminal width.
423 if "width" not in kwargs:
424 kwargs["width"] = _pytest._io.get_terminal_width()
425 super().__init__(*args, **kwargs)
426
427 def _format_action_invocation(self, action: argparse.Action) -> str:
428 orgstr = super()._format_action_invocation(action)
429 if orgstr and orgstr[0] != "-": # only optional arguments
430 return orgstr
431 options = orgstr.split(", ")
432 if len(options) == 2 and (len(options[0]) == 2 or len(options[1]) == 2):
433 # a shortcut for '-h, --help' or '--abc', '-a'
434 return orgstr
435 return_list = []
436 short_long: dict[str, str] = {}
437 for option in options:
438 if len(option) == 2 or option[2] == " ":
439 continue
440 assert option.startswith("--"), (
441 f'long optional argument without "--": [{option}]'
442 )
443 xxoption = option[2:]
444 shortened = xxoption.replace("-", "")
445 if shortened not in short_long or len(short_long[shortened]) < len(
446 xxoption
447 ):
448 short_long[shortened] = xxoption
449 # now short_long has been filled out to the longest with dashes
450 # **and** we keep the right option ordering from add_argument
451 for option in options:
452 if len(option) == 2 or option[2] == " ":
453 return_list.append(option)
454 if option[2:] == short_long.get(option.replace("-", "")):
455 return_list.append(option.replace(" ", "=", 1))
456 return ", ".join(return_list)
457
458 def _split_lines(self, text: str, width: int) -> list[str]:
459 """Wrap lines after splitting on original newlines.
460
461 This allows to have explicit line breaks in the help text.
462 """
463 lines = []
464 for line in text.splitlines():
465 lines.extend(textwrap.wrap(line.strip(), width))
466 return lines
467
468
469 class OverrideIniAction(argparse.Action):
470 """Custom argparse action that makes a CLI flag equivalent to overriding an
471 option, in addition to behaving like `store_true`.
472
473 This can simplify things since code only needs to inspect the config option
474 and not consider the CLI flag.
475 """
476
477 def __init__(
478 self,
479 option_strings: Sequence[str],
480 dest: str,
481 nargs: int | str | None = None,
482 *args,
483 ini_option: str,
484 ini_value: str,
485 **kwargs,
486 ) -> None:
487 super().__init__(option_strings, dest, 0, *args, **kwargs)
488 self.ini_option = ini_option
489 self.ini_value = ini_value
490
491 def __call__(
492 self,
493 parser: argparse.ArgumentParser,
494 namespace: argparse.Namespace,
495 *args,
496 **kwargs,
497 ) -> None:
498 setattr(namespace, self.dest, True)
499 current_overrides = getattr(namespace, "override_ini", None)
500 if current_overrides is None:
501 current_overrides = []
502 current_overrides.append(f"{self.ini_option}={self.ini_value}")
503 setattr(namespace, "override_ini", current_overrides)