argparsing.py 15 KB

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