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.

2958 lines
109KB

  1. import enum
  2. import errno
  3. import os
  4. import sys
  5. import typing
  6. import typing as t
  7. from collections import abc
  8. from contextlib import contextmanager
  9. from contextlib import ExitStack
  10. from functools import partial
  11. from functools import update_wrapper
  12. from gettext import gettext as _
  13. from gettext import ngettext
  14. from itertools import repeat
  15. from . import types
  16. from ._unicodefun import _verify_python_env
  17. from .exceptions import Abort
  18. from .exceptions import BadParameter
  19. from .exceptions import ClickException
  20. from .exceptions import Exit
  21. from .exceptions import MissingParameter
  22. from .exceptions import UsageError
  23. from .formatting import HelpFormatter
  24. from .formatting import join_options
  25. from .globals import pop_context
  26. from .globals import push_context
  27. from .parser import _flag_needs_value
  28. from .parser import OptionParser
  29. from .parser import split_opt
  30. from .termui import confirm
  31. from .termui import prompt
  32. from .termui import style
  33. from .utils import _detect_program_name
  34. from .utils import _expand_args
  35. from .utils import echo
  36. from .utils import make_default_short_help
  37. from .utils import make_str
  38. from .utils import PacifyFlushWrapper
  39. if t.TYPE_CHECKING:
  40. import typing_extensions as te
  41. from .shell_completion import CompletionItem
  42. F = t.TypeVar("F", bound=t.Callable[..., t.Any])
  43. V = t.TypeVar("V")
  44. def _fast_exit(code: int) -> "te.NoReturn":
  45. """Low-level exit that skips Python's cleanup but speeds up exit by
  46. about 10ms for things like shell completion.
  47. :param code: Exit code.
  48. """
  49. sys.stdout.flush()
  50. sys.stderr.flush()
  51. os._exit(code)
  52. def _complete_visible_commands(
  53. ctx: "Context", incomplete: str
  54. ) -> t.Iterator[t.Tuple[str, "Command"]]:
  55. """List all the subcommands of a group that start with the
  56. incomplete value and aren't hidden.
  57. :param ctx: Invocation context for the group.
  58. :param incomplete: Value being completed. May be empty.
  59. """
  60. multi = t.cast(MultiCommand, ctx.command)
  61. for name in multi.list_commands(ctx):
  62. if name.startswith(incomplete):
  63. command = multi.get_command(ctx, name)
  64. if command is not None and not command.hidden:
  65. yield name, command
  66. def _check_multicommand(
  67. base_command: "MultiCommand", cmd_name: str, cmd: "Command", register: bool = False
  68. ) -> None:
  69. if not base_command.chain or not isinstance(cmd, MultiCommand):
  70. return
  71. if register:
  72. hint = (
  73. "It is not possible to add multi commands as children to"
  74. " another multi command that is in chain mode."
  75. )
  76. else:
  77. hint = (
  78. "Found a multi command as subcommand to a multi command"
  79. " that is in chain mode. This is not supported."
  80. )
  81. raise RuntimeError(
  82. f"{hint}. Command {base_command.name!r} is set to chain and"
  83. f" {cmd_name!r} was added as a subcommand but it in itself is a"
  84. f" multi command. ({cmd_name!r} is a {type(cmd).__name__}"
  85. f" within a chained {type(base_command).__name__} named"
  86. f" {base_command.name!r})."
  87. )
  88. def batch(iterable: t.Iterable[V], batch_size: int) -> t.List[t.Tuple[V, ...]]:
  89. return list(zip(*repeat(iter(iterable), batch_size)))
  90. @contextmanager
  91. def augment_usage_errors(
  92. ctx: "Context", param: t.Optional["Parameter"] = None
  93. ) -> t.Iterator[None]:
  94. """Context manager that attaches extra information to exceptions."""
  95. try:
  96. yield
  97. except BadParameter as e:
  98. if e.ctx is None:
  99. e.ctx = ctx
  100. if param is not None and e.param is None:
  101. e.param = param
  102. raise
  103. except UsageError as e:
  104. if e.ctx is None:
  105. e.ctx = ctx
  106. raise
  107. def iter_params_for_processing(
  108. invocation_order: t.Sequence["Parameter"],
  109. declaration_order: t.Sequence["Parameter"],
  110. ) -> t.List["Parameter"]:
  111. """Given a sequence of parameters in the order as should be considered
  112. for processing and an iterable of parameters that exist, this returns
  113. a list in the correct order as they should be processed.
  114. """
  115. def sort_key(item: "Parameter") -> t.Tuple[bool, float]:
  116. try:
  117. idx: float = invocation_order.index(item)
  118. except ValueError:
  119. idx = float("inf")
  120. return not item.is_eager, idx
  121. return sorted(declaration_order, key=sort_key)
  122. class ParameterSource(enum.Enum):
  123. """This is an :class:`~enum.Enum` that indicates the source of a
  124. parameter's value.
  125. Use :meth:`click.Context.get_parameter_source` to get the
  126. source for a parameter by name.
  127. .. versionchanged:: 8.0
  128. Use :class:`~enum.Enum` and drop the ``validate`` method.
  129. .. versionchanged:: 8.0
  130. Added the ``PROMPT`` value.
  131. """
  132. COMMANDLINE = enum.auto()
  133. """The value was provided by the command line args."""
  134. ENVIRONMENT = enum.auto()
  135. """The value was provided with an environment variable."""
  136. DEFAULT = enum.auto()
  137. """Used the default specified by the parameter."""
  138. DEFAULT_MAP = enum.auto()
  139. """Used a default provided by :attr:`Context.default_map`."""
  140. PROMPT = enum.auto()
  141. """Used a prompt to confirm a default or provide a value."""
  142. class Context:
  143. """The context is a special internal object that holds state relevant
  144. for the script execution at every single level. It's normally invisible
  145. to commands unless they opt-in to getting access to it.
  146. The context is useful as it can pass internal objects around and can
  147. control special execution features such as reading data from
  148. environment variables.
  149. A context can be used as context manager in which case it will call
  150. :meth:`close` on teardown.
  151. :param command: the command class for this context.
  152. :param parent: the parent context.
  153. :param info_name: the info name for this invocation. Generally this
  154. is the most descriptive name for the script or
  155. command. For the toplevel script it is usually
  156. the name of the script, for commands below it it's
  157. the name of the script.
  158. :param obj: an arbitrary object of user data.
  159. :param auto_envvar_prefix: the prefix to use for automatic environment
  160. variables. If this is `None` then reading
  161. from environment variables is disabled. This
  162. does not affect manually set environment
  163. variables which are always read.
  164. :param default_map: a dictionary (like object) with default values
  165. for parameters.
  166. :param terminal_width: the width of the terminal. The default is
  167. inherit from parent context. If no context
  168. defines the terminal width then auto
  169. detection will be applied.
  170. :param max_content_width: the maximum width for content rendered by
  171. Click (this currently only affects help
  172. pages). This defaults to 80 characters if
  173. not overridden. In other words: even if the
  174. terminal is larger than that, Click will not
  175. format things wider than 80 characters by
  176. default. In addition to that, formatters might
  177. add some safety mapping on the right.
  178. :param resilient_parsing: if this flag is enabled then Click will
  179. parse without any interactivity or callback
  180. invocation. Default values will also be
  181. ignored. This is useful for implementing
  182. things such as completion support.
  183. :param allow_extra_args: if this is set to `True` then extra arguments
  184. at the end will not raise an error and will be
  185. kept on the context. The default is to inherit
  186. from the command.
  187. :param allow_interspersed_args: if this is set to `False` then options
  188. and arguments cannot be mixed. The
  189. default is to inherit from the command.
  190. :param ignore_unknown_options: instructs click to ignore options it does
  191. not know and keeps them for later
  192. processing.
  193. :param help_option_names: optionally a list of strings that define how
  194. the default help parameter is named. The
  195. default is ``['--help']``.
  196. :param token_normalize_func: an optional function that is used to
  197. normalize tokens (options, choices,
  198. etc.). This for instance can be used to
  199. implement case insensitive behavior.
  200. :param color: controls if the terminal supports ANSI colors or not. The
  201. default is autodetection. This is only needed if ANSI
  202. codes are used in texts that Click prints which is by
  203. default not the case. This for instance would affect
  204. help output.
  205. :param show_default: Show defaults for all options. If not set,
  206. defaults to the value from a parent context. Overrides an
  207. option's ``show_default`` argument.
  208. .. versionchanged:: 8.0
  209. The ``show_default`` parameter defaults to the value from the
  210. parent context.
  211. .. versionchanged:: 7.1
  212. Added the ``show_default`` parameter.
  213. .. versionchanged:: 4.0
  214. Added the ``color``, ``ignore_unknown_options``, and
  215. ``max_content_width`` parameters.
  216. .. versionchanged:: 3.0
  217. Added the ``allow_extra_args`` and ``allow_interspersed_args``
  218. parameters.
  219. .. versionchanged:: 2.0
  220. Added the ``resilient_parsing``, ``help_option_names``, and
  221. ``token_normalize_func`` parameters.
  222. """
  223. #: The formatter class to create with :meth:`make_formatter`.
  224. #:
  225. #: .. versionadded:: 8.0
  226. formatter_class: t.Type["HelpFormatter"] = HelpFormatter
  227. def __init__(
  228. self,
  229. command: "Command",
  230. parent: t.Optional["Context"] = None,
  231. info_name: t.Optional[str] = None,
  232. obj: t.Optional[t.Any] = None,
  233. auto_envvar_prefix: t.Optional[str] = None,
  234. default_map: t.Optional[t.Dict[str, t.Any]] = None,
  235. terminal_width: t.Optional[int] = None,
  236. max_content_width: t.Optional[int] = None,
  237. resilient_parsing: bool = False,
  238. allow_extra_args: t.Optional[bool] = None,
  239. allow_interspersed_args: t.Optional[bool] = None,
  240. ignore_unknown_options: t.Optional[bool] = None,
  241. help_option_names: t.Optional[t.List[str]] = None,
  242. token_normalize_func: t.Optional[t.Callable[[str], str]] = None,
  243. color: t.Optional[bool] = None,
  244. show_default: t.Optional[bool] = None,
  245. ) -> None:
  246. #: the parent context or `None` if none exists.
  247. self.parent = parent
  248. #: the :class:`Command` for this context.
  249. self.command = command
  250. #: the descriptive information name
  251. self.info_name = info_name
  252. #: Map of parameter names to their parsed values. Parameters
  253. #: with ``expose_value=False`` are not stored.
  254. self.params: t.Dict[str, t.Any] = {}
  255. #: the leftover arguments.
  256. self.args: t.List[str] = []
  257. #: protected arguments. These are arguments that are prepended
  258. #: to `args` when certain parsing scenarios are encountered but
  259. #: must be never propagated to another arguments. This is used
  260. #: to implement nested parsing.
  261. self.protected_args: t.List[str] = []
  262. if obj is None and parent is not None:
  263. obj = parent.obj
  264. #: the user object stored.
  265. self.obj: t.Any = obj
  266. self._meta: t.Dict[str, t.Any] = getattr(parent, "meta", {})
  267. #: A dictionary (-like object) with defaults for parameters.
  268. if (
  269. default_map is None
  270. and info_name is not None
  271. and parent is not None
  272. and parent.default_map is not None
  273. ):
  274. default_map = parent.default_map.get(info_name)
  275. self.default_map: t.Optional[t.Dict[str, t.Any]] = default_map
  276. #: This flag indicates if a subcommand is going to be executed. A
  277. #: group callback can use this information to figure out if it's
  278. #: being executed directly or because the execution flow passes
  279. #: onwards to a subcommand. By default it's None, but it can be
  280. #: the name of the subcommand to execute.
  281. #:
  282. #: If chaining is enabled this will be set to ``'*'`` in case
  283. #: any commands are executed. It is however not possible to
  284. #: figure out which ones. If you require this knowledge you
  285. #: should use a :func:`result_callback`.
  286. self.invoked_subcommand: t.Optional[str] = None
  287. if terminal_width is None and parent is not None:
  288. terminal_width = parent.terminal_width
  289. #: The width of the terminal (None is autodetection).
  290. self.terminal_width: t.Optional[int] = terminal_width
  291. if max_content_width is None and parent is not None:
  292. max_content_width = parent.max_content_width
  293. #: The maximum width of formatted content (None implies a sensible
  294. #: default which is 80 for most things).
  295. self.max_content_width: t.Optional[int] = max_content_width
  296. if allow_extra_args is None:
  297. allow_extra_args = command.allow_extra_args
  298. #: Indicates if the context allows extra args or if it should
  299. #: fail on parsing.
  300. #:
  301. #: .. versionadded:: 3.0
  302. self.allow_extra_args = allow_extra_args
  303. if allow_interspersed_args is None:
  304. allow_interspersed_args = command.allow_interspersed_args
  305. #: Indicates if the context allows mixing of arguments and
  306. #: options or not.
  307. #:
  308. #: .. versionadded:: 3.0
  309. self.allow_interspersed_args: bool = allow_interspersed_args
  310. if ignore_unknown_options is None:
  311. ignore_unknown_options = command.ignore_unknown_options
  312. #: Instructs click to ignore options that a command does not
  313. #: understand and will store it on the context for later
  314. #: processing. This is primarily useful for situations where you
  315. #: want to call into external programs. Generally this pattern is
  316. #: strongly discouraged because it's not possibly to losslessly
  317. #: forward all arguments.
  318. #:
  319. #: .. versionadded:: 4.0
  320. self.ignore_unknown_options: bool = ignore_unknown_options
  321. if help_option_names is None:
  322. if parent is not None:
  323. help_option_names = parent.help_option_names
  324. else:
  325. help_option_names = ["--help"]
  326. #: The names for the help options.
  327. self.help_option_names: t.List[str] = help_option_names
  328. if token_normalize_func is None and parent is not None:
  329. token_normalize_func = parent.token_normalize_func
  330. #: An optional normalization function for tokens. This is
  331. #: options, choices, commands etc.
  332. self.token_normalize_func: t.Optional[
  333. t.Callable[[str], str]
  334. ] = token_normalize_func
  335. #: Indicates if resilient parsing is enabled. In that case Click
  336. #: will do its best to not cause any failures and default values
  337. #: will be ignored. Useful for completion.
  338. self.resilient_parsing: bool = resilient_parsing
  339. # If there is no envvar prefix yet, but the parent has one and
  340. # the command on this level has a name, we can expand the envvar
  341. # prefix automatically.
  342. if auto_envvar_prefix is None:
  343. if (
  344. parent is not None
  345. and parent.auto_envvar_prefix is not None
  346. and self.info_name is not None
  347. ):
  348. auto_envvar_prefix = (
  349. f"{parent.auto_envvar_prefix}_{self.info_name.upper()}"
  350. )
  351. else:
  352. auto_envvar_prefix = auto_envvar_prefix.upper()
  353. if auto_envvar_prefix is not None:
  354. auto_envvar_prefix = auto_envvar_prefix.replace("-", "_")
  355. self.auto_envvar_prefix: t.Optional[str] = auto_envvar_prefix
  356. if color is None and parent is not None:
  357. color = parent.color
  358. #: Controls if styling output is wanted or not.
  359. self.color: t.Optional[bool] = color
  360. if show_default is None and parent is not None:
  361. show_default = parent.show_default
  362. #: Show option default values when formatting help text.
  363. self.show_default: t.Optional[bool] = show_default
  364. self._close_callbacks: t.List[t.Callable[[], t.Any]] = []
  365. self._depth = 0
  366. self._parameter_source: t.Dict[str, ParameterSource] = {}
  367. self._exit_stack = ExitStack()
  368. def to_info_dict(self) -> t.Dict[str, t.Any]:
  369. """Gather information that could be useful for a tool generating
  370. user-facing documentation. This traverses the entire CLI
  371. structure.
  372. .. code-block:: python
  373. with Context(cli) as ctx:
  374. info = ctx.to_info_dict()
  375. .. versionadded:: 8.0
  376. """
  377. return {
  378. "command": self.command.to_info_dict(self),
  379. "info_name": self.info_name,
  380. "allow_extra_args": self.allow_extra_args,
  381. "allow_interspersed_args": self.allow_interspersed_args,
  382. "ignore_unknown_options": self.ignore_unknown_options,
  383. "auto_envvar_prefix": self.auto_envvar_prefix,
  384. }
  385. def __enter__(self) -> "Context":
  386. self._depth += 1
  387. push_context(self)
  388. return self
  389. def __exit__(self, exc_type, exc_value, tb): # type: ignore
  390. self._depth -= 1
  391. if self._depth == 0:
  392. self.close()
  393. pop_context()
  394. @contextmanager
  395. def scope(self, cleanup: bool = True) -> t.Iterator["Context"]:
  396. """This helper method can be used with the context object to promote
  397. it to the current thread local (see :func:`get_current_context`).
  398. The default behavior of this is to invoke the cleanup functions which
  399. can be disabled by setting `cleanup` to `False`. The cleanup
  400. functions are typically used for things such as closing file handles.
  401. If the cleanup is intended the context object can also be directly
  402. used as a context manager.
  403. Example usage::
  404. with ctx.scope():
  405. assert get_current_context() is ctx
  406. This is equivalent::
  407. with ctx:
  408. assert get_current_context() is ctx
  409. .. versionadded:: 5.0
  410. :param cleanup: controls if the cleanup functions should be run or
  411. not. The default is to run these functions. In
  412. some situations the context only wants to be
  413. temporarily pushed in which case this can be disabled.
  414. Nested pushes automatically defer the cleanup.
  415. """
  416. if not cleanup:
  417. self._depth += 1
  418. try:
  419. with self as rv:
  420. yield rv
  421. finally:
  422. if not cleanup:
  423. self._depth -= 1
  424. @property
  425. def meta(self) -> t.Dict[str, t.Any]:
  426. """This is a dictionary which is shared with all the contexts
  427. that are nested. It exists so that click utilities can store some
  428. state here if they need to. It is however the responsibility of
  429. that code to manage this dictionary well.
  430. The keys are supposed to be unique dotted strings. For instance
  431. module paths are a good choice for it. What is stored in there is
  432. irrelevant for the operation of click. However what is important is
  433. that code that places data here adheres to the general semantics of
  434. the system.
  435. Example usage::
  436. LANG_KEY = f'{__name__}.lang'
  437. def set_language(value):
  438. ctx = get_current_context()
  439. ctx.meta[LANG_KEY] = value
  440. def get_language():
  441. return get_current_context().meta.get(LANG_KEY, 'en_US')
  442. .. versionadded:: 5.0
  443. """
  444. return self._meta
  445. def make_formatter(self) -> HelpFormatter:
  446. """Creates the :class:`~click.HelpFormatter` for the help and
  447. usage output.
  448. To quickly customize the formatter class used without overriding
  449. this method, set the :attr:`formatter_class` attribute.
  450. .. versionchanged:: 8.0
  451. Added the :attr:`formatter_class` attribute.
  452. """
  453. return self.formatter_class(
  454. width=self.terminal_width, max_width=self.max_content_width
  455. )
  456. def with_resource(self, context_manager: t.ContextManager[V]) -> V:
  457. """Register a resource as if it were used in a ``with``
  458. statement. The resource will be cleaned up when the context is
  459. popped.
  460. Uses :meth:`contextlib.ExitStack.enter_context`. It calls the
  461. resource's ``__enter__()`` method and returns the result. When
  462. the context is popped, it closes the stack, which calls the
  463. resource's ``__exit__()`` method.
  464. To register a cleanup function for something that isn't a
  465. context manager, use :meth:`call_on_close`. Or use something
  466. from :mod:`contextlib` to turn it into a context manager first.
  467. .. code-block:: python
  468. @click.group()
  469. @click.option("--name")
  470. @click.pass_context
  471. def cli(ctx):
  472. ctx.obj = ctx.with_resource(connect_db(name))
  473. :param context_manager: The context manager to enter.
  474. :return: Whatever ``context_manager.__enter__()`` returns.
  475. .. versionadded:: 8.0
  476. """
  477. return self._exit_stack.enter_context(context_manager)
  478. def call_on_close(self, f: t.Callable[..., t.Any]) -> t.Callable[..., t.Any]:
  479. """Register a function to be called when the context tears down.
  480. This can be used to close resources opened during the script
  481. execution. Resources that support Python's context manager
  482. protocol which would be used in a ``with`` statement should be
  483. registered with :meth:`with_resource` instead.
  484. :param f: The function to execute on teardown.
  485. """
  486. return self._exit_stack.callback(f)
  487. def close(self) -> None:
  488. """Invoke all close callbacks registered with
  489. :meth:`call_on_close`, and exit all context managers entered
  490. with :meth:`with_resource`.
  491. """
  492. self._exit_stack.close()
  493. # In case the context is reused, create a new exit stack.
  494. self._exit_stack = ExitStack()
  495. @property
  496. def command_path(self) -> str:
  497. """The computed command path. This is used for the ``usage``
  498. information on the help page. It's automatically created by
  499. combining the info names of the chain of contexts to the root.
  500. """
  501. rv = ""
  502. if self.info_name is not None:
  503. rv = self.info_name
  504. if self.parent is not None:
  505. parent_command_path = [self.parent.command_path]
  506. if isinstance(self.parent.command, Command):
  507. for param in self.parent.command.get_params(self):
  508. parent_command_path.extend(param.get_usage_pieces(self))
  509. rv = f"{' '.join(parent_command_path)} {rv}"
  510. return rv.lstrip()
  511. def find_root(self) -> "Context":
  512. """Finds the outermost context."""
  513. node = self
  514. while node.parent is not None:
  515. node = node.parent
  516. return node
  517. def find_object(self, object_type: t.Type[V]) -> t.Optional[V]:
  518. """Finds the closest object of a given type."""
  519. node: t.Optional["Context"] = self
  520. while node is not None:
  521. if isinstance(node.obj, object_type):
  522. return node.obj
  523. node = node.parent
  524. return None
  525. def ensure_object(self, object_type: t.Type[V]) -> V:
  526. """Like :meth:`find_object` but sets the innermost object to a
  527. new instance of `object_type` if it does not exist.
  528. """
  529. rv = self.find_object(object_type)
  530. if rv is None:
  531. self.obj = rv = object_type()
  532. return rv
  533. @typing.overload
  534. def lookup_default(
  535. self, name: str, call: "te.Literal[True]" = True
  536. ) -> t.Optional[t.Any]:
  537. ...
  538. @typing.overload
  539. def lookup_default(
  540. self, name: str, call: "te.Literal[False]" = ...
  541. ) -> t.Optional[t.Union[t.Any, t.Callable[[], t.Any]]]:
  542. ...
  543. def lookup_default(self, name: str, call: bool = True) -> t.Optional[t.Any]:
  544. """Get the default for a parameter from :attr:`default_map`.
  545. :param name: Name of the parameter.
  546. :param call: If the default is a callable, call it. Disable to
  547. return the callable instead.
  548. .. versionchanged:: 8.0
  549. Added the ``call`` parameter.
  550. """
  551. if self.default_map is not None:
  552. value = self.default_map.get(name)
  553. if call and callable(value):
  554. return value()
  555. return value
  556. return None
  557. def fail(self, message: str) -> "te.NoReturn":
  558. """Aborts the execution of the program with a specific error
  559. message.
  560. :param message: the error message to fail with.
  561. """
  562. raise UsageError(message, self)
  563. def abort(self) -> "te.NoReturn":
  564. """Aborts the script."""
  565. raise Abort()
  566. def exit(self, code: int = 0) -> "te.NoReturn":
  567. """Exits the application with a given exit code."""
  568. raise Exit(code)
  569. def get_usage(self) -> str:
  570. """Helper method to get formatted usage string for the current
  571. context and command.
  572. """
  573. return self.command.get_usage(self)
  574. def get_help(self) -> str:
  575. """Helper method to get formatted help page for the current
  576. context and command.
  577. """
  578. return self.command.get_help(self)
  579. def _make_sub_context(self, command: "Command") -> "Context":
  580. """Create a new context of the same type as this context, but
  581. for a new command.
  582. :meta private:
  583. """
  584. return type(self)(command, info_name=command.name, parent=self)
  585. def invoke(
  586. __self, # noqa: B902
  587. __callback: t.Union["Command", t.Callable[..., t.Any]],
  588. *args: t.Any,
  589. **kwargs: t.Any,
  590. ) -> t.Any:
  591. """Invokes a command callback in exactly the way it expects. There
  592. are two ways to invoke this method:
  593. 1. the first argument can be a callback and all other arguments and
  594. keyword arguments are forwarded directly to the function.
  595. 2. the first argument is a click command object. In that case all
  596. arguments are forwarded as well but proper click parameters
  597. (options and click arguments) must be keyword arguments and Click
  598. will fill in defaults.
  599. Note that before Click 3.2 keyword arguments were not properly filled
  600. in against the intention of this code and no context was created. For
  601. more information about this change and why it was done in a bugfix
  602. release see :ref:`upgrade-to-3.2`.
  603. .. versionchanged:: 8.0
  604. All ``kwargs`` are tracked in :attr:`params` so they will be
  605. passed if :meth:`forward` is called at multiple levels.
  606. """
  607. if isinstance(__callback, Command):
  608. other_cmd = __callback
  609. if other_cmd.callback is None:
  610. raise TypeError(
  611. "The given command does not have a callback that can be invoked."
  612. )
  613. else:
  614. __callback = other_cmd.callback
  615. ctx = __self._make_sub_context(other_cmd)
  616. for param in other_cmd.params:
  617. if param.name not in kwargs and param.expose_value:
  618. kwargs[param.name] = param.get_default(ctx) # type: ignore
  619. # Track all kwargs as params, so that forward() will pass
  620. # them on in subsequent calls.
  621. ctx.params.update(kwargs)
  622. else:
  623. ctx = __self
  624. with augment_usage_errors(__self):
  625. with ctx:
  626. return __callback(*args, **kwargs)
  627. def forward(
  628. __self, __cmd: "Command", *args: t.Any, **kwargs: t.Any # noqa: B902
  629. ) -> t.Any:
  630. """Similar to :meth:`invoke` but fills in default keyword
  631. arguments from the current context if the other command expects
  632. it. This cannot invoke callbacks directly, only other commands.
  633. .. versionchanged:: 8.0
  634. All ``kwargs`` are tracked in :attr:`params` so they will be
  635. passed if ``forward`` is called at multiple levels.
  636. """
  637. # Can only forward to other commands, not direct callbacks.
  638. if not isinstance(__cmd, Command):
  639. raise TypeError("Callback is not a command.")
  640. for param in __self.params:
  641. if param not in kwargs:
  642. kwargs[param] = __self.params[param]
  643. return __self.invoke(__cmd, *args, **kwargs)
  644. def set_parameter_source(self, name: str, source: ParameterSource) -> None:
  645. """Set the source of a parameter. This indicates the location
  646. from which the value of the parameter was obtained.
  647. :param name: The name of the parameter.
  648. :param source: A member of :class:`~click.core.ParameterSource`.
  649. """
  650. self._parameter_source[name] = source
  651. def get_parameter_source(self, name: str) -> t.Optional[ParameterSource]:
  652. """Get the source of a parameter. This indicates the location
  653. from which the value of the parameter was obtained.
  654. This can be useful for determining when a user specified a value
  655. on the command line that is the same as the default value. It
  656. will be :attr:`~click.core.ParameterSource.DEFAULT` only if the
  657. value was actually taken from the default.
  658. :param name: The name of the parameter.
  659. :rtype: ParameterSource
  660. .. versionchanged:: 8.0
  661. Returns ``None`` if the parameter was not provided from any
  662. source.
  663. """
  664. return self._parameter_source.get(name)
  665. class BaseCommand:
  666. """The base command implements the minimal API contract of commands.
  667. Most code will never use this as it does not implement a lot of useful
  668. functionality but it can act as the direct subclass of alternative
  669. parsing methods that do not depend on the Click parser.
  670. For instance, this can be used to bridge Click and other systems like
  671. argparse or docopt.
  672. Because base commands do not implement a lot of the API that other
  673. parts of Click take for granted, they are not supported for all
  674. operations. For instance, they cannot be used with the decorators
  675. usually and they have no built-in callback system.
  676. .. versionchanged:: 2.0
  677. Added the `context_settings` parameter.
  678. :param name: the name of the command to use unless a group overrides it.
  679. :param context_settings: an optional dictionary with defaults that are
  680. passed to the context object.
  681. """
  682. #: The context class to create with :meth:`make_context`.
  683. #:
  684. #: .. versionadded:: 8.0
  685. context_class: t.Type[Context] = Context
  686. #: the default for the :attr:`Context.allow_extra_args` flag.
  687. allow_extra_args = False
  688. #: the default for the :attr:`Context.allow_interspersed_args` flag.
  689. allow_interspersed_args = True
  690. #: the default for the :attr:`Context.ignore_unknown_options` flag.
  691. ignore_unknown_options = False
  692. def __init__(
  693. self,
  694. name: t.Optional[str],
  695. context_settings: t.Optional[t.Dict[str, t.Any]] = None,
  696. ) -> None:
  697. #: the name the command thinks it has. Upon registering a command
  698. #: on a :class:`Group` the group will default the command name
  699. #: with this information. You should instead use the
  700. #: :class:`Context`\'s :attr:`~Context.info_name` attribute.
  701. self.name = name
  702. if context_settings is None:
  703. context_settings = {}
  704. #: an optional dictionary with defaults passed to the context.
  705. self.context_settings: t.Dict[str, t.Any] = context_settings
  706. def to_info_dict(self, ctx: Context) -> t.Dict[str, t.Any]:
  707. """Gather information that could be useful for a tool generating
  708. user-facing documentation. This traverses the entire structure
  709. below this command.
  710. Use :meth:`click.Context.to_info_dict` to traverse the entire
  711. CLI structure.
  712. :param ctx: A :class:`Context` representing this command.
  713. .. versionadded:: 8.0
  714. """
  715. return {"name": self.name}
  716. def __repr__(self) -> str:
  717. return f"<{self.__class__.__name__} {self.name}>"
  718. def get_usage(self, ctx: Context) -> str:
  719. raise NotImplementedError("Base commands cannot get usage")
  720. def get_help(self, ctx: Context) -> str:
  721. raise NotImplementedError("Base commands cannot get help")
  722. def make_context(
  723. self,
  724. info_name: t.Optional[str],
  725. args: t.List[str],
  726. parent: t.Optional[Context] = None,
  727. **extra: t.Any,
  728. ) -> Context:
  729. """This function when given an info name and arguments will kick
  730. off the parsing and create a new :class:`Context`. It does not
  731. invoke the actual command callback though.
  732. To quickly customize the context class used without overriding
  733. this method, set the :attr:`context_class` attribute.
  734. :param info_name: the info name for this invocation. Generally this
  735. is the most descriptive name for the script or
  736. command. For the toplevel script it's usually
  737. the name of the script, for commands below it it's
  738. the name of the command.
  739. :param args: the arguments to parse as list of strings.
  740. :param parent: the parent context if available.
  741. :param extra: extra keyword arguments forwarded to the context
  742. constructor.
  743. .. versionchanged:: 8.0
  744. Added the :attr:`context_class` attribute.
  745. """
  746. for key, value in self.context_settings.items():
  747. if key not in extra:
  748. extra[key] = value
  749. ctx = self.context_class(
  750. self, info_name=info_name, parent=parent, **extra # type: ignore
  751. )
  752. with ctx.scope(cleanup=False):
  753. self.parse_args(ctx, args)
  754. return ctx
  755. def parse_args(self, ctx: Context, args: t.List[str]) -> t.List[str]:
  756. """Given a context and a list of arguments this creates the parser
  757. and parses the arguments, then modifies the context as necessary.
  758. This is automatically invoked by :meth:`make_context`.
  759. """
  760. raise NotImplementedError("Base commands do not know how to parse arguments.")
  761. def invoke(self, ctx: Context) -> t.Any:
  762. """Given a context, this invokes the command. The default
  763. implementation is raising a not implemented error.
  764. """
  765. raise NotImplementedError("Base commands are not invokable by default")
  766. def shell_complete(self, ctx: Context, incomplete: str) -> t.List["CompletionItem"]:
  767. """Return a list of completions for the incomplete value. Looks
  768. at the names of chained multi-commands.
  769. Any command could be part of a chained multi-command, so sibling
  770. commands are valid at any point during command completion. Other
  771. command classes will return more completions.
  772. :param ctx: Invocation context for this command.
  773. :param incomplete: Value being completed. May be empty.
  774. .. versionadded:: 8.0
  775. """
  776. from click.shell_completion import CompletionItem
  777. results: t.List["CompletionItem"] = []
  778. while ctx.parent is not None:
  779. ctx = ctx.parent
  780. if isinstance(ctx.command, MultiCommand) and ctx.command.chain:
  781. results.extend(
  782. CompletionItem(name, help=command.get_short_help_str())
  783. for name, command in _complete_visible_commands(ctx, incomplete)
  784. if name not in ctx.protected_args
  785. )
  786. return results
  787. @typing.overload
  788. def main(
  789. self,
  790. args: t.Optional[t.Sequence[str]] = None,
  791. prog_name: t.Optional[str] = None,
  792. complete_var: t.Optional[str] = None,
  793. standalone_mode: "te.Literal[True]" = True,
  794. **extra: t.Any,
  795. ) -> "te.NoReturn":
  796. ...
  797. @typing.overload
  798. def main(
  799. self,
  800. args: t.Optional[t.Sequence[str]] = None,
  801. prog_name: t.Optional[str] = None,
  802. complete_var: t.Optional[str] = None,
  803. standalone_mode: bool = ...,
  804. **extra: t.Any,
  805. ) -> t.Any:
  806. ...
  807. def main(
  808. self,
  809. args: t.Optional[t.Sequence[str]] = None,
  810. prog_name: t.Optional[str] = None,
  811. complete_var: t.Optional[str] = None,
  812. standalone_mode: bool = True,
  813. windows_expand_args: bool = True,
  814. **extra: t.Any,
  815. ) -> t.Any:
  816. """This is the way to invoke a script with all the bells and
  817. whistles as a command line application. This will always terminate
  818. the application after a call. If this is not wanted, ``SystemExit``
  819. needs to be caught.
  820. This method is also available by directly calling the instance of
  821. a :class:`Command`.
  822. :param args: the arguments that should be used for parsing. If not
  823. provided, ``sys.argv[1:]`` is used.
  824. :param prog_name: the program name that should be used. By default
  825. the program name is constructed by taking the file
  826. name from ``sys.argv[0]``.
  827. :param complete_var: the environment variable that controls the
  828. bash completion support. The default is
  829. ``"_<prog_name>_COMPLETE"`` with prog_name in
  830. uppercase.
  831. :param standalone_mode: the default behavior is to invoke the script
  832. in standalone mode. Click will then
  833. handle exceptions and convert them into
  834. error messages and the function will never
  835. return but shut down the interpreter. If
  836. this is set to `False` they will be
  837. propagated to the caller and the return
  838. value of this function is the return value
  839. of :meth:`invoke`.
  840. :param windows_expand_args: Expand glob patterns, user dir, and
  841. env vars in command line args on Windows.
  842. :param extra: extra keyword arguments are forwarded to the context
  843. constructor. See :class:`Context` for more information.
  844. .. versionchanged:: 8.0.1
  845. Added the ``windows_expand_args`` parameter to allow
  846. disabling command line arg expansion on Windows.
  847. .. versionchanged:: 8.0
  848. When taking arguments from ``sys.argv`` on Windows, glob
  849. patterns, user dir, and env vars are expanded.
  850. .. versionchanged:: 3.0
  851. Added the ``standalone_mode`` parameter.
  852. """
  853. # Verify that the environment is configured correctly, or reject
  854. # further execution to avoid a broken script.
  855. _verify_python_env()
  856. if args is None:
  857. args = sys.argv[1:]
  858. if os.name == "nt" and windows_expand_args:
  859. args = _expand_args(args)
  860. else:
  861. args = list(args)
  862. if prog_name is None:
  863. prog_name = _detect_program_name()
  864. # Process shell completion requests and exit early.
  865. self._main_shell_completion(extra, prog_name, complete_var)
  866. try:
  867. try:
  868. with self.make_context(prog_name, args, **extra) as ctx:
  869. rv = self.invoke(ctx)
  870. if not standalone_mode:
  871. return rv
  872. # it's not safe to `ctx.exit(rv)` here!
  873. # note that `rv` may actually contain data like "1" which
  874. # has obvious effects
  875. # more subtle case: `rv=[None, None]` can come out of
  876. # chained commands which all returned `None` -- so it's not
  877. # even always obvious that `rv` indicates success/failure
  878. # by its truthiness/falsiness
  879. ctx.exit()
  880. except (EOFError, KeyboardInterrupt):
  881. echo(file=sys.stderr)
  882. raise Abort()
  883. except ClickException as e:
  884. if not standalone_mode:
  885. raise
  886. e.show()
  887. sys.exit(e.exit_code)
  888. except OSError as e:
  889. if e.errno == errno.EPIPE:
  890. sys.stdout = t.cast(t.TextIO, PacifyFlushWrapper(sys.stdout))
  891. sys.stderr = t.cast(t.TextIO, PacifyFlushWrapper(sys.stderr))
  892. sys.exit(1)
  893. else:
  894. raise
  895. except Exit as e:
  896. if standalone_mode:
  897. sys.exit(e.exit_code)
  898. else:
  899. # in non-standalone mode, return the exit code
  900. # note that this is only reached if `self.invoke` above raises
  901. # an Exit explicitly -- thus bypassing the check there which
  902. # would return its result
  903. # the results of non-standalone execution may therefore be
  904. # somewhat ambiguous: if there are codepaths which lead to
  905. # `ctx.exit(1)` and to `return 1`, the caller won't be able to
  906. # tell the difference between the two
  907. return e.exit_code
  908. except Abort:
  909. if not standalone_mode:
  910. raise
  911. echo(_("Aborted!"), file=sys.stderr)
  912. sys.exit(1)
  913. def _main_shell_completion(
  914. self,
  915. ctx_args: t.Dict[str, t.Any],
  916. prog_name: str,
  917. complete_var: t.Optional[str] = None,
  918. ) -> None:
  919. """Check if the shell is asking for tab completion, process
  920. that, then exit early. Called from :meth:`main` before the
  921. program is invoked.
  922. :param prog_name: Name of the executable in the shell.
  923. :param complete_var: Name of the environment variable that holds
  924. the completion instruction. Defaults to
  925. ``_{PROG_NAME}_COMPLETE``.
  926. """
  927. if complete_var is None:
  928. complete_var = f"_{prog_name}_COMPLETE".replace("-", "_").upper()
  929. instruction = os.environ.get(complete_var)
  930. if not instruction:
  931. return
  932. from .shell_completion import shell_complete
  933. rv = shell_complete(self, ctx_args, prog_name, complete_var, instruction)
  934. _fast_exit(rv)
  935. def __call__(self, *args: t.Any, **kwargs: t.Any) -> t.Any:
  936. """Alias for :meth:`main`."""
  937. return self.main(*args, **kwargs)
  938. class Command(BaseCommand):
  939. """Commands are the basic building block of command line interfaces in
  940. Click. A basic command handles command line parsing and might dispatch
  941. more parsing to commands nested below it.
  942. .. versionchanged:: 2.0
  943. Added the `context_settings` parameter.
  944. .. versionchanged:: 8.0
  945. Added repr showing the command name
  946. .. versionchanged:: 7.1
  947. Added the `no_args_is_help` parameter.
  948. :param name: the name of the command to use unless a group overrides it.
  949. :param context_settings: an optional dictionary with defaults that are
  950. passed to the context object.
  951. :param callback: the callback to invoke. This is optional.
  952. :param params: the parameters to register with this command. This can
  953. be either :class:`Option` or :class:`Argument` objects.
  954. :param help: the help string to use for this command.
  955. :param epilog: like the help string but it's printed at the end of the
  956. help page after everything else.
  957. :param short_help: the short help to use for this command. This is
  958. shown on the command listing of the parent command.
  959. :param add_help_option: by default each command registers a ``--help``
  960. option. This can be disabled by this parameter.
  961. :param no_args_is_help: this controls what happens if no arguments are
  962. provided. This option is disabled by default.
  963. If enabled this will add ``--help`` as argument
  964. if no arguments are passed
  965. :param hidden: hide this command from help outputs.
  966. :param deprecated: issues a message indicating that
  967. the command is deprecated.
  968. """
  969. def __init__(
  970. self,
  971. name: t.Optional[str],
  972. context_settings: t.Optional[t.Dict[str, t.Any]] = None,
  973. callback: t.Optional[t.Callable[..., t.Any]] = None,
  974. params: t.Optional[t.List["Parameter"]] = None,
  975. help: t.Optional[str] = None,
  976. epilog: t.Optional[str] = None,
  977. short_help: t.Optional[str] = None,
  978. options_metavar: t.Optional[str] = "[OPTIONS]",
  979. add_help_option: bool = True,
  980. no_args_is_help: bool = False,
  981. hidden: bool = False,
  982. deprecated: bool = False,
  983. ) -> None:
  984. super().__init__(name, context_settings)
  985. #: the callback to execute when the command fires. This might be
  986. #: `None` in which case nothing happens.
  987. self.callback = callback
  988. #: the list of parameters for this command in the order they
  989. #: should show up in the help page and execute. Eager parameters
  990. #: will automatically be handled before non eager ones.
  991. self.params: t.List["Parameter"] = params or []
  992. # if a form feed (page break) is found in the help text, truncate help
  993. # text to the content preceding the first form feed
  994. if help and "\f" in help:
  995. help = help.split("\f", 1)[0]
  996. self.help = help
  997. self.epilog = epilog
  998. self.options_metavar = options_metavar
  999. self.short_help = short_help
  1000. self.add_help_option = add_help_option
  1001. self.no_args_is_help = no_args_is_help
  1002. self.hidden = hidden
  1003. self.deprecated = deprecated
  1004. def to_info_dict(self, ctx: Context) -> t.Dict[str, t.Any]:
  1005. info_dict = super().to_info_dict(ctx)
  1006. info_dict.update(
  1007. params=[param.to_info_dict() for param in self.get_params(ctx)],
  1008. help=self.help,
  1009. epilog=self.epilog,
  1010. short_help=self.short_help,
  1011. hidden=self.hidden,
  1012. deprecated=self.deprecated,
  1013. )
  1014. return info_dict
  1015. def get_usage(self, ctx: Context) -> str:
  1016. """Formats the usage line into a string and returns it.
  1017. Calls :meth:`format_usage` internally.
  1018. """
  1019. formatter = ctx.make_formatter()
  1020. self.format_usage(ctx, formatter)
  1021. return formatter.getvalue().rstrip("\n")
  1022. def get_params(self, ctx: Context) -> t.List["Parameter"]:
  1023. rv = self.params
  1024. help_option = self.get_help_option(ctx)
  1025. if help_option is not None:
  1026. rv = [*rv, help_option]
  1027. return rv
  1028. def format_usage(self, ctx: Context, formatter: HelpFormatter) -> None:
  1029. """Writes the usage line into the formatter.
  1030. This is a low-level method called by :meth:`get_usage`.
  1031. """
  1032. pieces = self.collect_usage_pieces(ctx)
  1033. formatter.write_usage(ctx.command_path, " ".join(pieces))
  1034. def collect_usage_pieces(self, ctx: Context) -> t.List[str]:
  1035. """Returns all the pieces that go into the usage line and returns
  1036. it as a list of strings.
  1037. """
  1038. rv = [self.options_metavar] if self.options_metavar else []
  1039. for param in self.get_params(ctx):
  1040. rv.extend(param.get_usage_pieces(ctx))
  1041. return rv
  1042. def get_help_option_names(self, ctx: Context) -> t.List[str]:
  1043. """Returns the names for the help option."""
  1044. all_names = set(ctx.help_option_names)
  1045. for param in self.params:
  1046. all_names.difference_update(param.opts)
  1047. all_names.difference_update(param.secondary_opts)
  1048. return list(all_names)
  1049. def get_help_option(self, ctx: Context) -> t.Optional["Option"]:
  1050. """Returns the help option object."""
  1051. help_options = self.get_help_option_names(ctx)
  1052. if not help_options or not self.add_help_option:
  1053. return None
  1054. def show_help(ctx: Context, param: "Parameter", value: str) -> None:
  1055. if value and not ctx.resilient_parsing:
  1056. echo(ctx.get_help(), color=ctx.color)
  1057. ctx.exit()
  1058. return Option(
  1059. help_options,
  1060. is_flag=True,
  1061. is_eager=True,
  1062. expose_value=False,
  1063. callback=show_help,
  1064. help=_("Show this message and exit."),
  1065. )
  1066. def make_parser(self, ctx: Context) -> OptionParser:
  1067. """Creates the underlying option parser for this command."""
  1068. parser = OptionParser(ctx)
  1069. for param in self.get_params(ctx):
  1070. param.add_to_parser(parser, ctx)
  1071. return parser
  1072. def get_help(self, ctx: Context) -> str:
  1073. """Formats the help into a string and returns it.
  1074. Calls :meth:`format_help` internally.
  1075. """
  1076. formatter = ctx.make_formatter()
  1077. self.format_help(ctx, formatter)
  1078. return formatter.getvalue().rstrip("\n")
  1079. def get_short_help_str(self, limit: int = 45) -> str:
  1080. """Gets short help for the command or makes it by shortening the
  1081. long help string.
  1082. """
  1083. text = self.short_help or ""
  1084. if not text and self.help:
  1085. text = make_default_short_help(self.help, limit)
  1086. if self.deprecated:
  1087. text = _("(Deprecated) {text}").format(text=text)
  1088. return text.strip()
  1089. def format_help(self, ctx: Context, formatter: HelpFormatter) -> None:
  1090. """Writes the help into the formatter if it exists.
  1091. This is a low-level method called by :meth:`get_help`.
  1092. This calls the following methods:
  1093. - :meth:`format_usage`
  1094. - :meth:`format_help_text`
  1095. - :meth:`format_options`
  1096. - :meth:`format_epilog`
  1097. """
  1098. self.format_usage(ctx, formatter)
  1099. self.format_help_text(ctx, formatter)
  1100. self.format_options(ctx, formatter)
  1101. self.format_epilog(ctx, formatter)
  1102. def format_help_text(self, ctx: Context, formatter: HelpFormatter) -> None:
  1103. """Writes the help text to the formatter if it exists."""
  1104. text = self.help or ""
  1105. if self.deprecated:
  1106. text = _("(Deprecated) {text}").format(text=text)
  1107. if text:
  1108. formatter.write_paragraph()
  1109. with formatter.indentation():
  1110. formatter.write_text(text)
  1111. def format_options(self, ctx: Context, formatter: HelpFormatter) -> None:
  1112. """Writes all the options into the formatter if they exist."""
  1113. opts = []
  1114. for param in self.get_params(ctx):
  1115. rv = param.get_help_record(ctx)
  1116. if rv is not None:
  1117. opts.append(rv)
  1118. if opts:
  1119. with formatter.section(_("Options")):
  1120. formatter.write_dl(opts)
  1121. def format_epilog(self, ctx: Context, formatter: HelpFormatter) -> None:
  1122. """Writes the epilog into the formatter if it exists."""
  1123. if self.epilog:
  1124. formatter.write_paragraph()
  1125. with formatter.indentation():
  1126. formatter.write_text(self.epilog)
  1127. def parse_args(self, ctx: Context, args: t.List[str]) -> t.List[str]:
  1128. if not args and self.no_args_is_help and not ctx.resilient_parsing:
  1129. echo(ctx.get_help(), color=ctx.color)
  1130. ctx.exit()
  1131. parser = self.make_parser(ctx)
  1132. opts, args, param_order = parser.parse_args(args=args)
  1133. for param in iter_params_for_processing(param_order, self.get_params(ctx)):
  1134. value, args = param.handle_parse_result(ctx, opts, args)
  1135. if args and not ctx.allow_extra_args and not ctx.resilient_parsing:
  1136. ctx.fail(
  1137. ngettext(
  1138. "Got unexpected extra argument ({args})",
  1139. "Got unexpected extra arguments ({args})",
  1140. len(args),
  1141. ).format(args=" ".join(map(str, args)))
  1142. )
  1143. ctx.args = args
  1144. return args
  1145. def invoke(self, ctx: Context) -> t.Any:
  1146. """Given a context, this invokes the attached callback (if it exists)
  1147. in the right way.
  1148. """
  1149. if self.deprecated:
  1150. message = _(
  1151. "DeprecationWarning: The command {name!r} is deprecated."
  1152. ).format(name=self.name)
  1153. echo(style(message, fg="red"), err=True)
  1154. if self.callback is not None:
  1155. return ctx.invoke(self.callback, **ctx.params)
  1156. def shell_complete(self, ctx: Context, incomplete: str) -> t.List["CompletionItem"]:
  1157. """Return a list of completions for the incomplete value. Looks
  1158. at the names of options and chained multi-commands.
  1159. :param ctx: Invocation context for this command.
  1160. :param incomplete: Value being completed. May be empty.
  1161. .. versionadded:: 8.0
  1162. """
  1163. from click.shell_completion import CompletionItem
  1164. results: t.List["CompletionItem"] = []
  1165. if incomplete and not incomplete[0].isalnum():
  1166. for param in self.get_params(ctx):
  1167. if (
  1168. not isinstance(param, Option)
  1169. or param.hidden
  1170. or (
  1171. not param.multiple
  1172. and ctx.get_parameter_source(param.name) # type: ignore
  1173. is ParameterSource.COMMANDLINE
  1174. )
  1175. ):
  1176. continue
  1177. results.extend(
  1178. CompletionItem(name, help=param.help)
  1179. for name in [*param.opts, *param.secondary_opts]
  1180. if name.startswith(incomplete)
  1181. )
  1182. results.extend(super().shell_complete(ctx, incomplete))
  1183. return results
  1184. class MultiCommand(Command):
  1185. """A multi command is the basic implementation of a command that
  1186. dispatches to subcommands. The most common version is the
  1187. :class:`Group`.
  1188. :param invoke_without_command: this controls how the multi command itself
  1189. is invoked. By default it's only invoked
  1190. if a subcommand is provided.
  1191. :param no_args_is_help: this controls what happens if no arguments are
  1192. provided. This option is enabled by default if
  1193. `invoke_without_command` is disabled or disabled
  1194. if it's enabled. If enabled this will add
  1195. ``--help`` as argument if no arguments are
  1196. passed.
  1197. :param subcommand_metavar: the string that is used in the documentation
  1198. to indicate the subcommand place.
  1199. :param chain: if this is set to `True` chaining of multiple subcommands
  1200. is enabled. This restricts the form of commands in that
  1201. they cannot have optional arguments but it allows
  1202. multiple commands to be chained together.
  1203. :param result_callback: The result callback to attach to this multi
  1204. command. This can be set or changed later with the
  1205. :meth:`result_callback` decorator.
  1206. """
  1207. allow_extra_args = True
  1208. allow_interspersed_args = False
  1209. def __init__(
  1210. self,
  1211. name: t.Optional[str] = None,
  1212. invoke_without_command: bool = False,
  1213. no_args_is_help: t.Optional[bool] = None,
  1214. subcommand_metavar: t.Optional[str] = None,
  1215. chain: bool = False,
  1216. result_callback: t.Optional[t.Callable[..., t.Any]] = None,
  1217. **attrs: t.Any,
  1218. ) -> None:
  1219. super().__init__(name, **attrs)
  1220. if no_args_is_help is None:
  1221. no_args_is_help = not invoke_without_command
  1222. self.no_args_is_help = no_args_is_help
  1223. self.invoke_without_command = invoke_without_command
  1224. if subcommand_metavar is None:
  1225. if chain:
  1226. subcommand_metavar = "COMMAND1 [ARGS]... [COMMAND2 [ARGS]...]..."
  1227. else:
  1228. subcommand_metavar = "COMMAND [ARGS]..."
  1229. self.subcommand_metavar = subcommand_metavar
  1230. self.chain = chain
  1231. # The result callback that is stored. This can be set or
  1232. # overridden with the :func:`result_callback` decorator.
  1233. self._result_callback = result_callback
  1234. if self.chain:
  1235. for param in self.params:
  1236. if isinstance(param, Argument) and not param.required:
  1237. raise RuntimeError(
  1238. "Multi commands in chain mode cannot have"
  1239. " optional arguments."
  1240. )
  1241. def to_info_dict(self, ctx: Context) -> t.Dict[str, t.Any]:
  1242. info_dict = super().to_info_dict(ctx)
  1243. commands = {}
  1244. for name in self.list_commands(ctx):
  1245. command = self.get_command(ctx, name)
  1246. if command is None:
  1247. continue
  1248. sub_ctx = ctx._make_sub_context(command)
  1249. with sub_ctx.scope(cleanup=False):
  1250. commands[name] = command.to_info_dict(sub_ctx)
  1251. info_dict.update(commands=commands, chain=self.chain)
  1252. return info_dict
  1253. def collect_usage_pieces(self, ctx: Context) -> t.List[str]:
  1254. rv = super().collect_usage_pieces(ctx)
  1255. rv.append(self.subcommand_metavar)
  1256. return rv
  1257. def format_options(self, ctx: Context, formatter: HelpFormatter) -> None:
  1258. super().format_options(ctx, formatter)
  1259. self.format_commands(ctx, formatter)
  1260. def result_callback(self, replace: bool = False) -> t.Callable[[F], F]:
  1261. """Adds a result callback to the command. By default if a
  1262. result callback is already registered this will chain them but
  1263. this can be disabled with the `replace` parameter. The result
  1264. callback is invoked with the return value of the subcommand
  1265. (or the list of return values from all subcommands if chaining
  1266. is enabled) as well as the parameters as they would be passed
  1267. to the main callback.
  1268. Example::
  1269. @click.group()
  1270. @click.option('-i', '--input', default=23)
  1271. def cli(input):
  1272. return 42
  1273. @cli.result_callback()
  1274. def process_result(result, input):
  1275. return result + input
  1276. :param replace: if set to `True` an already existing result
  1277. callback will be removed.
  1278. .. versionchanged:: 8.0
  1279. Renamed from ``resultcallback``.
  1280. .. versionadded:: 3.0
  1281. """
  1282. def decorator(f: F) -> F:
  1283. old_callback = self._result_callback
  1284. if old_callback is None or replace:
  1285. self._result_callback = f
  1286. return f
  1287. def function(__value, *args, **kwargs): # type: ignore
  1288. inner = old_callback(__value, *args, **kwargs) # type: ignore
  1289. return f(inner, *args, **kwargs)
  1290. self._result_callback = rv = update_wrapper(t.cast(F, function), f)
  1291. return rv
  1292. return decorator
  1293. def resultcallback(self, replace: bool = False) -> t.Callable[[F], F]:
  1294. import warnings
  1295. warnings.warn(
  1296. "'resultcallback' has been renamed to 'result_callback'."
  1297. " The old name will be removed in Click 8.1.",
  1298. DeprecationWarning,
  1299. stacklevel=2,
  1300. )
  1301. return self.result_callback(replace=replace)
  1302. def format_commands(self, ctx: Context, formatter: HelpFormatter) -> None:
  1303. """Extra format methods for multi methods that adds all the commands
  1304. after the options.
  1305. """
  1306. commands = []
  1307. for subcommand in self.list_commands(ctx):
  1308. cmd = self.get_command(ctx, subcommand)
  1309. # What is this, the tool lied about a command. Ignore it
  1310. if cmd is None:
  1311. continue
  1312. if cmd.hidden:
  1313. continue
  1314. commands.append((subcommand, cmd))
  1315. # allow for 3 times the default spacing
  1316. if len(commands):
  1317. limit = formatter.width - 6 - max(len(cmd[0]) for cmd in commands)
  1318. rows = []
  1319. for subcommand, cmd in commands:
  1320. help = cmd.get_short_help_str(limit)
  1321. rows.append((subcommand, help))
  1322. if rows:
  1323. with formatter.section(_("Commands")):
  1324. formatter.write_dl(rows)
  1325. def parse_args(self, ctx: Context, args: t.List[str]) -> t.List[str]:
  1326. if not args and self.no_args_is_help and not ctx.resilient_parsing:
  1327. echo(ctx.get_help(), color=ctx.color)
  1328. ctx.exit()
  1329. rest = super().parse_args(ctx, args)
  1330. if self.chain:
  1331. ctx.protected_args = rest
  1332. ctx.args = []
  1333. elif rest:
  1334. ctx.protected_args, ctx.args = rest[:1], rest[1:]
  1335. return ctx.args
  1336. def invoke(self, ctx: Context) -> t.Any:
  1337. def _process_result(value: t.Any) -> t.Any:
  1338. if self._result_callback is not None:
  1339. value = ctx.invoke(self._result_callback, value, **ctx.params)
  1340. return value
  1341. if not ctx.protected_args:
  1342. if self.invoke_without_command:
  1343. # No subcommand was invoked, so the result callback is
  1344. # invoked with None for regular groups, or an empty list
  1345. # for chained groups.
  1346. with ctx:
  1347. super().invoke(ctx)
  1348. return _process_result([] if self.chain else None)
  1349. ctx.fail(_("Missing command."))
  1350. # Fetch args back out
  1351. args = [*ctx.protected_args, *ctx.args]
  1352. ctx.args = []
  1353. ctx.protected_args = []
  1354. # If we're not in chain mode, we only allow the invocation of a
  1355. # single command but we also inform the current context about the
  1356. # name of the command to invoke.
  1357. if not self.chain:
  1358. # Make sure the context is entered so we do not clean up
  1359. # resources until the result processor has worked.
  1360. with ctx:
  1361. cmd_name, cmd, args = self.resolve_command(ctx, args)
  1362. assert cmd is not None
  1363. ctx.invoked_subcommand = cmd_name
  1364. super().invoke(ctx)
  1365. sub_ctx = cmd.make_context(cmd_name, args, parent=ctx)
  1366. with sub_ctx:
  1367. return _process_result(sub_ctx.command.invoke(sub_ctx))
  1368. # In chain mode we create the contexts step by step, but after the
  1369. # base command has been invoked. Because at that point we do not
  1370. # know the subcommands yet, the invoked subcommand attribute is
  1371. # set to ``*`` to inform the command that subcommands are executed
  1372. # but nothing else.
  1373. with ctx:
  1374. ctx.invoked_subcommand = "*" if args else None
  1375. super().invoke(ctx)
  1376. # Otherwise we make every single context and invoke them in a
  1377. # chain. In that case the return value to the result processor
  1378. # is the list of all invoked subcommand's results.
  1379. contexts = []
  1380. while args:
  1381. cmd_name, cmd, args = self.resolve_command(ctx, args)
  1382. assert cmd is not None
  1383. sub_ctx = cmd.make_context(
  1384. cmd_name,
  1385. args,
  1386. parent=ctx,
  1387. allow_extra_args=True,
  1388. allow_interspersed_args=False,
  1389. )
  1390. contexts.append(sub_ctx)
  1391. args, sub_ctx.args = sub_ctx.args, []
  1392. rv = []
  1393. for sub_ctx in contexts:
  1394. with sub_ctx:
  1395. rv.append(sub_ctx.command.invoke(sub_ctx))
  1396. return _process_result(rv)
  1397. def resolve_command(
  1398. self, ctx: Context, args: t.List[str]
  1399. ) -> t.Tuple[t.Optional[str], t.Optional[Command], t.List[str]]:
  1400. cmd_name = make_str(args[0])
  1401. original_cmd_name = cmd_name
  1402. # Get the command
  1403. cmd = self.get_command(ctx, cmd_name)
  1404. # If we can't find the command but there is a normalization
  1405. # function available, we try with that one.
  1406. if cmd is None and ctx.token_normalize_func is not None:
  1407. cmd_name = ctx.token_normalize_func(cmd_name)
  1408. cmd = self.get_command(ctx, cmd_name)
  1409. # If we don't find the command we want to show an error message
  1410. # to the user that it was not provided. However, there is
  1411. # something else we should do: if the first argument looks like
  1412. # an option we want to kick off parsing again for arguments to
  1413. # resolve things like --help which now should go to the main
  1414. # place.
  1415. if cmd is None and not ctx.resilient_parsing:
  1416. if split_opt(cmd_name)[0]:
  1417. self.parse_args(ctx, ctx.args)
  1418. ctx.fail(_("No such command {name!r}.").format(name=original_cmd_name))
  1419. return cmd_name if cmd else None, cmd, args[1:]
  1420. def get_command(self, ctx: Context, cmd_name: str) -> t.Optional[Command]:
  1421. """Given a context and a command name, this returns a
  1422. :class:`Command` object if it exists or returns `None`.
  1423. """
  1424. raise NotImplementedError
  1425. def list_commands(self, ctx: Context) -> t.List[str]:
  1426. """Returns a list of subcommand names in the order they should
  1427. appear.
  1428. """
  1429. return []
  1430. def shell_complete(self, ctx: Context, incomplete: str) -> t.List["CompletionItem"]:
  1431. """Return a list of completions for the incomplete value. Looks
  1432. at the names of options, subcommands, and chained
  1433. multi-commands.
  1434. :param ctx: Invocation context for this command.
  1435. :param incomplete: Value being completed. May be empty.
  1436. .. versionadded:: 8.0
  1437. """
  1438. from click.shell_completion import CompletionItem
  1439. results = [
  1440. CompletionItem(name, help=command.get_short_help_str())
  1441. for name, command in _complete_visible_commands(ctx, incomplete)
  1442. ]
  1443. results.extend(super().shell_complete(ctx, incomplete))
  1444. return results
  1445. class Group(MultiCommand):
  1446. """A group allows a command to have subcommands attached. This is
  1447. the most common way to implement nesting in Click.
  1448. :param name: The name of the group command.
  1449. :param commands: A dict mapping names to :class:`Command` objects.
  1450. Can also be a list of :class:`Command`, which will use
  1451. :attr:`Command.name` to create the dict.
  1452. :param attrs: Other command arguments described in
  1453. :class:`MultiCommand`, :class:`Command`, and
  1454. :class:`BaseCommand`.
  1455. .. versionchanged:: 8.0
  1456. The ``commmands`` argument can be a list of command objects.
  1457. """
  1458. #: If set, this is used by the group's :meth:`command` decorator
  1459. #: as the default :class:`Command` class. This is useful to make all
  1460. #: subcommands use a custom command class.
  1461. #:
  1462. #: .. versionadded:: 8.0
  1463. command_class: t.Optional[t.Type[Command]] = None
  1464. #: If set, this is used by the group's :meth:`group` decorator
  1465. #: as the default :class:`Group` class. This is useful to make all
  1466. #: subgroups use a custom group class.
  1467. #:
  1468. #: If set to the special value :class:`type` (literally
  1469. #: ``group_class = type``), this group's class will be used as the
  1470. #: default class. This makes a custom group class continue to make
  1471. #: custom groups.
  1472. #:
  1473. #: .. versionadded:: 8.0
  1474. group_class: t.Optional[t.Union[t.Type["Group"], t.Type[type]]] = None
  1475. # Literal[type] isn't valid, so use Type[type]
  1476. def __init__(
  1477. self,
  1478. name: t.Optional[str] = None,
  1479. commands: t.Optional[t.Union[t.Dict[str, Command], t.Sequence[Command]]] = None,
  1480. **attrs: t.Any,
  1481. ) -> None:
  1482. super().__init__(name, **attrs)
  1483. if commands is None:
  1484. commands = {}
  1485. elif isinstance(commands, abc.Sequence):
  1486. commands = {c.name: c for c in commands if c.name is not None}
  1487. #: The registered subcommands by their exported names.
  1488. self.commands: t.Dict[str, Command] = commands
  1489. def add_command(self, cmd: Command, name: t.Optional[str] = None) -> None:
  1490. """Registers another :class:`Command` with this group. If the name
  1491. is not provided, the name of the command is used.
  1492. """
  1493. name = name or cmd.name
  1494. if name is None:
  1495. raise TypeError("Command has no name.")
  1496. _check_multicommand(self, name, cmd, register=True)
  1497. self.commands[name] = cmd
  1498. def command(
  1499. self, *args: t.Any, **kwargs: t.Any
  1500. ) -> t.Callable[[t.Callable[..., t.Any]], Command]:
  1501. """A shortcut decorator for declaring and attaching a command to
  1502. the group. This takes the same arguments as :func:`command` and
  1503. immediately registers the created command with this group by
  1504. calling :meth:`add_command`.
  1505. To customize the command class used, set the
  1506. :attr:`command_class` attribute.
  1507. .. versionchanged:: 8.0
  1508. Added the :attr:`command_class` attribute.
  1509. """
  1510. from .decorators import command
  1511. if self.command_class is not None and "cls" not in kwargs:
  1512. kwargs["cls"] = self.command_class
  1513. def decorator(f: t.Callable[..., t.Any]) -> Command:
  1514. cmd = command(*args, **kwargs)(f)
  1515. self.add_command(cmd)
  1516. return cmd
  1517. return decorator
  1518. def group(
  1519. self, *args: t.Any, **kwargs: t.Any
  1520. ) -> t.Callable[[t.Callable[..., t.Any]], "Group"]:
  1521. """A shortcut decorator for declaring and attaching a group to
  1522. the group. This takes the same arguments as :func:`group` and
  1523. immediately registers the created group with this group by
  1524. calling :meth:`add_command`.
  1525. To customize the group class used, set the :attr:`group_class`
  1526. attribute.
  1527. .. versionchanged:: 8.0
  1528. Added the :attr:`group_class` attribute.
  1529. """
  1530. from .decorators import group
  1531. if self.group_class is not None and "cls" not in kwargs:
  1532. if self.group_class is type:
  1533. kwargs["cls"] = type(self)
  1534. else:
  1535. kwargs["cls"] = self.group_class
  1536. def decorator(f: t.Callable[..., t.Any]) -> "Group":
  1537. cmd = group(*args, **kwargs)(f)
  1538. self.add_command(cmd)
  1539. return cmd
  1540. return decorator
  1541. def get_command(self, ctx: Context, cmd_name: str) -> t.Optional[Command]:
  1542. return self.commands.get(cmd_name)
  1543. def list_commands(self, ctx: Context) -> t.List[str]:
  1544. return sorted(self.commands)
  1545. class CommandCollection(MultiCommand):
  1546. """A command collection is a multi command that merges multiple multi
  1547. commands together into one. This is a straightforward implementation
  1548. that accepts a list of different multi commands as sources and
  1549. provides all the commands for each of them.
  1550. """
  1551. def __init__(
  1552. self,
  1553. name: t.Optional[str] = None,
  1554. sources: t.Optional[t.List[MultiCommand]] = None,
  1555. **attrs: t.Any,
  1556. ) -> None:
  1557. super().__init__(name, **attrs)
  1558. #: The list of registered multi commands.
  1559. self.sources: t.List[MultiCommand] = sources or []
  1560. def add_source(self, multi_cmd: MultiCommand) -> None:
  1561. """Adds a new multi command to the chain dispatcher."""
  1562. self.sources.append(multi_cmd)
  1563. def get_command(self, ctx: Context, cmd_name: str) -> t.Optional[Command]:
  1564. for source in self.sources:
  1565. rv = source.get_command(ctx, cmd_name)
  1566. if rv is not None:
  1567. if self.chain:
  1568. _check_multicommand(self, cmd_name, rv)
  1569. return rv
  1570. return None
  1571. def list_commands(self, ctx: Context) -> t.List[str]:
  1572. rv: t.Set[str] = set()
  1573. for source in self.sources:
  1574. rv.update(source.list_commands(ctx))
  1575. return sorted(rv)
  1576. def _check_iter(value: t.Any) -> t.Iterator[t.Any]:
  1577. """Check if the value is iterable but not a string. Raises a type
  1578. error, or return an iterator over the value.
  1579. """
  1580. if isinstance(value, str):
  1581. raise TypeError
  1582. return iter(value)
  1583. class Parameter:
  1584. r"""A parameter to a command comes in two versions: they are either
  1585. :class:`Option`\s or :class:`Argument`\s. Other subclasses are currently
  1586. not supported by design as some of the internals for parsing are
  1587. intentionally not finalized.
  1588. Some settings are supported by both options and arguments.
  1589. :param param_decls: the parameter declarations for this option or
  1590. argument. This is a list of flags or argument
  1591. names.
  1592. :param type: the type that should be used. Either a :class:`ParamType`
  1593. or a Python type. The later is converted into the former
  1594. automatically if supported.
  1595. :param required: controls if this is optional or not.
  1596. :param default: the default value if omitted. This can also be a callable,
  1597. in which case it's invoked when the default is needed
  1598. without any arguments.
  1599. :param callback: A function to further process or validate the value
  1600. after type conversion. It is called as ``f(ctx, param, value)``
  1601. and must return the value. It is called for all sources,
  1602. including prompts.
  1603. :param nargs: the number of arguments to match. If not ``1`` the return
  1604. value is a tuple instead of single value. The default for
  1605. nargs is ``1`` (except if the type is a tuple, then it's
  1606. the arity of the tuple). If ``nargs=-1``, all remaining
  1607. parameters are collected.
  1608. :param metavar: how the value is represented in the help page.
  1609. :param expose_value: if this is `True` then the value is passed onwards
  1610. to the command callback and stored on the context,
  1611. otherwise it's skipped.
  1612. :param is_eager: eager values are processed before non eager ones. This
  1613. should not be set for arguments or it will inverse the
  1614. order of processing.
  1615. :param envvar: a string or list of strings that are environment variables
  1616. that should be checked.
  1617. :param shell_complete: A function that returns custom shell
  1618. completions. Used instead of the param's type completion if
  1619. given. Takes ``ctx, param, incomplete`` and must return a list
  1620. of :class:`~click.shell_completion.CompletionItem` or a list of
  1621. strings.
  1622. .. versionchanged:: 8.0
  1623. ``process_value`` validates required parameters and bounded
  1624. ``nargs``, and invokes the parameter callback before returning
  1625. the value. This allows the callback to validate prompts.
  1626. ``full_process_value`` is removed.
  1627. .. versionchanged:: 8.0
  1628. ``autocompletion`` is renamed to ``shell_complete`` and has new
  1629. semantics described above. The old name is deprecated and will
  1630. be removed in 8.1, until then it will be wrapped to match the
  1631. new requirements.
  1632. .. versionchanged:: 8.0
  1633. For ``multiple=True, nargs>1``, the default must be a list of
  1634. tuples.
  1635. .. versionchanged:: 8.0
  1636. Setting a default is no longer required for ``nargs>1``, it will
  1637. default to ``None``. ``multiple=True`` or ``nargs=-1`` will
  1638. default to ``()``.
  1639. .. versionchanged:: 7.1
  1640. Empty environment variables are ignored rather than taking the
  1641. empty string value. This makes it possible for scripts to clear
  1642. variables if they can't unset them.
  1643. .. versionchanged:: 2.0
  1644. Changed signature for parameter callback to also be passed the
  1645. parameter. The old callback format will still work, but it will
  1646. raise a warning to give you a chance to migrate the code easier.
  1647. """
  1648. param_type_name = "parameter"
  1649. def __init__(
  1650. self,
  1651. param_decls: t.Optional[t.Sequence[str]] = None,
  1652. type: t.Optional[t.Union[types.ParamType, t.Any]] = None,
  1653. required: bool = False,
  1654. default: t.Optional[t.Union[t.Any, t.Callable[[], t.Any]]] = None,
  1655. callback: t.Optional[t.Callable[[Context, "Parameter", t.Any], t.Any]] = None,
  1656. nargs: t.Optional[int] = None,
  1657. multiple: bool = False,
  1658. metavar: t.Optional[str] = None,
  1659. expose_value: bool = True,
  1660. is_eager: bool = False,
  1661. envvar: t.Optional[t.Union[str, t.Sequence[str]]] = None,
  1662. shell_complete: t.Optional[
  1663. t.Callable[
  1664. [Context, "Parameter", str],
  1665. t.Union[t.List["CompletionItem"], t.List[str]],
  1666. ]
  1667. ] = None,
  1668. autocompletion: t.Optional[
  1669. t.Callable[
  1670. [Context, t.List[str], str], t.List[t.Union[t.Tuple[str, str], str]]
  1671. ]
  1672. ] = None,
  1673. ) -> None:
  1674. self.name, self.opts, self.secondary_opts = self._parse_decls(
  1675. param_decls or (), expose_value
  1676. )
  1677. self.type = types.convert_type(type, default)
  1678. # Default nargs to what the type tells us if we have that
  1679. # information available.
  1680. if nargs is None:
  1681. if self.type.is_composite:
  1682. nargs = self.type.arity
  1683. else:
  1684. nargs = 1
  1685. self.required = required
  1686. self.callback = callback
  1687. self.nargs = nargs
  1688. self.multiple = multiple
  1689. self.expose_value = expose_value
  1690. self.default = default
  1691. self.is_eager = is_eager
  1692. self.metavar = metavar
  1693. self.envvar = envvar
  1694. if autocompletion is not None:
  1695. import warnings
  1696. warnings.warn(
  1697. "'autocompletion' is renamed to 'shell_complete'. The old name is"
  1698. " deprecated and will be removed in Click 8.1. See the docs about"
  1699. " 'Parameter' for information about new behavior.",
  1700. DeprecationWarning,
  1701. stacklevel=2,
  1702. )
  1703. def shell_complete(
  1704. ctx: Context, param: "Parameter", incomplete: str
  1705. ) -> t.List["CompletionItem"]:
  1706. from click.shell_completion import CompletionItem
  1707. out = []
  1708. for c in autocompletion(ctx, [], incomplete): # type: ignore
  1709. if isinstance(c, tuple):
  1710. c = CompletionItem(c[0], help=c[1])
  1711. elif isinstance(c, str):
  1712. c = CompletionItem(c)
  1713. if c.value.startswith(incomplete):
  1714. out.append(c)
  1715. return out
  1716. self._custom_shell_complete = shell_complete
  1717. if __debug__:
  1718. if self.type.is_composite and nargs != self.type.arity:
  1719. raise ValueError(
  1720. f"'nargs' must be {self.type.arity} (or None) for"
  1721. f" type {self.type!r}, but it was {nargs}."
  1722. )
  1723. # Skip no default or callable default.
  1724. check_default = default if not callable(default) else None
  1725. if check_default is not None:
  1726. if multiple:
  1727. try:
  1728. # Only check the first value against nargs.
  1729. check_default = next(_check_iter(check_default), None)
  1730. except TypeError:
  1731. raise ValueError(
  1732. "'default' must be a list when 'multiple' is true."
  1733. ) from None
  1734. # Can be None for multiple with empty default.
  1735. if nargs != 1 and check_default is not None:
  1736. try:
  1737. _check_iter(check_default)
  1738. except TypeError:
  1739. if multiple:
  1740. message = (
  1741. "'default' must be a list of lists when 'multiple' is"
  1742. " true and 'nargs' != 1."
  1743. )
  1744. else:
  1745. message = "'default' must be a list when 'nargs' != 1."
  1746. raise ValueError(message) from None
  1747. if nargs > 1 and len(check_default) != nargs:
  1748. subject = "item length" if multiple else "length"
  1749. raise ValueError(
  1750. f"'default' {subject} must match nargs={nargs}."
  1751. )
  1752. def to_info_dict(self) -> t.Dict[str, t.Any]:
  1753. """Gather information that could be useful for a tool generating
  1754. user-facing documentation.
  1755. Use :meth:`click.Context.to_info_dict` to traverse the entire
  1756. CLI structure.
  1757. .. versionadded:: 8.0
  1758. """
  1759. return {
  1760. "name": self.name,
  1761. "param_type_name": self.param_type_name,
  1762. "opts": self.opts,
  1763. "secondary_opts": self.secondary_opts,
  1764. "type": self.type.to_info_dict(),
  1765. "required": self.required,
  1766. "nargs": self.nargs,
  1767. "multiple": self.multiple,
  1768. "default": self.default,
  1769. "envvar": self.envvar,
  1770. }
  1771. def __repr__(self) -> str:
  1772. return f"<{self.__class__.__name__} {self.name}>"
  1773. def _parse_decls(
  1774. self, decls: t.Sequence[str], expose_value: bool
  1775. ) -> t.Tuple[t.Optional[str], t.List[str], t.List[str]]:
  1776. raise NotImplementedError()
  1777. @property
  1778. def human_readable_name(self) -> str:
  1779. """Returns the human readable name of this parameter. This is the
  1780. same as the name for options, but the metavar for arguments.
  1781. """
  1782. return self.name # type: ignore
  1783. def make_metavar(self) -> str:
  1784. if self.metavar is not None:
  1785. return self.metavar
  1786. metavar = self.type.get_metavar(self)
  1787. if metavar is None:
  1788. metavar = self.type.name.upper()
  1789. if self.nargs != 1:
  1790. metavar += "..."
  1791. return metavar
  1792. @typing.overload
  1793. def get_default(
  1794. self, ctx: Context, call: "te.Literal[True]" = True
  1795. ) -> t.Optional[t.Any]:
  1796. ...
  1797. @typing.overload
  1798. def get_default(
  1799. self, ctx: Context, call: bool = ...
  1800. ) -> t.Optional[t.Union[t.Any, t.Callable[[], t.Any]]]:
  1801. ...
  1802. def get_default(
  1803. self, ctx: Context, call: bool = True
  1804. ) -> t.Optional[t.Union[t.Any, t.Callable[[], t.Any]]]:
  1805. """Get the default for the parameter. Tries
  1806. :meth:`Context.lookup_value` first, then the local default.
  1807. :param ctx: Current context.
  1808. :param call: If the default is a callable, call it. Disable to
  1809. return the callable instead.
  1810. .. versionchanged:: 8.0.1
  1811. Type casting can fail in resilient parsing mode. Invalid
  1812. defaults will not prevent showing help text.
  1813. .. versionchanged:: 8.0
  1814. Looks at ``ctx.default_map`` first.
  1815. .. versionchanged:: 8.0
  1816. Added the ``call`` parameter.
  1817. """
  1818. value = ctx.lookup_default(self.name, call=False) # type: ignore
  1819. if value is None:
  1820. value = self.default
  1821. if callable(value):
  1822. if not call:
  1823. # Don't type cast the callable.
  1824. return value
  1825. value = value()
  1826. try:
  1827. return self.type_cast_value(ctx, value)
  1828. except BadParameter:
  1829. if ctx.resilient_parsing:
  1830. return value
  1831. raise
  1832. def add_to_parser(self, parser: OptionParser, ctx: Context) -> None:
  1833. raise NotImplementedError()
  1834. def consume_value(
  1835. self, ctx: Context, opts: t.Mapping[str, t.Any]
  1836. ) -> t.Tuple[t.Any, ParameterSource]:
  1837. value = opts.get(self.name) # type: ignore
  1838. source = ParameterSource.COMMANDLINE
  1839. if value is None:
  1840. value = self.value_from_envvar(ctx)
  1841. source = ParameterSource.ENVIRONMENT
  1842. if value is None:
  1843. value = ctx.lookup_default(self.name) # type: ignore
  1844. source = ParameterSource.DEFAULT_MAP
  1845. if value is None:
  1846. value = self.get_default(ctx)
  1847. source = ParameterSource.DEFAULT
  1848. return value, source
  1849. def type_cast_value(self, ctx: Context, value: t.Any) -> t.Any:
  1850. """Convert and validate a value against the option's
  1851. :attr:`type`, :attr:`multiple`, and :attr:`nargs`.
  1852. """
  1853. if value is None:
  1854. return () if self.multiple or self.nargs == -1 else None
  1855. def check_iter(value: t.Any) -> t.Iterator:
  1856. try:
  1857. return _check_iter(value)
  1858. except TypeError:
  1859. # This should only happen when passing in args manually,
  1860. # the parser should construct an iterable when parsing
  1861. # the command line.
  1862. raise BadParameter(
  1863. _("Value must be an iterable."), ctx=ctx, param=self
  1864. ) from None
  1865. if self.nargs == 1 or self.type.is_composite:
  1866. convert: t.Callable[[t.Any], t.Any] = partial(
  1867. self.type, param=self, ctx=ctx
  1868. )
  1869. elif self.nargs == -1:
  1870. def convert(value: t.Any) -> t.Tuple:
  1871. return tuple(self.type(x, self, ctx) for x in check_iter(value))
  1872. else: # nargs > 1
  1873. def convert(value: t.Any) -> t.Tuple:
  1874. value = tuple(check_iter(value))
  1875. if len(value) != self.nargs:
  1876. raise BadParameter(
  1877. ngettext(
  1878. "Takes {nargs} values but 1 was given.",
  1879. "Takes {nargs} values but {len} were given.",
  1880. len(value),
  1881. ).format(nargs=self.nargs, len=len(value)),
  1882. ctx=ctx,
  1883. param=self,
  1884. )
  1885. return tuple(self.type(x, self, ctx) for x in value)
  1886. if self.multiple:
  1887. return tuple(convert(x) for x in check_iter(value))
  1888. return convert(value)
  1889. def value_is_missing(self, value: t.Any) -> bool:
  1890. if value is None:
  1891. return True
  1892. if (self.nargs != 1 or self.multiple) and value == ():
  1893. return True
  1894. return False
  1895. def process_value(self, ctx: Context, value: t.Any) -> t.Any:
  1896. if value is not None:
  1897. value = self.type_cast_value(ctx, value)
  1898. if self.required and self.value_is_missing(value):
  1899. raise MissingParameter(ctx=ctx, param=self)
  1900. if self.callback is not None:
  1901. value = self.callback(ctx, self, value)
  1902. return value
  1903. def resolve_envvar_value(self, ctx: Context) -> t.Optional[str]:
  1904. if self.envvar is None:
  1905. return None
  1906. if isinstance(self.envvar, str):
  1907. rv = os.environ.get(self.envvar)
  1908. if rv:
  1909. return rv
  1910. else:
  1911. for envvar in self.envvar:
  1912. rv = os.environ.get(envvar)
  1913. if rv:
  1914. return rv
  1915. return None
  1916. def value_from_envvar(self, ctx: Context) -> t.Optional[t.Any]:
  1917. rv: t.Optional[t.Any] = self.resolve_envvar_value(ctx)
  1918. if rv is not None and self.nargs != 1:
  1919. rv = self.type.split_envvar_value(rv)
  1920. return rv
  1921. def handle_parse_result(
  1922. self, ctx: Context, opts: t.Mapping[str, t.Any], args: t.List[str]
  1923. ) -> t.Tuple[t.Any, t.List[str]]:
  1924. with augment_usage_errors(ctx, param=self):
  1925. value, source = self.consume_value(ctx, opts)
  1926. ctx.set_parameter_source(self.name, source) # type: ignore
  1927. try:
  1928. value = self.process_value(ctx, value)
  1929. except Exception:
  1930. if not ctx.resilient_parsing:
  1931. raise
  1932. value = None
  1933. if self.expose_value:
  1934. ctx.params[self.name] = value # type: ignore
  1935. return value, args
  1936. def get_help_record(self, ctx: Context) -> t.Optional[t.Tuple[str, str]]:
  1937. pass
  1938. def get_usage_pieces(self, ctx: Context) -> t.List[str]:
  1939. return []
  1940. def get_error_hint(self, ctx: Context) -> str:
  1941. """Get a stringified version of the param for use in error messages to
  1942. indicate which param caused the error.
  1943. """
  1944. hint_list = self.opts or [self.human_readable_name]
  1945. return " / ".join(f"'{x}'" for x in hint_list)
  1946. def shell_complete(self, ctx: Context, incomplete: str) -> t.List["CompletionItem"]:
  1947. """Return a list of completions for the incomplete value. If a
  1948. ``shell_complete`` function was given during init, it is used.
  1949. Otherwise, the :attr:`type`
  1950. :meth:`~click.types.ParamType.shell_complete` function is used.
  1951. :param ctx: Invocation context for this command.
  1952. :param incomplete: Value being completed. May be empty.
  1953. .. versionadded:: 8.0
  1954. """
  1955. if self._custom_shell_complete is not None:
  1956. results = self._custom_shell_complete(ctx, self, incomplete)
  1957. if results and isinstance(results[0], str):
  1958. from click.shell_completion import CompletionItem
  1959. results = [CompletionItem(c) for c in results]
  1960. return t.cast(t.List["CompletionItem"], results)
  1961. return self.type.shell_complete(ctx, self, incomplete)
  1962. class Option(Parameter):
  1963. """Options are usually optional values on the command line and
  1964. have some extra features that arguments don't have.
  1965. All other parameters are passed onwards to the parameter constructor.
  1966. :param show_default: controls if the default value should be shown on the
  1967. help page. Normally, defaults are not shown. If this
  1968. value is a string, it shows the string instead of the
  1969. value. This is particularly useful for dynamic options.
  1970. :param show_envvar: controls if an environment variable should be shown on
  1971. the help page. Normally, environment variables
  1972. are not shown.
  1973. :param prompt: if set to `True` or a non empty string then the user will be
  1974. prompted for input. If set to `True` the prompt will be the
  1975. option name capitalized.
  1976. :param confirmation_prompt: Prompt a second time to confirm the
  1977. value if it was prompted for. Can be set to a string instead of
  1978. ``True`` to customize the message.
  1979. :param prompt_required: If set to ``False``, the user will be
  1980. prompted for input only when the option was specified as a flag
  1981. without a value.
  1982. :param hide_input: if this is `True` then the input on the prompt will be
  1983. hidden from the user. This is useful for password
  1984. input.
  1985. :param is_flag: forces this option to act as a flag. The default is
  1986. auto detection.
  1987. :param flag_value: which value should be used for this flag if it's
  1988. enabled. This is set to a boolean automatically if
  1989. the option string contains a slash to mark two options.
  1990. :param multiple: if this is set to `True` then the argument is accepted
  1991. multiple times and recorded. This is similar to ``nargs``
  1992. in how it works but supports arbitrary number of
  1993. arguments.
  1994. :param count: this flag makes an option increment an integer.
  1995. :param allow_from_autoenv: if this is enabled then the value of this
  1996. parameter will be pulled from an environment
  1997. variable in case a prefix is defined on the
  1998. context.
  1999. :param help: the help string.
  2000. :param hidden: hide this option from help outputs.
  2001. .. versionchanged:: 8.0.1
  2002. ``type`` is detected from ``flag_value`` if given.
  2003. """
  2004. param_type_name = "option"
  2005. def __init__(
  2006. self,
  2007. param_decls: t.Optional[t.Sequence[str]] = None,
  2008. show_default: bool = False,
  2009. prompt: t.Union[bool, str] = False,
  2010. confirmation_prompt: t.Union[bool, str] = False,
  2011. prompt_required: bool = True,
  2012. hide_input: bool = False,
  2013. is_flag: t.Optional[bool] = None,
  2014. flag_value: t.Optional[t.Any] = None,
  2015. multiple: bool = False,
  2016. count: bool = False,
  2017. allow_from_autoenv: bool = True,
  2018. type: t.Optional[t.Union[types.ParamType, t.Any]] = None,
  2019. help: t.Optional[str] = None,
  2020. hidden: bool = False,
  2021. show_choices: bool = True,
  2022. show_envvar: bool = False,
  2023. **attrs: t.Any,
  2024. ) -> None:
  2025. default_is_missing = "default" not in attrs
  2026. super().__init__(param_decls, type=type, multiple=multiple, **attrs)
  2027. if prompt is True:
  2028. if self.name is None:
  2029. raise TypeError("'name' is required with 'prompt=True'.")
  2030. prompt_text: t.Optional[str] = self.name.replace("_", " ").capitalize()
  2031. elif prompt is False:
  2032. prompt_text = None
  2033. else:
  2034. prompt_text = t.cast(str, prompt)
  2035. self.prompt = prompt_text
  2036. self.confirmation_prompt = confirmation_prompt
  2037. self.prompt_required = prompt_required
  2038. self.hide_input = hide_input
  2039. self.hidden = hidden
  2040. # If prompt is enabled but not required, then the option can be
  2041. # used as a flag to indicate using prompt or flag_value.
  2042. self._flag_needs_value = self.prompt is not None and not self.prompt_required
  2043. if is_flag is None:
  2044. if flag_value is not None:
  2045. # Implicitly a flag because flag_value was set.
  2046. is_flag = True
  2047. elif self._flag_needs_value:
  2048. # Not a flag, but when used as a flag it shows a prompt.
  2049. is_flag = False
  2050. else:
  2051. # Implicitly a flag because flag options were given.
  2052. is_flag = bool(self.secondary_opts)
  2053. elif is_flag is False and not self._flag_needs_value:
  2054. # Not a flag, and prompt is not enabled, can be used as a
  2055. # flag if flag_value is set.
  2056. self._flag_needs_value = flag_value is not None
  2057. if is_flag and default_is_missing:
  2058. self.default: t.Union[t.Any, t.Callable[[], t.Any]] = False
  2059. if flag_value is None:
  2060. flag_value = not self.default
  2061. if is_flag and type is None:
  2062. # Re-guess the type from the flag value instead of the
  2063. # default.
  2064. self.type = types.convert_type(None, flag_value)
  2065. self.is_flag: bool = is_flag
  2066. self.is_bool_flag = isinstance(self.type, types.BoolParamType)
  2067. self.flag_value: t.Any = flag_value
  2068. # Counting
  2069. self.count = count
  2070. if count:
  2071. if type is None:
  2072. self.type = types.IntRange(min=0)
  2073. if default_is_missing:
  2074. self.default = 0
  2075. self.allow_from_autoenv = allow_from_autoenv
  2076. self.help = help
  2077. self.show_default = show_default
  2078. self.show_choices = show_choices
  2079. self.show_envvar = show_envvar
  2080. if __debug__:
  2081. if self.nargs == -1:
  2082. raise TypeError("nargs=-1 is not supported for options.")
  2083. if self.prompt and self.is_flag and not self.is_bool_flag:
  2084. raise TypeError("'prompt' is not valid for non-boolean flag.")
  2085. if not self.is_bool_flag and self.secondary_opts:
  2086. raise TypeError("Secondary flag is not valid for non-boolean flag.")
  2087. if self.is_bool_flag and self.hide_input and self.prompt is not None:
  2088. raise TypeError(
  2089. "'prompt' with 'hide_input' is not valid for boolean flag."
  2090. )
  2091. if self.count:
  2092. if self.multiple:
  2093. raise TypeError("'count' is not valid with 'multiple'.")
  2094. if self.is_flag:
  2095. raise TypeError("'count' is not valid with 'is_flag'.")
  2096. def to_info_dict(self) -> t.Dict[str, t.Any]:
  2097. info_dict = super().to_info_dict()
  2098. info_dict.update(
  2099. help=self.help,
  2100. prompt=self.prompt,
  2101. is_flag=self.is_flag,
  2102. flag_value=self.flag_value,
  2103. count=self.count,
  2104. hidden=self.hidden,
  2105. )
  2106. return info_dict
  2107. def _parse_decls(
  2108. self, decls: t.Sequence[str], expose_value: bool
  2109. ) -> t.Tuple[t.Optional[str], t.List[str], t.List[str]]:
  2110. opts = []
  2111. secondary_opts = []
  2112. name = None
  2113. possible_names = []
  2114. for decl in decls:
  2115. if decl.isidentifier():
  2116. if name is not None:
  2117. raise TypeError("Name defined twice")
  2118. name = decl
  2119. else:
  2120. split_char = ";" if decl[:1] == "/" else "/"
  2121. if split_char in decl:
  2122. first, second = decl.split(split_char, 1)
  2123. first = first.rstrip()
  2124. if first:
  2125. possible_names.append(split_opt(first))
  2126. opts.append(first)
  2127. second = second.lstrip()
  2128. if second:
  2129. secondary_opts.append(second.lstrip())
  2130. if first == second:
  2131. raise ValueError(
  2132. f"Boolean option {decl!r} cannot use the"
  2133. " same flag for true/false."
  2134. )
  2135. else:
  2136. possible_names.append(split_opt(decl))
  2137. opts.append(decl)
  2138. if name is None and possible_names:
  2139. possible_names.sort(key=lambda x: -len(x[0])) # group long options first
  2140. name = possible_names[0][1].replace("-", "_").lower()
  2141. if not name.isidentifier():
  2142. name = None
  2143. if name is None:
  2144. if not expose_value:
  2145. return None, opts, secondary_opts
  2146. raise TypeError("Could not determine name for option")
  2147. if not opts and not secondary_opts:
  2148. raise TypeError(
  2149. f"No options defined but a name was passed ({name})."
  2150. " Did you mean to declare an argument instead? Did"
  2151. f" you mean to pass '--{name}'?"
  2152. )
  2153. return name, opts, secondary_opts
  2154. def add_to_parser(self, parser: OptionParser, ctx: Context) -> None:
  2155. if self.multiple:
  2156. action = "append"
  2157. elif self.count:
  2158. action = "count"
  2159. else:
  2160. action = "store"
  2161. if self.is_flag:
  2162. action = f"{action}_const"
  2163. if self.is_bool_flag and self.secondary_opts:
  2164. parser.add_option(
  2165. obj=self, opts=self.opts, dest=self.name, action=action, const=True
  2166. )
  2167. parser.add_option(
  2168. obj=self,
  2169. opts=self.secondary_opts,
  2170. dest=self.name,
  2171. action=action,
  2172. const=False,
  2173. )
  2174. else:
  2175. parser.add_option(
  2176. obj=self,
  2177. opts=self.opts,
  2178. dest=self.name,
  2179. action=action,
  2180. const=self.flag_value,
  2181. )
  2182. else:
  2183. parser.add_option(
  2184. obj=self,
  2185. opts=self.opts,
  2186. dest=self.name,
  2187. action=action,
  2188. nargs=self.nargs,
  2189. )
  2190. def get_help_record(self, ctx: Context) -> t.Optional[t.Tuple[str, str]]:
  2191. if self.hidden:
  2192. return None
  2193. any_prefix_is_slash = False
  2194. def _write_opts(opts: t.Sequence[str]) -> str:
  2195. nonlocal any_prefix_is_slash
  2196. rv, any_slashes = join_options(opts)
  2197. if any_slashes:
  2198. any_prefix_is_slash = True
  2199. if not self.is_flag and not self.count:
  2200. rv += f" {self.make_metavar()}"
  2201. return rv
  2202. rv = [_write_opts(self.opts)]
  2203. if self.secondary_opts:
  2204. rv.append(_write_opts(self.secondary_opts))
  2205. help = self.help or ""
  2206. extra = []
  2207. if self.show_envvar:
  2208. envvar = self.envvar
  2209. if envvar is None:
  2210. if (
  2211. self.allow_from_autoenv
  2212. and ctx.auto_envvar_prefix is not None
  2213. and self.name is not None
  2214. ):
  2215. envvar = f"{ctx.auto_envvar_prefix}_{self.name.upper()}"
  2216. if envvar is not None:
  2217. var_str = (
  2218. envvar
  2219. if isinstance(envvar, str)
  2220. else ", ".join(str(d) for d in envvar)
  2221. )
  2222. extra.append(_("env var: {var}").format(var=var_str))
  2223. # Temporarily enable resilient parsing to avoid type casting
  2224. # failing for the default. Might be possible to extend this to
  2225. # help formatting in general.
  2226. resilient = ctx.resilient_parsing
  2227. ctx.resilient_parsing = True
  2228. try:
  2229. default_value = self.get_default(ctx, call=False)
  2230. finally:
  2231. ctx.resilient_parsing = resilient
  2232. show_default_is_str = isinstance(self.show_default, str)
  2233. if show_default_is_str or (
  2234. default_value is not None and (self.show_default or ctx.show_default)
  2235. ):
  2236. if show_default_is_str:
  2237. default_string = f"({self.show_default})"
  2238. elif isinstance(default_value, (list, tuple)):
  2239. default_string = ", ".join(str(d) for d in default_value)
  2240. elif callable(default_value):
  2241. default_string = _("(dynamic)")
  2242. elif self.is_bool_flag and self.secondary_opts:
  2243. # For boolean flags that have distinct True/False opts,
  2244. # use the opt without prefix instead of the value.
  2245. default_string = split_opt(
  2246. (self.opts if self.default else self.secondary_opts)[0]
  2247. )[1]
  2248. else:
  2249. default_string = str(default_value)
  2250. extra.append(_("default: {default}").format(default=default_string))
  2251. if isinstance(self.type, types._NumberRangeBase):
  2252. range_str = self.type._describe_range()
  2253. if range_str:
  2254. extra.append(range_str)
  2255. if self.required:
  2256. extra.append(_("required"))
  2257. if extra:
  2258. extra_str = ";".join(extra)
  2259. help = f"{help} [{extra_str}]" if help else f"[{extra_str}]"
  2260. return ("; " if any_prefix_is_slash else " / ").join(rv), help
  2261. @typing.overload
  2262. def get_default(
  2263. self, ctx: Context, call: "te.Literal[True]" = True
  2264. ) -> t.Optional[t.Any]:
  2265. ...
  2266. @typing.overload
  2267. def get_default(
  2268. self, ctx: Context, call: bool = ...
  2269. ) -> t.Optional[t.Union[t.Any, t.Callable[[], t.Any]]]:
  2270. ...
  2271. def get_default(
  2272. self, ctx: Context, call: bool = True
  2273. ) -> t.Optional[t.Union[t.Any, t.Callable[[], t.Any]]]:
  2274. # If we're a non boolean flag our default is more complex because
  2275. # we need to look at all flags in the same group to figure out
  2276. # if we're the the default one in which case we return the flag
  2277. # value as default.
  2278. if self.is_flag and not self.is_bool_flag:
  2279. for param in ctx.command.params:
  2280. if param.name == self.name and param.default:
  2281. return param.flag_value # type: ignore
  2282. return None
  2283. return super().get_default(ctx, call=call)
  2284. def prompt_for_value(self, ctx: Context) -> t.Any:
  2285. """This is an alternative flow that can be activated in the full
  2286. value processing if a value does not exist. It will prompt the
  2287. user until a valid value exists and then returns the processed
  2288. value as result.
  2289. """
  2290. assert self.prompt is not None
  2291. # Calculate the default before prompting anything to be stable.
  2292. default = self.get_default(ctx)
  2293. # If this is a prompt for a flag we need to handle this
  2294. # differently.
  2295. if self.is_bool_flag:
  2296. return confirm(self.prompt, default)
  2297. return prompt(
  2298. self.prompt,
  2299. default=default,
  2300. type=self.type,
  2301. hide_input=self.hide_input,
  2302. show_choices=self.show_choices,
  2303. confirmation_prompt=self.confirmation_prompt,
  2304. value_proc=lambda x: self.process_value(ctx, x),
  2305. )
  2306. def resolve_envvar_value(self, ctx: Context) -> t.Optional[str]:
  2307. rv = super().resolve_envvar_value(ctx)
  2308. if rv is not None:
  2309. return rv
  2310. if (
  2311. self.allow_from_autoenv
  2312. and ctx.auto_envvar_prefix is not None
  2313. and self.name is not None
  2314. ):
  2315. envvar = f"{ctx.auto_envvar_prefix}_{self.name.upper()}"
  2316. rv = os.environ.get(envvar)
  2317. return rv
  2318. def value_from_envvar(self, ctx: Context) -> t.Optional[t.Any]:
  2319. rv: t.Optional[t.Any] = self.resolve_envvar_value(ctx)
  2320. if rv is None:
  2321. return None
  2322. value_depth = (self.nargs != 1) + bool(self.multiple)
  2323. if value_depth > 0:
  2324. rv = self.type.split_envvar_value(rv)
  2325. if self.multiple and self.nargs != 1:
  2326. rv = batch(rv, self.nargs)
  2327. return rv
  2328. def consume_value(
  2329. self, ctx: Context, opts: t.Mapping[str, "Parameter"]
  2330. ) -> t.Tuple[t.Any, ParameterSource]:
  2331. value, source = super().consume_value(ctx, opts)
  2332. # The parser will emit a sentinel value if the option can be
  2333. # given as a flag without a value. This is different from None
  2334. # to distinguish from the flag not being given at all.
  2335. if value is _flag_needs_value:
  2336. if self.prompt is not None and not ctx.resilient_parsing:
  2337. value = self.prompt_for_value(ctx)
  2338. source = ParameterSource.PROMPT
  2339. else:
  2340. value = self.flag_value
  2341. source = ParameterSource.COMMANDLINE
  2342. # The value wasn't set, or used the param's default, prompt if
  2343. # prompting is enabled.
  2344. elif (
  2345. source in {None, ParameterSource.DEFAULT}
  2346. and self.prompt is not None
  2347. and (self.required or self.prompt_required)
  2348. and not ctx.resilient_parsing
  2349. ):
  2350. value = self.prompt_for_value(ctx)
  2351. source = ParameterSource.PROMPT
  2352. return value, source
  2353. class Argument(Parameter):
  2354. """Arguments are positional parameters to a command. They generally
  2355. provide fewer features than options but can have infinite ``nargs``
  2356. and are required by default.
  2357. All parameters are passed onwards to the parameter constructor.
  2358. """
  2359. param_type_name = "argument"
  2360. def __init__(
  2361. self,
  2362. param_decls: t.Sequence[str],
  2363. required: t.Optional[bool] = None,
  2364. **attrs: t.Any,
  2365. ) -> None:
  2366. if required is None:
  2367. if attrs.get("default") is not None:
  2368. required = False
  2369. else:
  2370. required = attrs.get("nargs", 1) > 0
  2371. if "multiple" in attrs:
  2372. raise TypeError("__init__() got an unexpected keyword argument 'multiple'.")
  2373. super().__init__(param_decls, required=required, **attrs)
  2374. if __debug__:
  2375. if self.default is not None and self.nargs == -1:
  2376. raise TypeError("'default' is not supported for nargs=-1.")
  2377. @property
  2378. def human_readable_name(self) -> str:
  2379. if self.metavar is not None:
  2380. return self.metavar
  2381. return self.name.upper() # type: ignore
  2382. def make_metavar(self) -> str:
  2383. if self.metavar is not None:
  2384. return self.metavar
  2385. var = self.type.get_metavar(self)
  2386. if not var:
  2387. var = self.name.upper() # type: ignore
  2388. if not self.required:
  2389. var = f"[{var}]"
  2390. if self.nargs != 1:
  2391. var += "..."
  2392. return var
  2393. def _parse_decls(
  2394. self, decls: t.Sequence[str], expose_value: bool
  2395. ) -> t.Tuple[t.Optional[str], t.List[str], t.List[str]]:
  2396. if not decls:
  2397. if not expose_value:
  2398. return None, [], []
  2399. raise TypeError("Could not determine name for argument")
  2400. if len(decls) == 1:
  2401. name = arg = decls[0]
  2402. name = name.replace("-", "_").lower()
  2403. else:
  2404. raise TypeError(
  2405. "Arguments take exactly one parameter declaration, got"
  2406. f" {len(decls)}."
  2407. )
  2408. return name, [arg], []
  2409. def get_usage_pieces(self, ctx: Context) -> t.List[str]:
  2410. return [self.make_metavar()]
  2411. def get_error_hint(self, ctx: Context) -> str:
  2412. return f"'{self.make_metavar()}'"
  2413. def add_to_parser(self, parser: OptionParser, ctx: Context) -> None:
  2414. parser.add_argument(dest=self.name, nargs=self.nargs, obj=self)