argparsing.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  1. # -*- coding: utf-8 -*-
  2. import argparse
  3. import warnings
  4. import py
  5. import six
  6. from _pytest.config.exceptions import UsageError
  7. FILE_OR_DIR = "file_or_dir"
  8. class Parser(object):
  9. """ Parser for command line arguments and ini-file values.
  10. :ivar extra_info: dict of generic param -> value to display in case
  11. there's an error processing the command line arguments.
  12. """
  13. prog = None
  14. def __init__(self, usage=None, processopt=None):
  15. self._anonymous = OptionGroup("custom options", parser=self)
  16. self._groups = []
  17. self._processopt = processopt
  18. self._usage = usage
  19. self._inidict = {}
  20. self._ininames = []
  21. self.extra_info = {}
  22. def processoption(self, option):
  23. if self._processopt:
  24. if option.dest:
  25. self._processopt(option)
  26. def getgroup(self, name, description="", after=None):
  27. """ get (or create) a named option Group.
  28. :name: name of the option group.
  29. :description: long description for --help output.
  30. :after: name of other group, used for ordering --help output.
  31. The returned group object has an ``addoption`` method with the same
  32. signature as :py:func:`parser.addoption
  33. <_pytest.config.Parser.addoption>` but will be shown in the
  34. respective group in the output of ``pytest. --help``.
  35. """
  36. for group in self._groups:
  37. if group.name == name:
  38. return group
  39. group = OptionGroup(name, description, parser=self)
  40. i = 0
  41. for i, grp in enumerate(self._groups):
  42. if grp.name == after:
  43. break
  44. self._groups.insert(i + 1, group)
  45. return group
  46. def addoption(self, *opts, **attrs):
  47. """ register a command line option.
  48. :opts: option names, can be short or long options.
  49. :attrs: same attributes which the ``add_option()`` function of the
  50. `argparse library
  51. <http://docs.python.org/2/library/argparse.html>`_
  52. accepts.
  53. After command line parsing options are available on the pytest config
  54. object via ``config.option.NAME`` where ``NAME`` is usually set
  55. by passing a ``dest`` attribute, for example
  56. ``addoption("--long", dest="NAME", ...)``.
  57. """
  58. self._anonymous.addoption(*opts, **attrs)
  59. def parse(self, args, namespace=None):
  60. from _pytest._argcomplete import try_argcomplete
  61. self.optparser = self._getparser()
  62. try_argcomplete(self.optparser)
  63. args = [str(x) if isinstance(x, py.path.local) else x for x in args]
  64. return self.optparser.parse_args(args, namespace=namespace)
  65. def _getparser(self):
  66. from _pytest._argcomplete import filescompleter
  67. optparser = MyOptionParser(self, self.extra_info, prog=self.prog)
  68. groups = self._groups + [self._anonymous]
  69. for group in groups:
  70. if group.options:
  71. desc = group.description or group.name
  72. arggroup = optparser.add_argument_group(desc)
  73. for option in group.options:
  74. n = option.names()
  75. a = option.attrs()
  76. arggroup.add_argument(*n, **a)
  77. # bash like autocompletion for dirs (appending '/')
  78. optparser.add_argument(FILE_OR_DIR, nargs="*").completer = filescompleter
  79. return optparser
  80. def parse_setoption(self, args, option, namespace=None):
  81. parsedoption = self.parse(args, namespace=namespace)
  82. for name, value in parsedoption.__dict__.items():
  83. setattr(option, name, value)
  84. return getattr(parsedoption, FILE_OR_DIR)
  85. def parse_known_args(self, args, namespace=None):
  86. """parses and returns a namespace object with known arguments at this
  87. point.
  88. """
  89. return self.parse_known_and_unknown_args(args, namespace=namespace)[0]
  90. def parse_known_and_unknown_args(self, args, namespace=None):
  91. """parses and returns a namespace object with known arguments, and
  92. the remaining arguments unknown at this point.
  93. """
  94. optparser = self._getparser()
  95. args = [str(x) if isinstance(x, py.path.local) else x for x in args]
  96. return optparser.parse_known_args(args, namespace=namespace)
  97. def addini(self, name, help, type=None, default=None):
  98. """ register an ini-file option.
  99. :name: name of the ini-variable
  100. :type: type of the variable, can be ``pathlist``, ``args``, ``linelist``
  101. or ``bool``.
  102. :default: default value if no ini-file option exists but is queried.
  103. The value of ini-variables can be retrieved via a call to
  104. :py:func:`config.getini(name) <_pytest.config.Config.getini>`.
  105. """
  106. assert type in (None, "pathlist", "args", "linelist", "bool")
  107. self._inidict[name] = (help, type, default)
  108. self._ininames.append(name)
  109. class ArgumentError(Exception):
  110. """
  111. Raised if an Argument instance is created with invalid or
  112. inconsistent arguments.
  113. """
  114. def __init__(self, msg, option):
  115. self.msg = msg
  116. self.option_id = str(option)
  117. def __str__(self):
  118. if self.option_id:
  119. return "option %s: %s" % (self.option_id, self.msg)
  120. else:
  121. return self.msg
  122. class Argument(object):
  123. """class that mimics the necessary behaviour of optparse.Option
  124. it's currently a least effort implementation
  125. and ignoring choices and integer prefixes
  126. https://docs.python.org/3/library/optparse.html#optparse-standard-option-types
  127. """
  128. _typ_map = {"int": int, "string": str, "float": float, "complex": complex}
  129. def __init__(self, *names, **attrs):
  130. """store parms in private vars for use in add_argument"""
  131. self._attrs = attrs
  132. self._short_opts = []
  133. self._long_opts = []
  134. self.dest = attrs.get("dest")
  135. if "%default" in (attrs.get("help") or ""):
  136. warnings.warn(
  137. 'pytest now uses argparse. "%default" should be'
  138. ' changed to "%(default)s" ',
  139. DeprecationWarning,
  140. stacklevel=3,
  141. )
  142. try:
  143. typ = attrs["type"]
  144. except KeyError:
  145. pass
  146. else:
  147. # this might raise a keyerror as well, don't want to catch that
  148. if isinstance(typ, six.string_types):
  149. if typ == "choice":
  150. warnings.warn(
  151. "`type` argument to addoption() is the string %r."
  152. " For choices this is optional and can be omitted, "
  153. " but when supplied should be a type (for example `str` or `int`)."
  154. " (options: %s)" % (typ, names),
  155. DeprecationWarning,
  156. stacklevel=4,
  157. )
  158. # argparse expects a type here take it from
  159. # the type of the first element
  160. attrs["type"] = type(attrs["choices"][0])
  161. else:
  162. warnings.warn(
  163. "`type` argument to addoption() is the string %r, "
  164. " but when supplied should be a type (for example `str` or `int`)."
  165. " (options: %s)" % (typ, names),
  166. DeprecationWarning,
  167. stacklevel=4,
  168. )
  169. attrs["type"] = Argument._typ_map[typ]
  170. # used in test_parseopt -> test_parse_defaultgetter
  171. self.type = attrs["type"]
  172. else:
  173. self.type = typ
  174. try:
  175. # attribute existence is tested in Config._processopt
  176. self.default = attrs["default"]
  177. except KeyError:
  178. pass
  179. self._set_opt_strings(names)
  180. if not self.dest:
  181. if self._long_opts:
  182. self.dest = self._long_opts[0][2:].replace("-", "_")
  183. else:
  184. try:
  185. self.dest = self._short_opts[0][1:]
  186. except IndexError:
  187. raise ArgumentError("need a long or short option", self)
  188. def names(self):
  189. return self._short_opts + self._long_opts
  190. def attrs(self):
  191. # update any attributes set by processopt
  192. attrs = "default dest help".split()
  193. if self.dest:
  194. attrs.append(self.dest)
  195. for attr in attrs:
  196. try:
  197. self._attrs[attr] = getattr(self, attr)
  198. except AttributeError:
  199. pass
  200. if self._attrs.get("help"):
  201. a = self._attrs["help"]
  202. a = a.replace("%default", "%(default)s")
  203. # a = a.replace('%prog', '%(prog)s')
  204. self._attrs["help"] = a
  205. return self._attrs
  206. def _set_opt_strings(self, opts):
  207. """directly from optparse
  208. might not be necessary as this is passed to argparse later on"""
  209. for opt in opts:
  210. if len(opt) < 2:
  211. raise ArgumentError(
  212. "invalid option string %r: "
  213. "must be at least two characters long" % opt,
  214. self,
  215. )
  216. elif len(opt) == 2:
  217. if not (opt[0] == "-" and opt[1] != "-"):
  218. raise ArgumentError(
  219. "invalid short option string %r: "
  220. "must be of the form -x, (x any non-dash char)" % opt,
  221. self,
  222. )
  223. self._short_opts.append(opt)
  224. else:
  225. if not (opt[0:2] == "--" and opt[2] != "-"):
  226. raise ArgumentError(
  227. "invalid long option string %r: "
  228. "must start with --, followed by non-dash" % opt,
  229. self,
  230. )
  231. self._long_opts.append(opt)
  232. def __repr__(self):
  233. args = []
  234. if self._short_opts:
  235. args += ["_short_opts: " + repr(self._short_opts)]
  236. if self._long_opts:
  237. args += ["_long_opts: " + repr(self._long_opts)]
  238. args += ["dest: " + repr(self.dest)]
  239. if hasattr(self, "type"):
  240. args += ["type: " + repr(self.type)]
  241. if hasattr(self, "default"):
  242. args += ["default: " + repr(self.default)]
  243. return "Argument({})".format(", ".join(args))
  244. class OptionGroup(object):
  245. def __init__(self, name, description="", parser=None):
  246. self.name = name
  247. self.description = description
  248. self.options = []
  249. self.parser = parser
  250. def addoption(self, *optnames, **attrs):
  251. """ add an option to this group.
  252. if a shortened version of a long option is specified it will
  253. be suppressed in the help. addoption('--twowords', '--two-words')
  254. results in help showing '--two-words' only, but --twowords gets
  255. accepted **and** the automatic destination is in args.twowords
  256. """
  257. conflict = set(optnames).intersection(
  258. name for opt in self.options for name in opt.names()
  259. )
  260. if conflict:
  261. raise ValueError("option names %s already added" % conflict)
  262. option = Argument(*optnames, **attrs)
  263. self._addoption_instance(option, shortupper=False)
  264. def _addoption(self, *optnames, **attrs):
  265. option = Argument(*optnames, **attrs)
  266. self._addoption_instance(option, shortupper=True)
  267. def _addoption_instance(self, option, shortupper=False):
  268. if not shortupper:
  269. for opt in option._short_opts:
  270. if opt[0] == "-" and opt[1].islower():
  271. raise ValueError("lowercase shortoptions reserved")
  272. if self.parser:
  273. self.parser.processoption(option)
  274. self.options.append(option)
  275. class MyOptionParser(argparse.ArgumentParser):
  276. def __init__(self, parser, extra_info=None, prog=None):
  277. if not extra_info:
  278. extra_info = {}
  279. self._parser = parser
  280. argparse.ArgumentParser.__init__(
  281. self,
  282. prog=prog,
  283. usage=parser._usage,
  284. add_help=False,
  285. formatter_class=DropShorterLongHelpFormatter,
  286. )
  287. # extra_info is a dict of (param -> value) to display if there's
  288. # an usage error to provide more contextual information to the user
  289. self.extra_info = extra_info
  290. def error(self, message):
  291. """Transform argparse error message into UsageError."""
  292. msg = "%s: error: %s" % (self.prog, message)
  293. if hasattr(self._parser, "_config_source_hint"):
  294. msg = "%s (%s)" % (msg, self._parser._config_source_hint)
  295. raise UsageError(self.format_usage() + msg)
  296. def parse_args(self, args=None, namespace=None):
  297. """allow splitting of positional arguments"""
  298. args, argv = self.parse_known_args(args, namespace)
  299. if argv:
  300. for arg in argv:
  301. if arg and arg[0] == "-":
  302. lines = ["unrecognized arguments: %s" % (" ".join(argv))]
  303. for k, v in sorted(self.extra_info.items()):
  304. lines.append(" %s: %s" % (k, v))
  305. self.error("\n".join(lines))
  306. getattr(args, FILE_OR_DIR).extend(argv)
  307. return args
  308. class DropShorterLongHelpFormatter(argparse.HelpFormatter):
  309. """shorten help for long options that differ only in extra hyphens
  310. - collapse **long** options that are the same except for extra hyphens
  311. - special action attribute map_long_option allows surpressing additional
  312. long options
  313. - shortcut if there are only two options and one of them is a short one
  314. - cache result on action object as this is called at least 2 times
  315. """
  316. def _format_action_invocation(self, action):
  317. orgstr = argparse.HelpFormatter._format_action_invocation(self, action)
  318. if orgstr and orgstr[0] != "-": # only optional arguments
  319. return orgstr
  320. res = getattr(action, "_formatted_action_invocation", None)
  321. if res:
  322. return res
  323. options = orgstr.split(", ")
  324. if len(options) == 2 and (len(options[0]) == 2 or len(options[1]) == 2):
  325. # a shortcut for '-h, --help' or '--abc', '-a'
  326. action._formatted_action_invocation = orgstr
  327. return orgstr
  328. return_list = []
  329. option_map = getattr(action, "map_long_option", {})
  330. if option_map is None:
  331. option_map = {}
  332. short_long = {}
  333. for option in options:
  334. if len(option) == 2 or option[2] == " ":
  335. continue
  336. if not option.startswith("--"):
  337. raise ArgumentError(
  338. 'long optional argument without "--": [%s]' % (option), self
  339. )
  340. xxoption = option[2:]
  341. if xxoption.split()[0] not in option_map:
  342. shortened = xxoption.replace("-", "")
  343. if shortened not in short_long or len(short_long[shortened]) < len(
  344. xxoption
  345. ):
  346. short_long[shortened] = xxoption
  347. # now short_long has been filled out to the longest with dashes
  348. # **and** we keep the right option ordering from add_argument
  349. for option in options:
  350. if len(option) == 2 or option[2] == " ":
  351. return_list.append(option)
  352. if option[2:] == short_long.get(option.replace("-", "")):
  353. return_list.append(option.replace(" ", "=", 1))
  354. action._formatted_action_invocation = ", ".join(return_list)
  355. return action._formatted_action_invocation