parser.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529
  1. """
  2. This module started out as largely a copy paste from the stdlib's
  3. optparse module with the features removed that we do not need from
  4. optparse because we implement them in Click on a higher level (for
  5. instance type handling, help formatting and a lot more).
  6. The plan is to remove more and more from here over time.
  7. The reason this is a different module and not optparse from the stdlib
  8. is that there are differences in 2.x and 3.x about the error messages
  9. generated and optparse in the stdlib uses gettext for no good reason
  10. and might cause us issues.
  11. Click uses parts of optparse written by Gregory P. Ward and maintained
  12. by the Python Software Foundation. This is limited to code in parser.py.
  13. Copyright 2001-2006 Gregory P. Ward. All rights reserved.
  14. Copyright 2002-2006 Python Software Foundation. All rights reserved.
  15. """
  16. # This code uses parts of optparse written by Gregory P. Ward and
  17. # maintained by the Python Software Foundation.
  18. # Copyright 2001-2006 Gregory P. Ward
  19. # Copyright 2002-2006 Python Software Foundation
  20. import typing as t
  21. from collections import deque
  22. from gettext import gettext as _
  23. from gettext import ngettext
  24. from .exceptions import BadArgumentUsage
  25. from .exceptions import BadOptionUsage
  26. from .exceptions import NoSuchOption
  27. from .exceptions import UsageError
  28. if t.TYPE_CHECKING:
  29. import typing_extensions as te
  30. from .core import Argument as CoreArgument
  31. from .core import Context
  32. from .core import Option as CoreOption
  33. from .core import Parameter as CoreParameter
  34. V = t.TypeVar("V")
  35. # Sentinel value that indicates an option was passed as a flag without a
  36. # value but is not a flag option. Option.consume_value uses this to
  37. # prompt or use the flag_value.
  38. _flag_needs_value = object()
  39. def _unpack_args(
  40. args: t.Sequence[str], nargs_spec: t.Sequence[int]
  41. ) -> t.Tuple[t.Sequence[t.Union[str, t.Sequence[t.Optional[str]], None]], t.List[str]]:
  42. """Given an iterable of arguments and an iterable of nargs specifications,
  43. it returns a tuple with all the unpacked arguments at the first index
  44. and all remaining arguments as the second.
  45. The nargs specification is the number of arguments that should be consumed
  46. or `-1` to indicate that this position should eat up all the remainders.
  47. Missing items are filled with `None`.
  48. """
  49. args = deque(args)
  50. nargs_spec = deque(nargs_spec)
  51. rv: t.List[t.Union[str, t.Tuple[t.Optional[str], ...], None]] = []
  52. spos: t.Optional[int] = None
  53. def _fetch(c: "te.Deque[V]") -> t.Optional[V]:
  54. try:
  55. if spos is None:
  56. return c.popleft()
  57. else:
  58. return c.pop()
  59. except IndexError:
  60. return None
  61. while nargs_spec:
  62. nargs = _fetch(nargs_spec)
  63. if nargs is None:
  64. continue
  65. if nargs == 1:
  66. rv.append(_fetch(args))
  67. elif nargs > 1:
  68. x = [_fetch(args) for _ in range(nargs)]
  69. # If we're reversed, we're pulling in the arguments in reverse,
  70. # so we need to turn them around.
  71. if spos is not None:
  72. x.reverse()
  73. rv.append(tuple(x))
  74. elif nargs < 0:
  75. if spos is not None:
  76. raise TypeError("Cannot have two nargs < 0")
  77. spos = len(rv)
  78. rv.append(None)
  79. # spos is the position of the wildcard (star). If it's not `None`,
  80. # we fill it with the remainder.
  81. if spos is not None:
  82. rv[spos] = tuple(args)
  83. args = []
  84. rv[spos + 1 :] = reversed(rv[spos + 1 :])
  85. return tuple(rv), list(args)
  86. def split_opt(opt: str) -> t.Tuple[str, str]:
  87. first = opt[:1]
  88. if first.isalnum():
  89. return "", opt
  90. if opt[1:2] == first:
  91. return opt[:2], opt[2:]
  92. return first, opt[1:]
  93. def normalize_opt(opt: str, ctx: t.Optional["Context"]) -> str:
  94. if ctx is None or ctx.token_normalize_func is None:
  95. return opt
  96. prefix, opt = split_opt(opt)
  97. return f"{prefix}{ctx.token_normalize_func(opt)}"
  98. def split_arg_string(string: str) -> t.List[str]:
  99. """Split an argument string as with :func:`shlex.split`, but don't
  100. fail if the string is incomplete. Ignores a missing closing quote or
  101. incomplete escape sequence and uses the partial token as-is.
  102. .. code-block:: python
  103. split_arg_string("example 'my file")
  104. ["example", "my file"]
  105. split_arg_string("example my\\")
  106. ["example", "my"]
  107. :param string: String to split.
  108. """
  109. import shlex
  110. lex = shlex.shlex(string, posix=True)
  111. lex.whitespace_split = True
  112. lex.commenters = ""
  113. out = []
  114. try:
  115. for token in lex:
  116. out.append(token)
  117. except ValueError:
  118. # Raised when end-of-string is reached in an invalid state. Use
  119. # the partial token as-is. The quote or escape character is in
  120. # lex.state, not lex.token.
  121. out.append(lex.token)
  122. return out
  123. class Option:
  124. def __init__(
  125. self,
  126. obj: "CoreOption",
  127. opts: t.Sequence[str],
  128. dest: t.Optional[str],
  129. action: t.Optional[str] = None,
  130. nargs: int = 1,
  131. const: t.Optional[t.Any] = None,
  132. ):
  133. self._short_opts = []
  134. self._long_opts = []
  135. self.prefixes = set()
  136. for opt in opts:
  137. prefix, value = split_opt(opt)
  138. if not prefix:
  139. raise ValueError(f"Invalid start character for option ({opt})")
  140. self.prefixes.add(prefix[0])
  141. if len(prefix) == 1 and len(value) == 1:
  142. self._short_opts.append(opt)
  143. else:
  144. self._long_opts.append(opt)
  145. self.prefixes.add(prefix)
  146. if action is None:
  147. action = "store"
  148. self.dest = dest
  149. self.action = action
  150. self.nargs = nargs
  151. self.const = const
  152. self.obj = obj
  153. @property
  154. def takes_value(self) -> bool:
  155. return self.action in ("store", "append")
  156. def process(self, value: str, state: "ParsingState") -> None:
  157. if self.action == "store":
  158. state.opts[self.dest] = value # type: ignore
  159. elif self.action == "store_const":
  160. state.opts[self.dest] = self.const # type: ignore
  161. elif self.action == "append":
  162. state.opts.setdefault(self.dest, []).append(value) # type: ignore
  163. elif self.action == "append_const":
  164. state.opts.setdefault(self.dest, []).append(self.const) # type: ignore
  165. elif self.action == "count":
  166. state.opts[self.dest] = state.opts.get(self.dest, 0) + 1 # type: ignore
  167. else:
  168. raise ValueError(f"unknown action '{self.action}'")
  169. state.order.append(self.obj)
  170. class Argument:
  171. def __init__(self, obj: "CoreArgument", dest: t.Optional[str], nargs: int = 1):
  172. self.dest = dest
  173. self.nargs = nargs
  174. self.obj = obj
  175. def process(
  176. self,
  177. value: t.Union[t.Optional[str], t.Sequence[t.Optional[str]]],
  178. state: "ParsingState",
  179. ) -> None:
  180. if self.nargs > 1:
  181. assert value is not None
  182. holes = sum(1 for x in value if x is None)
  183. if holes == len(value):
  184. value = None
  185. elif holes != 0:
  186. raise BadArgumentUsage(
  187. _("Argument {name!r} takes {nargs} values.").format(
  188. name=self.dest, nargs=self.nargs
  189. )
  190. )
  191. if self.nargs == -1 and self.obj.envvar is not None and value == ():
  192. # Replace empty tuple with None so that a value from the
  193. # environment may be tried.
  194. value = None
  195. state.opts[self.dest] = value # type: ignore
  196. state.order.append(self.obj)
  197. class ParsingState:
  198. def __init__(self, rargs: t.List[str]) -> None:
  199. self.opts: t.Dict[str, t.Any] = {}
  200. self.largs: t.List[str] = []
  201. self.rargs = rargs
  202. self.order: t.List["CoreParameter"] = []
  203. class OptionParser:
  204. """The option parser is an internal class that is ultimately used to
  205. parse options and arguments. It's modelled after optparse and brings
  206. a similar but vastly simplified API. It should generally not be used
  207. directly as the high level Click classes wrap it for you.
  208. It's not nearly as extensible as optparse or argparse as it does not
  209. implement features that are implemented on a higher level (such as
  210. types or defaults).
  211. :param ctx: optionally the :class:`~click.Context` where this parser
  212. should go with.
  213. """
  214. def __init__(self, ctx: t.Optional["Context"] = None) -> None:
  215. #: The :class:`~click.Context` for this parser. This might be
  216. #: `None` for some advanced use cases.
  217. self.ctx = ctx
  218. #: This controls how the parser deals with interspersed arguments.
  219. #: If this is set to `False`, the parser will stop on the first
  220. #: non-option. Click uses this to implement nested subcommands
  221. #: safely.
  222. self.allow_interspersed_args = True
  223. #: This tells the parser how to deal with unknown options. By
  224. #: default it will error out (which is sensible), but there is a
  225. #: second mode where it will ignore it and continue processing
  226. #: after shifting all the unknown options into the resulting args.
  227. self.ignore_unknown_options = False
  228. if ctx is not None:
  229. self.allow_interspersed_args = ctx.allow_interspersed_args
  230. self.ignore_unknown_options = ctx.ignore_unknown_options
  231. self._short_opt: t.Dict[str, Option] = {}
  232. self._long_opt: t.Dict[str, Option] = {}
  233. self._opt_prefixes = {"-", "--"}
  234. self._args: t.List[Argument] = []
  235. def add_option(
  236. self,
  237. obj: "CoreOption",
  238. opts: t.Sequence[str],
  239. dest: t.Optional[str],
  240. action: t.Optional[str] = None,
  241. nargs: int = 1,
  242. const: t.Optional[t.Any] = None,
  243. ) -> None:
  244. """Adds a new option named `dest` to the parser. The destination
  245. is not inferred (unlike with optparse) and needs to be explicitly
  246. provided. Action can be any of ``store``, ``store_const``,
  247. ``append``, ``append_const`` or ``count``.
  248. The `obj` can be used to identify the option in the order list
  249. that is returned from the parser.
  250. """
  251. opts = [normalize_opt(opt, self.ctx) for opt in opts]
  252. option = Option(obj, opts, dest, action=action, nargs=nargs, const=const)
  253. self._opt_prefixes.update(option.prefixes)
  254. for opt in option._short_opts:
  255. self._short_opt[opt] = option
  256. for opt in option._long_opts:
  257. self._long_opt[opt] = option
  258. def add_argument(
  259. self, obj: "CoreArgument", dest: t.Optional[str], nargs: int = 1
  260. ) -> None:
  261. """Adds a positional argument named `dest` to the parser.
  262. The `obj` can be used to identify the option in the order list
  263. that is returned from the parser.
  264. """
  265. self._args.append(Argument(obj, dest=dest, nargs=nargs))
  266. def parse_args(
  267. self, args: t.List[str]
  268. ) -> t.Tuple[t.Dict[str, t.Any], t.List[str], t.List["CoreParameter"]]:
  269. """Parses positional arguments and returns ``(values, args, order)``
  270. for the parsed options and arguments as well as the leftover
  271. arguments if there are any. The order is a list of objects as they
  272. appear on the command line. If arguments appear multiple times they
  273. will be memorized multiple times as well.
  274. """
  275. state = ParsingState(args)
  276. try:
  277. self._process_args_for_options(state)
  278. self._process_args_for_args(state)
  279. except UsageError:
  280. if self.ctx is None or not self.ctx.resilient_parsing:
  281. raise
  282. return state.opts, state.largs, state.order
  283. def _process_args_for_args(self, state: ParsingState) -> None:
  284. pargs, args = _unpack_args(
  285. state.largs + state.rargs, [x.nargs for x in self._args]
  286. )
  287. for idx, arg in enumerate(self._args):
  288. arg.process(pargs[idx], state)
  289. state.largs = args
  290. state.rargs = []
  291. def _process_args_for_options(self, state: ParsingState) -> None:
  292. while state.rargs:
  293. arg = state.rargs.pop(0)
  294. arglen = len(arg)
  295. # Double dashes always handled explicitly regardless of what
  296. # prefixes are valid.
  297. if arg == "--":
  298. return
  299. elif arg[:1] in self._opt_prefixes and arglen > 1:
  300. self._process_opts(arg, state)
  301. elif self.allow_interspersed_args:
  302. state.largs.append(arg)
  303. else:
  304. state.rargs.insert(0, arg)
  305. return
  306. # Say this is the original argument list:
  307. # [arg0, arg1, ..., arg(i-1), arg(i), arg(i+1), ..., arg(N-1)]
  308. # ^
  309. # (we are about to process arg(i)).
  310. #
  311. # Then rargs is [arg(i), ..., arg(N-1)] and largs is a *subset* of
  312. # [arg0, ..., arg(i-1)] (any options and their arguments will have
  313. # been removed from largs).
  314. #
  315. # The while loop will usually consume 1 or more arguments per pass.
  316. # If it consumes 1 (eg. arg is an option that takes no arguments),
  317. # then after _process_arg() is done the situation is:
  318. #
  319. # largs = subset of [arg0, ..., arg(i)]
  320. # rargs = [arg(i+1), ..., arg(N-1)]
  321. #
  322. # If allow_interspersed_args is false, largs will always be
  323. # *empty* -- still a subset of [arg0, ..., arg(i-1)], but
  324. # not a very interesting subset!
  325. def _match_long_opt(
  326. self, opt: str, explicit_value: t.Optional[str], state: ParsingState
  327. ) -> None:
  328. if opt not in self._long_opt:
  329. from difflib import get_close_matches
  330. possibilities = get_close_matches(opt, self._long_opt)
  331. raise NoSuchOption(opt, possibilities=possibilities, ctx=self.ctx)
  332. option = self._long_opt[opt]
  333. if option.takes_value:
  334. # At this point it's safe to modify rargs by injecting the
  335. # explicit value, because no exception is raised in this
  336. # branch. This means that the inserted value will be fully
  337. # consumed.
  338. if explicit_value is not None:
  339. state.rargs.insert(0, explicit_value)
  340. value = self._get_value_from_state(opt, option, state)
  341. elif explicit_value is not None:
  342. raise BadOptionUsage(
  343. opt, _("Option {name!r} does not take a value.").format(name=opt)
  344. )
  345. else:
  346. value = None
  347. option.process(value, state)
  348. def _match_short_opt(self, arg: str, state: ParsingState) -> None:
  349. stop = False
  350. i = 1
  351. prefix = arg[0]
  352. unknown_options = []
  353. for ch in arg[1:]:
  354. opt = normalize_opt(f"{prefix}{ch}", self.ctx)
  355. option = self._short_opt.get(opt)
  356. i += 1
  357. if not option:
  358. if self.ignore_unknown_options:
  359. unknown_options.append(ch)
  360. continue
  361. raise NoSuchOption(opt, ctx=self.ctx)
  362. if option.takes_value:
  363. # Any characters left in arg? Pretend they're the
  364. # next arg, and stop consuming characters of arg.
  365. if i < len(arg):
  366. state.rargs.insert(0, arg[i:])
  367. stop = True
  368. value = self._get_value_from_state(opt, option, state)
  369. else:
  370. value = None
  371. option.process(value, state)
  372. if stop:
  373. break
  374. # If we got any unknown options we re-combinate the string of the
  375. # remaining options and re-attach the prefix, then report that
  376. # to the state as new larg. This way there is basic combinatorics
  377. # that can be achieved while still ignoring unknown arguments.
  378. if self.ignore_unknown_options and unknown_options:
  379. state.largs.append(f"{prefix}{''.join(unknown_options)}")
  380. def _get_value_from_state(
  381. self, option_name: str, option: Option, state: ParsingState
  382. ) -> t.Any:
  383. nargs = option.nargs
  384. if len(state.rargs) < nargs:
  385. if option.obj._flag_needs_value:
  386. # Option allows omitting the value.
  387. value = _flag_needs_value
  388. else:
  389. raise BadOptionUsage(
  390. option_name,
  391. ngettext(
  392. "Option {name!r} requires an argument.",
  393. "Option {name!r} requires {nargs} arguments.",
  394. nargs,
  395. ).format(name=option_name, nargs=nargs),
  396. )
  397. elif nargs == 1:
  398. next_rarg = state.rargs[0]
  399. if (
  400. option.obj._flag_needs_value
  401. and isinstance(next_rarg, str)
  402. and next_rarg[:1] in self._opt_prefixes
  403. and len(next_rarg) > 1
  404. ):
  405. # The next arg looks like the start of an option, don't
  406. # use it as the value if omitting the value is allowed.
  407. value = _flag_needs_value
  408. else:
  409. value = state.rargs.pop(0)
  410. else:
  411. value = tuple(state.rargs[:nargs])
  412. del state.rargs[:nargs]
  413. return value
  414. def _process_opts(self, arg: str, state: ParsingState) -> None:
  415. explicit_value = None
  416. # Long option handling happens in two parts. The first part is
  417. # supporting explicitly attached values. In any case, we will try
  418. # to long match the option first.
  419. if "=" in arg:
  420. long_opt, explicit_value = arg.split("=", 1)
  421. else:
  422. long_opt = arg
  423. norm_long_opt = normalize_opt(long_opt, self.ctx)
  424. # At this point we will match the (assumed) long option through
  425. # the long option matching code. Note that this allows options
  426. # like "-foo" to be matched as long options.
  427. try:
  428. self._match_long_opt(norm_long_opt, explicit_value, state)
  429. except NoSuchOption:
  430. # At this point the long option matching failed, and we need
  431. # to try with short options. However there is a special rule
  432. # which says, that if we have a two character options prefix
  433. # (applies to "--foo" for instance), we do not dispatch to the
  434. # short option code and will instead raise the no option
  435. # error.
  436. if arg[:2] not in self._opt_prefixes:
  437. self._match_short_opt(arg, state)
  438. return
  439. if not self.ignore_unknown_options:
  440. raise
  441. state.largs.append(arg)