You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

427 lines
15 KiB

4 years ago
  1. # -*- coding: utf-8 -*-
  2. """
  3. click.parser
  4. ~~~~~~~~~~~~
  5. This module started out as largely a copy paste from the stdlib's
  6. optparse module with the features removed that we do not need from
  7. optparse because we implement them in Click on a higher level (for
  8. instance type handling, help formatting and a lot more).
  9. The plan is to remove more and more from here over time.
  10. The reason this is a different module and not optparse from the stdlib
  11. is that there are differences in 2.x and 3.x about the error messages
  12. generated and optparse in the stdlib uses gettext for no good reason
  13. and might cause us issues.
  14. """
  15. import re
  16. from collections import deque
  17. from .exceptions import UsageError, NoSuchOption, BadOptionUsage, \
  18. BadArgumentUsage
  19. def _unpack_args(args, nargs_spec):
  20. """Given an iterable of arguments and an iterable of nargs specifications,
  21. it returns a tuple with all the unpacked arguments at the first index
  22. and all remaining arguments as the second.
  23. The nargs specification is the number of arguments that should be consumed
  24. or `-1` to indicate that this position should eat up all the remainders.
  25. Missing items are filled with `None`.
  26. """
  27. args = deque(args)
  28. nargs_spec = deque(nargs_spec)
  29. rv = []
  30. spos = None
  31. def _fetch(c):
  32. try:
  33. if spos is None:
  34. return c.popleft()
  35. else:
  36. return c.pop()
  37. except IndexError:
  38. return None
  39. while nargs_spec:
  40. nargs = _fetch(nargs_spec)
  41. if nargs == 1:
  42. rv.append(_fetch(args))
  43. elif nargs > 1:
  44. x = [_fetch(args) for _ in range(nargs)]
  45. # If we're reversed, we're pulling in the arguments in reverse,
  46. # so we need to turn them around.
  47. if spos is not None:
  48. x.reverse()
  49. rv.append(tuple(x))
  50. elif nargs < 0:
  51. if spos is not None:
  52. raise TypeError('Cannot have two nargs < 0')
  53. spos = len(rv)
  54. rv.append(None)
  55. # spos is the position of the wildcard (star). If it's not `None`,
  56. # we fill it with the remainder.
  57. if spos is not None:
  58. rv[spos] = tuple(args)
  59. args = []
  60. rv[spos + 1:] = reversed(rv[spos + 1:])
  61. return tuple(rv), list(args)
  62. def _error_opt_args(nargs, opt):
  63. if nargs == 1:
  64. raise BadOptionUsage(opt, '%s option requires an argument' % opt)
  65. raise BadOptionUsage(opt, '%s option requires %d arguments' % (opt, nargs))
  66. def split_opt(opt):
  67. first = opt[:1]
  68. if first.isalnum():
  69. return '', opt
  70. if opt[1:2] == first:
  71. return opt[:2], opt[2:]
  72. return first, opt[1:]
  73. def normalize_opt(opt, ctx):
  74. if ctx is None or ctx.token_normalize_func is None:
  75. return opt
  76. prefix, opt = split_opt(opt)
  77. return prefix + ctx.token_normalize_func(opt)
  78. def split_arg_string(string):
  79. """Given an argument string this attempts to split it into small parts."""
  80. rv = []
  81. for match in re.finditer(r"('([^'\\]*(?:\\.[^'\\]*)*)'"
  82. r'|"([^"\\]*(?:\\.[^"\\]*)*)"'
  83. r'|\S+)\s*', string, re.S):
  84. arg = match.group().strip()
  85. if arg[:1] == arg[-1:] and arg[:1] in '"\'':
  86. arg = arg[1:-1].encode('ascii', 'backslashreplace') \
  87. .decode('unicode-escape')
  88. try:
  89. arg = type(string)(arg)
  90. except UnicodeError:
  91. pass
  92. rv.append(arg)
  93. return rv
  94. class Option(object):
  95. def __init__(self, opts, dest, action=None, nargs=1, const=None, obj=None):
  96. self._short_opts = []
  97. self._long_opts = []
  98. self.prefixes = set()
  99. for opt in opts:
  100. prefix, value = split_opt(opt)
  101. if not prefix:
  102. raise ValueError('Invalid start character for option (%s)'
  103. % opt)
  104. self.prefixes.add(prefix[0])
  105. if len(prefix) == 1 and len(value) == 1:
  106. self._short_opts.append(opt)
  107. else:
  108. self._long_opts.append(opt)
  109. self.prefixes.add(prefix)
  110. if action is None:
  111. action = 'store'
  112. self.dest = dest
  113. self.action = action
  114. self.nargs = nargs
  115. self.const = const
  116. self.obj = obj
  117. @property
  118. def takes_value(self):
  119. return self.action in ('store', 'append')
  120. def process(self, value, state):
  121. if self.action == 'store':
  122. state.opts[self.dest] = value
  123. elif self.action == 'store_const':
  124. state.opts[self.dest] = self.const
  125. elif self.action == 'append':
  126. state.opts.setdefault(self.dest, []).append(value)
  127. elif self.action == 'append_const':
  128. state.opts.setdefault(self.dest, []).append(self.const)
  129. elif self.action == 'count':
  130. state.opts[self.dest] = state.opts.get(self.dest, 0) + 1
  131. else:
  132. raise ValueError('unknown action %r' % self.action)
  133. state.order.append(self.obj)
  134. class Argument(object):
  135. def __init__(self, dest, nargs=1, obj=None):
  136. self.dest = dest
  137. self.nargs = nargs
  138. self.obj = obj
  139. def process(self, value, state):
  140. if self.nargs > 1:
  141. holes = sum(1 for x in value if x is None)
  142. if holes == len(value):
  143. value = None
  144. elif holes != 0:
  145. raise BadArgumentUsage('argument %s takes %d values'
  146. % (self.dest, self.nargs))
  147. state.opts[self.dest] = value
  148. state.order.append(self.obj)
  149. class ParsingState(object):
  150. def __init__(self, rargs):
  151. self.opts = {}
  152. self.largs = []
  153. self.rargs = rargs
  154. self.order = []
  155. class OptionParser(object):
  156. """The option parser is an internal class that is ultimately used to
  157. parse options and arguments. It's modelled after optparse and brings
  158. a similar but vastly simplified API. It should generally not be used
  159. directly as the high level Click classes wrap it for you.
  160. It's not nearly as extensible as optparse or argparse as it does not
  161. implement features that are implemented on a higher level (such as
  162. types or defaults).
  163. :param ctx: optionally the :class:`~click.Context` where this parser
  164. should go with.
  165. """
  166. def __init__(self, ctx=None):
  167. #: The :class:`~click.Context` for this parser. This might be
  168. #: `None` for some advanced use cases.
  169. self.ctx = ctx
  170. #: This controls how the parser deals with interspersed arguments.
  171. #: If this is set to `False`, the parser will stop on the first
  172. #: non-option. Click uses this to implement nested subcommands
  173. #: safely.
  174. self.allow_interspersed_args = True
  175. #: This tells the parser how to deal with unknown options. By
  176. #: default it will error out (which is sensible), but there is a
  177. #: second mode where it will ignore it and continue processing
  178. #: after shifting all the unknown options into the resulting args.
  179. self.ignore_unknown_options = False
  180. if ctx is not None:
  181. self.allow_interspersed_args = ctx.allow_interspersed_args
  182. self.ignore_unknown_options = ctx.ignore_unknown_options
  183. self._short_opt = {}
  184. self._long_opt = {}
  185. self._opt_prefixes = set(['-', '--'])
  186. self._args = []
  187. def add_option(self, opts, dest, action=None, nargs=1, const=None,
  188. obj=None):
  189. """Adds a new option named `dest` to the parser. The destination
  190. is not inferred (unlike with optparse) and needs to be explicitly
  191. provided. Action can be any of ``store``, ``store_const``,
  192. ``append``, ``appnd_const`` or ``count``.
  193. The `obj` can be used to identify the option in the order list
  194. that is returned from the parser.
  195. """
  196. if obj is None:
  197. obj = dest
  198. opts = [normalize_opt(opt, self.ctx) for opt in opts]
  199. option = Option(opts, dest, action=action, nargs=nargs,
  200. const=const, obj=obj)
  201. self._opt_prefixes.update(option.prefixes)
  202. for opt in option._short_opts:
  203. self._short_opt[opt] = option
  204. for opt in option._long_opts:
  205. self._long_opt[opt] = option
  206. def add_argument(self, dest, nargs=1, obj=None):
  207. """Adds a positional argument named `dest` to the parser.
  208. The `obj` can be used to identify the option in the order list
  209. that is returned from the parser.
  210. """
  211. if obj is None:
  212. obj = dest
  213. self._args.append(Argument(dest=dest, nargs=nargs, obj=obj))
  214. def parse_args(self, args):
  215. """Parses positional arguments and returns ``(values, args, order)``
  216. for the parsed options and arguments as well as the leftover
  217. arguments if there are any. The order is a list of objects as they
  218. appear on the command line. If arguments appear multiple times they
  219. will be memorized multiple times as well.
  220. """
  221. state = ParsingState(args)
  222. try:
  223. self._process_args_for_options(state)
  224. self._process_args_for_args(state)
  225. except UsageError:
  226. if self.ctx is None or not self.ctx.resilient_parsing:
  227. raise
  228. return state.opts, state.largs, state.order
  229. def _process_args_for_args(self, state):
  230. pargs, args = _unpack_args(state.largs + state.rargs,
  231. [x.nargs for x in self._args])
  232. for idx, arg in enumerate(self._args):
  233. arg.process(pargs[idx], state)
  234. state.largs = args
  235. state.rargs = []
  236. def _process_args_for_options(self, state):
  237. while state.rargs:
  238. arg = state.rargs.pop(0)
  239. arglen = len(arg)
  240. # Double dashes always handled explicitly regardless of what
  241. # prefixes are valid.
  242. if arg == '--':
  243. return
  244. elif arg[:1] in self._opt_prefixes and arglen > 1:
  245. self._process_opts(arg, state)
  246. elif self.allow_interspersed_args:
  247. state.largs.append(arg)
  248. else:
  249. state.rargs.insert(0, arg)
  250. return
  251. # Say this is the original argument list:
  252. # [arg0, arg1, ..., arg(i-1), arg(i), arg(i+1), ..., arg(N-1)]
  253. # ^
  254. # (we are about to process arg(i)).
  255. #
  256. # Then rargs is [arg(i), ..., arg(N-1)] and largs is a *subset* of
  257. # [arg0, ..., arg(i-1)] (any options and their arguments will have
  258. # been removed from largs).
  259. #
  260. # The while loop will usually consume 1 or more arguments per pass.
  261. # If it consumes 1 (eg. arg is an option that takes no arguments),
  262. # then after _process_arg() is done the situation is:
  263. #
  264. # largs = subset of [arg0, ..., arg(i)]
  265. # rargs = [arg(i+1), ..., arg(N-1)]
  266. #
  267. # If allow_interspersed_args is false, largs will always be
  268. # *empty* -- still a subset of [arg0, ..., arg(i-1)], but
  269. # not a very interesting subset!
  270. def _match_long_opt(self, opt, explicit_value, state):
  271. if opt not in self._long_opt:
  272. possibilities = [word for word in self._long_opt
  273. if word.startswith(opt)]
  274. raise NoSuchOption(opt, possibilities=possibilities, ctx=self.ctx)
  275. option = self._long_opt[opt]
  276. if option.takes_value:
  277. # At this point it's safe to modify rargs by injecting the
  278. # explicit value, because no exception is raised in this
  279. # branch. This means that the inserted value will be fully
  280. # consumed.
  281. if explicit_value is not None:
  282. state.rargs.insert(0, explicit_value)
  283. nargs = option.nargs
  284. if len(state.rargs) < nargs:
  285. _error_opt_args(nargs, opt)
  286. elif nargs == 1:
  287. value = state.rargs.pop(0)
  288. else:
  289. value = tuple(state.rargs[:nargs])
  290. del state.rargs[:nargs]
  291. elif explicit_value is not None:
  292. raise BadOptionUsage(opt, '%s option does not take a value' % opt)
  293. else:
  294. value = None
  295. option.process(value, state)
  296. def _match_short_opt(self, arg, state):
  297. stop = False
  298. i = 1
  299. prefix = arg[0]
  300. unknown_options = []
  301. for ch in arg[1:]:
  302. opt = normalize_opt(prefix + ch, self.ctx)
  303. option = self._short_opt.get(opt)
  304. i += 1
  305. if not option:
  306. if self.ignore_unknown_options:
  307. unknown_options.append(ch)
  308. continue
  309. raise NoSuchOption(opt, ctx=self.ctx)
  310. if option.takes_value:
  311. # Any characters left in arg? Pretend they're the
  312. # next arg, and stop consuming characters of arg.
  313. if i < len(arg):
  314. state.rargs.insert(0, arg[i:])
  315. stop = True
  316. nargs = option.nargs
  317. if len(state.rargs) < nargs:
  318. _error_opt_args(nargs, opt)
  319. elif nargs == 1:
  320. value = state.rargs.pop(0)
  321. else:
  322. value = tuple(state.rargs[:nargs])
  323. del state.rargs[:nargs]
  324. else:
  325. value = None
  326. option.process(value, state)
  327. if stop:
  328. break
  329. # If we got any unknown options we re-combinate the string of the
  330. # remaining options and re-attach the prefix, then report that
  331. # to the state as new larg. This way there is basic combinatorics
  332. # that can be achieved while still ignoring unknown arguments.
  333. if self.ignore_unknown_options and unknown_options:
  334. state.largs.append(prefix + ''.join(unknown_options))
  335. def _process_opts(self, arg, state):
  336. explicit_value = None
  337. # Long option handling happens in two parts. The first part is
  338. # supporting explicitly attached values. In any case, we will try
  339. # to long match the option first.
  340. if '=' in arg:
  341. long_opt, explicit_value = arg.split('=', 1)
  342. else:
  343. long_opt = arg
  344. norm_long_opt = normalize_opt(long_opt, self.ctx)
  345. # At this point we will match the (assumed) long option through
  346. # the long option matching code. Note that this allows options
  347. # like "-foo" to be matched as long options.
  348. try:
  349. self._match_long_opt(norm_long_opt, explicit_value, state)
  350. except NoSuchOption:
  351. # At this point the long option matching failed, and we need
  352. # to try with short options. However there is a special rule
  353. # which says, that if we have a two character options prefix
  354. # (applies to "--foo" for instance), we do not dispatch to the
  355. # short option code and will instead raise the no option
  356. # error.
  357. if arg[:2] not in self._opt_prefixes:
  358. return self._match_short_opt(arg, state)
  359. if not self.ignore_unknown_options:
  360. raise
  361. state.largs.append(arg)