argparsing.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551
  1. import argparse
  2. import os
  3. import sys
  4. import warnings
  5. from gettext import gettext
  6. from typing import Any
  7. from typing import Callable
  8. from typing import cast
  9. from typing import Dict
  10. from typing import List
  11. from typing import Mapping
  12. from typing import NoReturn
  13. from typing import Optional
  14. from typing import Sequence
  15. from typing import Tuple
  16. from typing import TYPE_CHECKING
  17. from typing import Union
  18. import _pytest._io
  19. from _pytest.compat import final
  20. from _pytest.config.exceptions import UsageError
  21. from _pytest.deprecated import ARGUMENT_PERCENT_DEFAULT
  22. from _pytest.deprecated import ARGUMENT_TYPE_STR
  23. from _pytest.deprecated import ARGUMENT_TYPE_STR_CHOICE
  24. from _pytest.deprecated import check_ispytest
  25. if TYPE_CHECKING:
  26. from typing_extensions import Literal
  27. FILE_OR_DIR = "file_or_dir"
  28. @final
  29. class Parser:
  30. """Parser for command line arguments and ini-file values.
  31. :ivar extra_info: Dict of generic param -> value to display in case
  32. there's an error processing the command line arguments.
  33. """
  34. prog: Optional[str] = None
  35. def __init__(
  36. self,
  37. usage: Optional[str] = None,
  38. processopt: Optional[Callable[["Argument"], None]] = None,
  39. *,
  40. _ispytest: bool = False,
  41. ) -> None:
  42. check_ispytest(_ispytest)
  43. self._anonymous = OptionGroup("Custom options", parser=self, _ispytest=True)
  44. self._groups: List[OptionGroup] = []
  45. self._processopt = processopt
  46. self._usage = usage
  47. self._inidict: Dict[str, Tuple[str, Optional[str], Any]] = {}
  48. self._ininames: List[str] = []
  49. self.extra_info: Dict[str, Any] = {}
  50. def processoption(self, option: "Argument") -> None:
  51. if self._processopt:
  52. if option.dest:
  53. self._processopt(option)
  54. def getgroup(
  55. self, name: str, description: str = "", after: Optional[str] = None
  56. ) -> "OptionGroup":
  57. """Get (or create) a named option Group.
  58. :param name: Name of the option group.
  59. :param description: Long description for --help output.
  60. :param after: Name of another group, used for ordering --help output.
  61. :returns: The option group.
  62. The returned group object has an ``addoption`` method with the same
  63. signature as :func:`parser.addoption <pytest.Parser.addoption>` but
  64. will be shown in the respective group in the output of
  65. ``pytest --help``.
  66. """
  67. for group in self._groups:
  68. if group.name == name:
  69. return group
  70. group = OptionGroup(name, description, parser=self, _ispytest=True)
  71. i = 0
  72. for i, grp in enumerate(self._groups):
  73. if grp.name == after:
  74. break
  75. self._groups.insert(i + 1, group)
  76. return group
  77. def addoption(self, *opts: str, **attrs: Any) -> None:
  78. """Register a command line option.
  79. :param opts:
  80. Option names, can be short or long options.
  81. :param attrs:
  82. Same attributes as the argparse library's :py:func:`add_argument()
  83. <argparse.ArgumentParser.add_argument>` function accepts.
  84. After command line parsing, options are available on the pytest config
  85. object via ``config.option.NAME`` where ``NAME`` is usually set
  86. by passing a ``dest`` attribute, for example
  87. ``addoption("--long", dest="NAME", ...)``.
  88. """
  89. self._anonymous.addoption(*opts, **attrs)
  90. def parse(
  91. self,
  92. args: Sequence[Union[str, "os.PathLike[str]"]],
  93. namespace: Optional[argparse.Namespace] = None,
  94. ) -> argparse.Namespace:
  95. from _pytest._argcomplete import try_argcomplete
  96. self.optparser = self._getparser()
  97. try_argcomplete(self.optparser)
  98. strargs = [os.fspath(x) for x in args]
  99. return self.optparser.parse_args(strargs, namespace=namespace)
  100. def _getparser(self) -> "MyOptionParser":
  101. from _pytest._argcomplete import filescompleter
  102. optparser = MyOptionParser(self, self.extra_info, prog=self.prog)
  103. groups = self._groups + [self._anonymous]
  104. for group in groups:
  105. if group.options:
  106. desc = group.description or group.name
  107. arggroup = optparser.add_argument_group(desc)
  108. for option in group.options:
  109. n = option.names()
  110. a = option.attrs()
  111. arggroup.add_argument(*n, **a)
  112. file_or_dir_arg = optparser.add_argument(FILE_OR_DIR, nargs="*")
  113. # bash like autocompletion for dirs (appending '/')
  114. # Type ignored because typeshed doesn't know about argcomplete.
  115. file_or_dir_arg.completer = filescompleter # type: ignore
  116. return optparser
  117. def parse_setoption(
  118. self,
  119. args: Sequence[Union[str, "os.PathLike[str]"]],
  120. option: argparse.Namespace,
  121. namespace: Optional[argparse.Namespace] = None,
  122. ) -> List[str]:
  123. parsedoption = self.parse(args, namespace=namespace)
  124. for name, value in parsedoption.__dict__.items():
  125. setattr(option, name, value)
  126. return cast(List[str], getattr(parsedoption, FILE_OR_DIR))
  127. def parse_known_args(
  128. self,
  129. args: Sequence[Union[str, "os.PathLike[str]"]],
  130. namespace: Optional[argparse.Namespace] = None,
  131. ) -> argparse.Namespace:
  132. """Parse the known arguments at this point.
  133. :returns: An argparse namespace object.
  134. """
  135. return self.parse_known_and_unknown_args(args, namespace=namespace)[0]
  136. def parse_known_and_unknown_args(
  137. self,
  138. args: Sequence[Union[str, "os.PathLike[str]"]],
  139. namespace: Optional[argparse.Namespace] = None,
  140. ) -> Tuple[argparse.Namespace, List[str]]:
  141. """Parse the known arguments at this point, and also return the
  142. remaining unknown arguments.
  143. :returns:
  144. A tuple containing an argparse namespace object for the known
  145. arguments, and a list of the unknown arguments.
  146. """
  147. optparser = self._getparser()
  148. strargs = [os.fspath(x) for x in args]
  149. return optparser.parse_known_args(strargs, namespace=namespace)
  150. def addini(
  151. self,
  152. name: str,
  153. help: str,
  154. type: Optional[
  155. "Literal['string', 'paths', 'pathlist', 'args', 'linelist', 'bool']"
  156. ] = None,
  157. default: Any = None,
  158. ) -> None:
  159. """Register an ini-file option.
  160. :param name:
  161. Name of the ini-variable.
  162. :param type:
  163. Type of the variable. Can be:
  164. * ``string``: a string
  165. * ``bool``: a boolean
  166. * ``args``: a list of strings, separated as in a shell
  167. * ``linelist``: a list of strings, separated by line breaks
  168. * ``paths``: a list of :class:`pathlib.Path`, separated as in a shell
  169. * ``pathlist``: a list of ``py.path``, separated as in a shell
  170. .. versionadded:: 7.0
  171. The ``paths`` variable type.
  172. Defaults to ``string`` if ``None`` or not passed.
  173. :param default:
  174. Default value if no ini-file option exists but is queried.
  175. The value of ini-variables can be retrieved via a call to
  176. :py:func:`config.getini(name) <pytest.Config.getini>`.
  177. """
  178. assert type in (None, "string", "paths", "pathlist", "args", "linelist", "bool")
  179. self._inidict[name] = (help, type, default)
  180. self._ininames.append(name)
  181. class ArgumentError(Exception):
  182. """Raised if an Argument instance is created with invalid or
  183. inconsistent arguments."""
  184. def __init__(self, msg: str, option: Union["Argument", str]) -> None:
  185. self.msg = msg
  186. self.option_id = str(option)
  187. def __str__(self) -> str:
  188. if self.option_id:
  189. return f"option {self.option_id}: {self.msg}"
  190. else:
  191. return self.msg
  192. class Argument:
  193. """Class that mimics the necessary behaviour of optparse.Option.
  194. It's currently a least effort implementation and ignoring choices
  195. and integer prefixes.
  196. https://docs.python.org/3/library/optparse.html#optparse-standard-option-types
  197. """
  198. _typ_map = {"int": int, "string": str, "float": float, "complex": complex}
  199. def __init__(self, *names: str, **attrs: Any) -> None:
  200. """Store params in private vars for use in add_argument."""
  201. self._attrs = attrs
  202. self._short_opts: List[str] = []
  203. self._long_opts: List[str] = []
  204. if "%default" in (attrs.get("help") or ""):
  205. warnings.warn(ARGUMENT_PERCENT_DEFAULT, stacklevel=3)
  206. try:
  207. typ = attrs["type"]
  208. except KeyError:
  209. pass
  210. else:
  211. # This might raise a keyerror as well, don't want to catch that.
  212. if isinstance(typ, str):
  213. if typ == "choice":
  214. warnings.warn(
  215. ARGUMENT_TYPE_STR_CHOICE.format(typ=typ, names=names),
  216. stacklevel=4,
  217. )
  218. # argparse expects a type here take it from
  219. # the type of the first element
  220. attrs["type"] = type(attrs["choices"][0])
  221. else:
  222. warnings.warn(
  223. ARGUMENT_TYPE_STR.format(typ=typ, names=names), stacklevel=4
  224. )
  225. attrs["type"] = Argument._typ_map[typ]
  226. # Used in test_parseopt -> test_parse_defaultgetter.
  227. self.type = attrs["type"]
  228. else:
  229. self.type = typ
  230. try:
  231. # Attribute existence is tested in Config._processopt.
  232. self.default = attrs["default"]
  233. except KeyError:
  234. pass
  235. self._set_opt_strings(names)
  236. dest: Optional[str] = attrs.get("dest")
  237. if dest:
  238. self.dest = dest
  239. elif self._long_opts:
  240. self.dest = self._long_opts[0][2:].replace("-", "_")
  241. else:
  242. try:
  243. self.dest = self._short_opts[0][1:]
  244. except IndexError as e:
  245. self.dest = "???" # Needed for the error repr.
  246. raise ArgumentError("need a long or short option", self) from e
  247. def names(self) -> List[str]:
  248. return self._short_opts + self._long_opts
  249. def attrs(self) -> Mapping[str, Any]:
  250. # Update any attributes set by processopt.
  251. attrs = "default dest help".split()
  252. attrs.append(self.dest)
  253. for attr in attrs:
  254. try:
  255. self._attrs[attr] = getattr(self, attr)
  256. except AttributeError:
  257. pass
  258. if self._attrs.get("help"):
  259. a = self._attrs["help"]
  260. a = a.replace("%default", "%(default)s")
  261. # a = a.replace('%prog', '%(prog)s')
  262. self._attrs["help"] = a
  263. return self._attrs
  264. def _set_opt_strings(self, opts: Sequence[str]) -> None:
  265. """Directly from optparse.
  266. Might not be necessary as this is passed to argparse later on.
  267. """
  268. for opt in opts:
  269. if len(opt) < 2:
  270. raise ArgumentError(
  271. "invalid option string %r: "
  272. "must be at least two characters long" % opt,
  273. self,
  274. )
  275. elif len(opt) == 2:
  276. if not (opt[0] == "-" and opt[1] != "-"):
  277. raise ArgumentError(
  278. "invalid short option string %r: "
  279. "must be of the form -x, (x any non-dash char)" % opt,
  280. self,
  281. )
  282. self._short_opts.append(opt)
  283. else:
  284. if not (opt[0:2] == "--" and opt[2] != "-"):
  285. raise ArgumentError(
  286. "invalid long option string %r: "
  287. "must start with --, followed by non-dash" % opt,
  288. self,
  289. )
  290. self._long_opts.append(opt)
  291. def __repr__(self) -> str:
  292. args: List[str] = []
  293. if self._short_opts:
  294. args += ["_short_opts: " + repr(self._short_opts)]
  295. if self._long_opts:
  296. args += ["_long_opts: " + repr(self._long_opts)]
  297. args += ["dest: " + repr(self.dest)]
  298. if hasattr(self, "type"):
  299. args += ["type: " + repr(self.type)]
  300. if hasattr(self, "default"):
  301. args += ["default: " + repr(self.default)]
  302. return "Argument({})".format(", ".join(args))
  303. class OptionGroup:
  304. """A group of options shown in its own section."""
  305. def __init__(
  306. self,
  307. name: str,
  308. description: str = "",
  309. parser: Optional[Parser] = None,
  310. *,
  311. _ispytest: bool = False,
  312. ) -> None:
  313. check_ispytest(_ispytest)
  314. self.name = name
  315. self.description = description
  316. self.options: List[Argument] = []
  317. self.parser = parser
  318. def addoption(self, *opts: str, **attrs: Any) -> None:
  319. """Add an option to this group.
  320. If a shortened version of a long option is specified, it will
  321. be suppressed in the help. ``addoption('--twowords', '--two-words')``
  322. results in help showing ``--two-words`` only, but ``--twowords`` gets
  323. accepted **and** the automatic destination is in ``args.twowords``.
  324. :param opts:
  325. Option names, can be short or long options.
  326. :param attrs:
  327. Same attributes as the argparse library's :py:func:`add_argument()
  328. <argparse.ArgumentParser.add_argument>` function accepts.
  329. """
  330. conflict = set(opts).intersection(
  331. name for opt in self.options for name in opt.names()
  332. )
  333. if conflict:
  334. raise ValueError("option names %s already added" % conflict)
  335. option = Argument(*opts, **attrs)
  336. self._addoption_instance(option, shortupper=False)
  337. def _addoption(self, *opts: str, **attrs: Any) -> None:
  338. option = Argument(*opts, **attrs)
  339. self._addoption_instance(option, shortupper=True)
  340. def _addoption_instance(self, option: "Argument", shortupper: bool = False) -> None:
  341. if not shortupper:
  342. for opt in option._short_opts:
  343. if opt[0] == "-" and opt[1].islower():
  344. raise ValueError("lowercase shortoptions reserved")
  345. if self.parser:
  346. self.parser.processoption(option)
  347. self.options.append(option)
  348. class MyOptionParser(argparse.ArgumentParser):
  349. def __init__(
  350. self,
  351. parser: Parser,
  352. extra_info: Optional[Dict[str, Any]] = None,
  353. prog: Optional[str] = None,
  354. ) -> None:
  355. self._parser = parser
  356. super().__init__(
  357. prog=prog,
  358. usage=parser._usage,
  359. add_help=False,
  360. formatter_class=DropShorterLongHelpFormatter,
  361. allow_abbrev=False,
  362. )
  363. # extra_info is a dict of (param -> value) to display if there's
  364. # an usage error to provide more contextual information to the user.
  365. self.extra_info = extra_info if extra_info else {}
  366. def error(self, message: str) -> NoReturn:
  367. """Transform argparse error message into UsageError."""
  368. msg = f"{self.prog}: error: {message}"
  369. if hasattr(self._parser, "_config_source_hint"):
  370. # Type ignored because the attribute is set dynamically.
  371. msg = f"{msg} ({self._parser._config_source_hint})" # type: ignore
  372. raise UsageError(self.format_usage() + msg)
  373. # Type ignored because typeshed has a very complex type in the superclass.
  374. def parse_args( # type: ignore
  375. self,
  376. args: Optional[Sequence[str]] = None,
  377. namespace: Optional[argparse.Namespace] = None,
  378. ) -> argparse.Namespace:
  379. """Allow splitting of positional arguments."""
  380. parsed, unrecognized = self.parse_known_args(args, namespace)
  381. if unrecognized:
  382. for arg in unrecognized:
  383. if arg and arg[0] == "-":
  384. lines = ["unrecognized arguments: %s" % (" ".join(unrecognized))]
  385. for k, v in sorted(self.extra_info.items()):
  386. lines.append(f" {k}: {v}")
  387. self.error("\n".join(lines))
  388. getattr(parsed, FILE_OR_DIR).extend(unrecognized)
  389. return parsed
  390. if sys.version_info[:2] < (3, 9): # pragma: no cover
  391. # Backport of https://github.com/python/cpython/pull/14316 so we can
  392. # disable long --argument abbreviations without breaking short flags.
  393. def _parse_optional(
  394. self, arg_string: str
  395. ) -> Optional[Tuple[Optional[argparse.Action], str, Optional[str]]]:
  396. if not arg_string:
  397. return None
  398. if not arg_string[0] in self.prefix_chars:
  399. return None
  400. if arg_string in self._option_string_actions:
  401. action = self._option_string_actions[arg_string]
  402. return action, arg_string, None
  403. if len(arg_string) == 1:
  404. return None
  405. if "=" in arg_string:
  406. option_string, explicit_arg = arg_string.split("=", 1)
  407. if option_string in self._option_string_actions:
  408. action = self._option_string_actions[option_string]
  409. return action, option_string, explicit_arg
  410. if self.allow_abbrev or not arg_string.startswith("--"):
  411. option_tuples = self._get_option_tuples(arg_string)
  412. if len(option_tuples) > 1:
  413. msg = gettext(
  414. "ambiguous option: %(option)s could match %(matches)s"
  415. )
  416. options = ", ".join(option for _, option, _ in option_tuples)
  417. self.error(msg % {"option": arg_string, "matches": options})
  418. elif len(option_tuples) == 1:
  419. (option_tuple,) = option_tuples
  420. return option_tuple
  421. if self._negative_number_matcher.match(arg_string):
  422. if not self._has_negative_number_optionals:
  423. return None
  424. if " " in arg_string:
  425. return None
  426. return None, arg_string, None
  427. class DropShorterLongHelpFormatter(argparse.HelpFormatter):
  428. """Shorten help for long options that differ only in extra hyphens.
  429. - Collapse **long** options that are the same except for extra hyphens.
  430. - Shortcut if there are only two options and one of them is a short one.
  431. - Cache result on the action object as this is called at least 2 times.
  432. """
  433. def __init__(self, *args: Any, **kwargs: Any) -> None:
  434. # Use more accurate terminal width.
  435. if "width" not in kwargs:
  436. kwargs["width"] = _pytest._io.get_terminal_width()
  437. super().__init__(*args, **kwargs)
  438. def _format_action_invocation(self, action: argparse.Action) -> str:
  439. orgstr = super()._format_action_invocation(action)
  440. if orgstr and orgstr[0] != "-": # only optional arguments
  441. return orgstr
  442. res: Optional[str] = getattr(action, "_formatted_action_invocation", None)
  443. if res:
  444. return res
  445. options = orgstr.split(", ")
  446. if len(options) == 2 and (len(options[0]) == 2 or len(options[1]) == 2):
  447. # a shortcut for '-h, --help' or '--abc', '-a'
  448. action._formatted_action_invocation = orgstr # type: ignore
  449. return orgstr
  450. return_list = []
  451. short_long: Dict[str, str] = {}
  452. for option in options:
  453. if len(option) == 2 or option[2] == " ":
  454. continue
  455. if not option.startswith("--"):
  456. raise ArgumentError(
  457. 'long optional argument without "--": [%s]' % (option), option
  458. )
  459. xxoption = option[2:]
  460. shortened = xxoption.replace("-", "")
  461. if shortened not in short_long or len(short_long[shortened]) < len(
  462. xxoption
  463. ):
  464. short_long[shortened] = xxoption
  465. # now short_long has been filled out to the longest with dashes
  466. # **and** we keep the right option ordering from add_argument
  467. for option in options:
  468. if len(option) == 2 or option[2] == " ":
  469. return_list.append(option)
  470. if option[2:] == short_long.get(option.replace("-", "")):
  471. return_list.append(option.replace(" ", "=", 1))
  472. formatted_action_invocation = ", ".join(return_list)
  473. action._formatted_action_invocation = formatted_action_invocation # type: ignore
  474. return formatted_action_invocation
  475. def _split_lines(self, text, width):
  476. """Wrap lines after splitting on original newlines.
  477. This allows to have explicit line breaks in the help text.
  478. """
  479. import textwrap
  480. lines = []
  481. for line in text.splitlines():
  482. lines.extend(textwrap.wrap(line.strip(), width))
  483. return lines