argparsing.py 20 KB

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