Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/click/core.py: 32%
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1from __future__ import annotations
3import collections.abc as cabc
4import enum
5import errno
6import inspect
7import os
8import sys
9import typing as t
10from collections import abc
11from collections import Counter
12from contextlib import AbstractContextManager
13from contextlib import contextmanager
14from contextlib import ExitStack
15from functools import update_wrapper
16from gettext import gettext as _
17from gettext import ngettext
18from itertools import repeat
19from types import TracebackType
21from . import types
22from .exceptions import Abort
23from .exceptions import BadParameter
24from .exceptions import ClickException
25from .exceptions import Exit
26from .exceptions import MissingParameter
27from .exceptions import NoArgsIsHelpError
28from .exceptions import UsageError
29from .formatting import HelpFormatter
30from .formatting import join_options
31from .globals import pop_context
32from .globals import push_context
33from .parser import _flag_needs_value
34from .parser import _OptionParser
35from .parser import _split_opt
36from .termui import confirm
37from .termui import prompt
38from .termui import style
39from .utils import _detect_program_name
40from .utils import _expand_args
41from .utils import echo
42from .utils import make_default_short_help
43from .utils import make_str
44from .utils import PacifyFlushWrapper
46if t.TYPE_CHECKING:
47 from .shell_completion import CompletionItem
49F = t.TypeVar("F", bound="t.Callable[..., t.Any]")
50V = t.TypeVar("V")
53def _complete_visible_commands(
54 ctx: Context, incomplete: str
55) -> cabc.Iterator[tuple[str, Command]]:
56 """List all the subcommands of a group that start with the
57 incomplete value and aren't hidden.
59 :param ctx: Invocation context for the group.
60 :param incomplete: Value being completed. May be empty.
61 """
62 multi = t.cast(Group, ctx.command)
64 for name in multi.list_commands(ctx):
65 if name.startswith(incomplete):
66 command = multi.get_command(ctx, name)
68 if command is not None and not command.hidden:
69 yield name, command
72def _check_nested_chain(
73 base_command: Group, cmd_name: str, cmd: Command, register: bool = False
74) -> None:
75 if not base_command.chain or not isinstance(cmd, Group):
76 return
78 if register:
79 message = (
80 f"It is not possible to add the group {cmd_name!r} to another"
81 f" group {base_command.name!r} that is in chain mode."
82 )
83 else:
84 message = (
85 f"Found the group {cmd_name!r} as subcommand to another group "
86 f" {base_command.name!r} that is in chain mode. This is not supported."
87 )
89 raise RuntimeError(message)
92def batch(iterable: cabc.Iterable[V], batch_size: int) -> list[tuple[V, ...]]:
93 return list(zip(*repeat(iter(iterable), batch_size), strict=False))
96@contextmanager
97def augment_usage_errors(
98 ctx: Context, param: Parameter | None = None
99) -> cabc.Iterator[None]:
100 """Context manager that attaches extra information to exceptions."""
101 try:
102 yield
103 except BadParameter as e:
104 if e.ctx is None:
105 e.ctx = ctx
106 if param is not None and e.param is None:
107 e.param = param
108 raise
109 except UsageError as e:
110 if e.ctx is None:
111 e.ctx = ctx
112 raise
115def iter_params_for_processing(
116 invocation_order: cabc.Sequence[Parameter],
117 declaration_order: cabc.Sequence[Parameter],
118) -> list[Parameter]:
119 """Returns all declared parameters in the order they should be processed.
121 The declared parameters are re-shuffled depending on the order in which
122 they were invoked, as well as the eagerness of each parameters.
124 The invocation order takes precedence over the declaration order. I.e. the
125 order in which the user provided them to the CLI is respected.
127 This behavior and its effect on callback evaluation is detailed at:
128 https://click.palletsprojects.com/en/stable/advanced/#callback-evaluation-order
129 """
131 def sort_key(item: Parameter) -> tuple[bool, float]:
132 try:
133 idx: float = invocation_order.index(item)
134 except ValueError:
135 idx = float("inf")
137 return not item.is_eager, idx
139 return sorted(declaration_order, key=sort_key)
142class ParameterSource(enum.Enum):
143 """This is an :class:`~enum.Enum` that indicates the source of a
144 parameter's value.
146 Use :meth:`click.Context.get_parameter_source` to get the
147 source for a parameter by name.
149 .. versionchanged:: 8.0
150 Use :class:`~enum.Enum` and drop the ``validate`` method.
152 .. versionchanged:: 8.0
153 Added the ``PROMPT`` value.
154 """
156 COMMANDLINE = enum.auto()
157 """The value was provided by the command line args."""
158 ENVIRONMENT = enum.auto()
159 """The value was provided with an environment variable."""
160 DEFAULT = enum.auto()
161 """Used the default specified by the parameter."""
162 DEFAULT_MAP = enum.auto()
163 """Used a default provided by :attr:`Context.default_map`."""
164 PROMPT = enum.auto()
165 """Used a prompt to confirm a default or provide a value."""
168class Context:
169 """The context is a special internal object that holds state relevant
170 for the script execution at every single level. It's normally invisible
171 to commands unless they opt-in to getting access to it.
173 The context is useful as it can pass internal objects around and can
174 control special execution features such as reading data from
175 environment variables.
177 A context can be used as context manager in which case it will call
178 :meth:`close` on teardown.
180 :param command: the command class for this context.
181 :param parent: the parent context.
182 :param info_name: the info name for this invocation. Generally this
183 is the most descriptive name for the script or
184 command. For the toplevel script it is usually
185 the name of the script, for commands below it it's
186 the name of the script.
187 :param obj: an arbitrary object of user data.
188 :param auto_envvar_prefix: the prefix to use for automatic environment
189 variables. If this is `None` then reading
190 from environment variables is disabled. This
191 does not affect manually set environment
192 variables which are always read.
193 :param default_map: a dictionary (like object) with default values
194 for parameters.
195 :param terminal_width: the width of the terminal. The default is
196 inherit from parent context. If no context
197 defines the terminal width then auto
198 detection will be applied.
199 :param max_content_width: the maximum width for content rendered by
200 Click (this currently only affects help
201 pages). This defaults to 80 characters if
202 not overridden. In other words: even if the
203 terminal is larger than that, Click will not
204 format things wider than 80 characters by
205 default. In addition to that, formatters might
206 add some safety mapping on the right.
207 :param resilient_parsing: if this flag is enabled then Click will
208 parse without any interactivity or callback
209 invocation. Default values will also be
210 ignored. This is useful for implementing
211 things such as completion support.
212 :param allow_extra_args: if this is set to `True` then extra arguments
213 at the end will not raise an error and will be
214 kept on the context. The default is to inherit
215 from the command.
216 :param allow_interspersed_args: if this is set to `False` then options
217 and arguments cannot be mixed. The
218 default is to inherit from the command.
219 :param ignore_unknown_options: instructs click to ignore options it does
220 not know and keeps them for later
221 processing.
222 :param help_option_names: optionally a list of strings that define how
223 the default help parameter is named. The
224 default is ``['--help']``.
225 :param token_normalize_func: an optional function that is used to
226 normalize tokens (options, choices,
227 etc.). This for instance can be used to
228 implement case insensitive behavior.
229 :param color: controls if the terminal supports ANSI colors or not. The
230 default is autodetection. This is only needed if ANSI
231 codes are used in texts that Click prints which is by
232 default not the case. This for instance would affect
233 help output.
234 :param show_default: Show the default value for commands. If this
235 value is not set, it defaults to the value from the parent
236 context. ``Command.show_default`` overrides this default for the
237 specific command.
239 .. versionchanged:: 8.2
240 The ``protected_args`` attribute is deprecated and will be removed in
241 Click 9.0. ``args`` will contain remaining unparsed tokens.
243 .. versionchanged:: 8.1
244 The ``show_default`` parameter is overridden by
245 ``Command.show_default``, instead of the other way around.
247 .. versionchanged:: 8.0
248 The ``show_default`` parameter defaults to the value from the
249 parent context.
251 .. versionchanged:: 7.1
252 Added the ``show_default`` parameter.
254 .. versionchanged:: 4.0
255 Added the ``color``, ``ignore_unknown_options``, and
256 ``max_content_width`` parameters.
258 .. versionchanged:: 3.0
259 Added the ``allow_extra_args`` and ``allow_interspersed_args``
260 parameters.
262 .. versionchanged:: 2.0
263 Added the ``resilient_parsing``, ``help_option_names``, and
264 ``token_normalize_func`` parameters.
265 """
267 #: The formatter class to create with :meth:`make_formatter`.
268 #:
269 #: .. versionadded:: 8.0
270 formatter_class: type[HelpFormatter] = HelpFormatter
272 def __init__(
273 self,
274 command: Command,
275 parent: Context | None = None,
276 info_name: str | None = None,
277 obj: t.Any | None = None,
278 auto_envvar_prefix: str | None = None,
279 default_map: cabc.MutableMapping[str, t.Any] | None = None,
280 terminal_width: int | None = None,
281 max_content_width: int | None = None,
282 resilient_parsing: bool = False,
283 allow_extra_args: bool | None = None,
284 allow_interspersed_args: bool | None = None,
285 ignore_unknown_options: bool | None = None,
286 help_option_names: list[str] | None = None,
287 token_normalize_func: t.Callable[[str], str] | None = None,
288 color: bool | None = None,
289 show_default: bool | None = None,
290 ) -> None:
291 #: the parent context or `None` if none exists.
292 self.parent = parent
293 #: the :class:`Command` for this context.
294 self.command = command
295 #: the descriptive information name
296 self.info_name = info_name
297 #: Map of parameter names to their parsed values. Parameters
298 #: with ``expose_value=False`` are not stored.
299 self.params: dict[str, t.Any] = {}
300 #: the leftover arguments.
301 self.args: list[str] = []
302 #: protected arguments. These are arguments that are prepended
303 #: to `args` when certain parsing scenarios are encountered but
304 #: must be never propagated to another arguments. This is used
305 #: to implement nested parsing.
306 self._protected_args: list[str] = []
307 #: the collected prefixes of the command's options.
308 self._opt_prefixes: set[str] = set(parent._opt_prefixes) if parent else set()
310 if obj is None and parent is not None:
311 obj = parent.obj
313 #: the user object stored.
314 self.obj: t.Any = obj
315 self._meta: dict[str, t.Any] = getattr(parent, "meta", {})
317 #: A dictionary (-like object) with defaults for parameters.
318 if (
319 default_map is None
320 and info_name is not None
321 and parent is not None
322 and parent.default_map is not None
323 ):
324 default_map = parent.default_map.get(info_name)
326 self.default_map: cabc.MutableMapping[str, t.Any] | None = default_map
328 #: This flag indicates if a subcommand is going to be executed. A
329 #: group callback can use this information to figure out if it's
330 #: being executed directly or because the execution flow passes
331 #: onwards to a subcommand. By default it's None, but it can be
332 #: the name of the subcommand to execute.
333 #:
334 #: If chaining is enabled this will be set to ``'*'`` in case
335 #: any commands are executed. It is however not possible to
336 #: figure out which ones. If you require this knowledge you
337 #: should use a :func:`result_callback`.
338 self.invoked_subcommand: str | None = None
340 if terminal_width is None and parent is not None:
341 terminal_width = parent.terminal_width
343 #: The width of the terminal (None is autodetection).
344 self.terminal_width: int | None = terminal_width
346 if max_content_width is None and parent is not None:
347 max_content_width = parent.max_content_width
349 #: The maximum width of formatted content (None implies a sensible
350 #: default which is 80 for most things).
351 self.max_content_width: int | None = max_content_width
353 if allow_extra_args is None:
354 allow_extra_args = command.allow_extra_args
356 #: Indicates if the context allows extra args or if it should
357 #: fail on parsing.
358 #:
359 #: .. versionadded:: 3.0
360 self.allow_extra_args = allow_extra_args
362 if allow_interspersed_args is None:
363 allow_interspersed_args = command.allow_interspersed_args
365 #: Indicates if the context allows mixing of arguments and
366 #: options or not.
367 #:
368 #: .. versionadded:: 3.0
369 self.allow_interspersed_args: bool = allow_interspersed_args
371 if ignore_unknown_options is None:
372 ignore_unknown_options = command.ignore_unknown_options
374 #: Instructs click to ignore options that a command does not
375 #: understand and will store it on the context for later
376 #: processing. This is primarily useful for situations where you
377 #: want to call into external programs. Generally this pattern is
378 #: strongly discouraged because it's not possibly to losslessly
379 #: forward all arguments.
380 #:
381 #: .. versionadded:: 4.0
382 self.ignore_unknown_options: bool = ignore_unknown_options
384 if help_option_names is None:
385 if parent is not None:
386 help_option_names = parent.help_option_names
387 else:
388 help_option_names = ["--help"]
390 #: The names for the help options.
391 self.help_option_names: list[str] = help_option_names
393 if token_normalize_func is None and parent is not None:
394 token_normalize_func = parent.token_normalize_func
396 #: An optional normalization function for tokens. This is
397 #: options, choices, commands etc.
398 self.token_normalize_func: t.Callable[[str], str] | None = token_normalize_func
400 #: Indicates if resilient parsing is enabled. In that case Click
401 #: will do its best to not cause any failures and default values
402 #: will be ignored. Useful for completion.
403 self.resilient_parsing: bool = resilient_parsing
405 # If there is no envvar prefix yet, but the parent has one and
406 # the command on this level has a name, we can expand the envvar
407 # prefix automatically.
408 if auto_envvar_prefix is None:
409 if (
410 parent is not None
411 and parent.auto_envvar_prefix is not None
412 and self.info_name is not None
413 ):
414 auto_envvar_prefix = (
415 f"{parent.auto_envvar_prefix}_{self.info_name.upper()}"
416 )
417 else:
418 auto_envvar_prefix = auto_envvar_prefix.upper()
420 if auto_envvar_prefix is not None:
421 auto_envvar_prefix = auto_envvar_prefix.replace("-", "_")
423 self.auto_envvar_prefix: str | None = auto_envvar_prefix
425 if color is None and parent is not None:
426 color = parent.color
428 #: Controls if styling output is wanted or not.
429 self.color: bool | None = color
431 if show_default is None and parent is not None:
432 show_default = parent.show_default
434 #: Show option default values when formatting help text.
435 self.show_default: bool | None = show_default
437 self._close_callbacks: list[t.Callable[[], t.Any]] = []
438 self._depth = 0
439 self._parameter_source: dict[str, ParameterSource] = {}
440 self._exit_stack = ExitStack()
442 @property
443 def protected_args(self) -> list[str]:
444 import warnings
446 warnings.warn(
447 "'protected_args' is deprecated and will be removed in Click 9.0."
448 " 'args' will contain remaining unparsed tokens.",
449 DeprecationWarning,
450 stacklevel=2,
451 )
452 return self._protected_args
454 def to_info_dict(self) -> dict[str, t.Any]:
455 """Gather information that could be useful for a tool generating
456 user-facing documentation. This traverses the entire CLI
457 structure.
459 .. code-block:: python
461 with Context(cli) as ctx:
462 info = ctx.to_info_dict()
464 .. versionadded:: 8.0
465 """
466 return {
467 "command": self.command.to_info_dict(self),
468 "info_name": self.info_name,
469 "allow_extra_args": self.allow_extra_args,
470 "allow_interspersed_args": self.allow_interspersed_args,
471 "ignore_unknown_options": self.ignore_unknown_options,
472 "auto_envvar_prefix": self.auto_envvar_prefix,
473 }
475 def __enter__(self) -> Context:
476 self._depth += 1
477 push_context(self)
478 return self
480 def __exit__(
481 self,
482 exc_type: type[BaseException] | None,
483 exc_value: BaseException | None,
484 tb: TracebackType | None,
485 ) -> None:
486 self._depth -= 1
487 if self._depth == 0:
488 self.close()
489 pop_context()
491 @contextmanager
492 def scope(self, cleanup: bool = True) -> cabc.Iterator[Context]:
493 """This helper method can be used with the context object to promote
494 it to the current thread local (see :func:`get_current_context`).
495 The default behavior of this is to invoke the cleanup functions which
496 can be disabled by setting `cleanup` to `False`. The cleanup
497 functions are typically used for things such as closing file handles.
499 If the cleanup is intended the context object can also be directly
500 used as a context manager.
502 Example usage::
504 with ctx.scope():
505 assert get_current_context() is ctx
507 This is equivalent::
509 with ctx:
510 assert get_current_context() is ctx
512 .. versionadded:: 5.0
514 :param cleanup: controls if the cleanup functions should be run or
515 not. The default is to run these functions. In
516 some situations the context only wants to be
517 temporarily pushed in which case this can be disabled.
518 Nested pushes automatically defer the cleanup.
519 """
520 if not cleanup:
521 self._depth += 1
522 try:
523 with self as rv:
524 yield rv
525 finally:
526 if not cleanup:
527 self._depth -= 1
529 @property
530 def meta(self) -> dict[str, t.Any]:
531 """This is a dictionary which is shared with all the contexts
532 that are nested. It exists so that click utilities can store some
533 state here if they need to. It is however the responsibility of
534 that code to manage this dictionary well.
536 The keys are supposed to be unique dotted strings. For instance
537 module paths are a good choice for it. What is stored in there is
538 irrelevant for the operation of click. However what is important is
539 that code that places data here adheres to the general semantics of
540 the system.
542 Example usage::
544 LANG_KEY = f'{__name__}.lang'
546 def set_language(value):
547 ctx = get_current_context()
548 ctx.meta[LANG_KEY] = value
550 def get_language():
551 return get_current_context().meta.get(LANG_KEY, 'en_US')
553 .. versionadded:: 5.0
554 """
555 return self._meta
557 def make_formatter(self) -> HelpFormatter:
558 """Creates the :class:`~click.HelpFormatter` for the help and
559 usage output.
561 To quickly customize the formatter class used without overriding
562 this method, set the :attr:`formatter_class` attribute.
564 .. versionchanged:: 8.0
565 Added the :attr:`formatter_class` attribute.
566 """
567 return self.formatter_class(
568 width=self.terminal_width, max_width=self.max_content_width
569 )
571 def with_resource(self, context_manager: AbstractContextManager[V]) -> V:
572 """Register a resource as if it were used in a ``with``
573 statement. The resource will be cleaned up when the context is
574 popped.
576 Uses :meth:`contextlib.ExitStack.enter_context`. It calls the
577 resource's ``__enter__()`` method and returns the result. When
578 the context is popped, it closes the stack, which calls the
579 resource's ``__exit__()`` method.
581 To register a cleanup function for something that isn't a
582 context manager, use :meth:`call_on_close`. Or use something
583 from :mod:`contextlib` to turn it into a context manager first.
585 .. code-block:: python
587 @click.group()
588 @click.option("--name")
589 @click.pass_context
590 def cli(ctx):
591 ctx.obj = ctx.with_resource(connect_db(name))
593 :param context_manager: The context manager to enter.
594 :return: Whatever ``context_manager.__enter__()`` returns.
596 .. versionadded:: 8.0
597 """
598 return self._exit_stack.enter_context(context_manager)
600 def call_on_close(self, f: t.Callable[..., t.Any]) -> t.Callable[..., t.Any]:
601 """Register a function to be called when the context tears down.
603 This can be used to close resources opened during the script
604 execution. Resources that support Python's context manager
605 protocol which would be used in a ``with`` statement should be
606 registered with :meth:`with_resource` instead.
608 :param f: The function to execute on teardown.
609 """
610 return self._exit_stack.callback(f)
612 def close(self) -> None:
613 """Invoke all close callbacks registered with
614 :meth:`call_on_close`, and exit all context managers entered
615 with :meth:`with_resource`.
616 """
617 self._exit_stack.close()
618 # In case the context is reused, create a new exit stack.
619 self._exit_stack = ExitStack()
621 @property
622 def command_path(self) -> str:
623 """The computed command path. This is used for the ``usage``
624 information on the help page. It's automatically created by
625 combining the info names of the chain of contexts to the root.
626 """
627 rv = ""
628 if self.info_name is not None:
629 rv = self.info_name
630 if self.parent is not None:
631 parent_command_path = [self.parent.command_path]
633 if isinstance(self.parent.command, Command):
634 for param in self.parent.command.get_params(self):
635 parent_command_path.extend(param.get_usage_pieces(self))
637 rv = f"{' '.join(parent_command_path)} {rv}"
638 return rv.lstrip()
640 def find_root(self) -> Context:
641 """Finds the outermost context."""
642 node = self
643 while node.parent is not None:
644 node = node.parent
645 return node
647 def find_object(self, object_type: type[V]) -> V | None:
648 """Finds the closest object of a given type."""
649 node: Context | None = self
651 while node is not None:
652 if isinstance(node.obj, object_type):
653 return node.obj
655 node = node.parent
657 return None
659 def ensure_object(self, object_type: type[V]) -> V:
660 """Like :meth:`find_object` but sets the innermost object to a
661 new instance of `object_type` if it does not exist.
662 """
663 rv = self.find_object(object_type)
664 if rv is None:
665 self.obj = rv = object_type()
666 return rv
668 @t.overload
669 def lookup_default(
670 self, name: str, call: t.Literal[True] = True
671 ) -> t.Any | None: ...
673 @t.overload
674 def lookup_default(
675 self, name: str, call: t.Literal[False] = ...
676 ) -> t.Any | t.Callable[[], t.Any] | None: ...
678 def lookup_default(self, name: str, call: bool = True) -> t.Any | None:
679 """Get the default for a parameter from :attr:`default_map`.
681 :param name: Name of the parameter.
682 :param call: If the default is a callable, call it. Disable to
683 return the callable instead.
685 .. versionchanged:: 8.0
686 Added the ``call`` parameter.
687 """
688 if self.default_map is not None:
689 value = self.default_map.get(name)
691 if call and callable(value):
692 return value()
694 return value
696 return None
698 def fail(self, message: str) -> t.NoReturn:
699 """Aborts the execution of the program with a specific error
700 message.
702 :param message: the error message to fail with.
703 """
704 raise UsageError(message, self)
706 def abort(self) -> t.NoReturn:
707 """Aborts the script."""
708 raise Abort()
710 def exit(self, code: int = 0) -> t.NoReturn:
711 """Exits the application with a given exit code.
713 .. versionchanged:: 8.2
714 Callbacks and context managers registered with :meth:`call_on_close`
715 and :meth:`with_resource` are closed before exiting.
716 """
717 self.close()
718 raise Exit(code)
720 def get_usage(self) -> str:
721 """Helper method to get formatted usage string for the current
722 context and command.
723 """
724 return self.command.get_usage(self)
726 def get_help(self) -> str:
727 """Helper method to get formatted help page for the current
728 context and command.
729 """
730 return self.command.get_help(self)
732 def _make_sub_context(self, command: Command) -> Context:
733 """Create a new context of the same type as this context, but
734 for a new command.
736 :meta private:
737 """
738 return type(self)(command, info_name=command.name, parent=self)
740 @t.overload
741 def invoke(
742 self, callback: t.Callable[..., V], /, *args: t.Any, **kwargs: t.Any
743 ) -> V: ...
745 @t.overload
746 def invoke(self, callback: Command, /, *args: t.Any, **kwargs: t.Any) -> t.Any: ...
748 def invoke(
749 self, callback: Command | t.Callable[..., V], /, *args: t.Any, **kwargs: t.Any
750 ) -> t.Any | V:
751 """Invokes a command callback in exactly the way it expects. There
752 are two ways to invoke this method:
754 1. the first argument can be a callback and all other arguments and
755 keyword arguments are forwarded directly to the function.
756 2. the first argument is a click command object. In that case all
757 arguments are forwarded as well but proper click parameters
758 (options and click arguments) must be keyword arguments and Click
759 will fill in defaults.
761 .. versionchanged:: 8.0
762 All ``kwargs`` are tracked in :attr:`params` so they will be
763 passed if :meth:`forward` is called at multiple levels.
765 .. versionchanged:: 3.2
766 A new context is created, and missing arguments use default values.
767 """
768 if isinstance(callback, Command):
769 other_cmd = callback
771 if other_cmd.callback is None:
772 raise TypeError(
773 "The given command does not have a callback that can be invoked."
774 )
775 else:
776 callback = t.cast("t.Callable[..., V]", other_cmd.callback)
778 ctx = self._make_sub_context(other_cmd)
780 for param in other_cmd.params:
781 if param.name not in kwargs and param.expose_value:
782 kwargs[param.name] = param.type_cast_value( # type: ignore
783 ctx, param.get_default(ctx)
784 )
786 # Track all kwargs as params, so that forward() will pass
787 # them on in subsequent calls.
788 ctx.params.update(kwargs)
789 else:
790 ctx = self
792 with augment_usage_errors(self):
793 with ctx:
794 return callback(*args, **kwargs)
796 def forward(self, cmd: Command, /, *args: t.Any, **kwargs: t.Any) -> t.Any:
797 """Similar to :meth:`invoke` but fills in default keyword
798 arguments from the current context if the other command expects
799 it. This cannot invoke callbacks directly, only other commands.
801 .. versionchanged:: 8.0
802 All ``kwargs`` are tracked in :attr:`params` so they will be
803 passed if ``forward`` is called at multiple levels.
804 """
805 # Can only forward to other commands, not direct callbacks.
806 if not isinstance(cmd, Command):
807 raise TypeError("Callback is not a command.")
809 for param in self.params:
810 if param not in kwargs:
811 kwargs[param] = self.params[param]
813 return self.invoke(cmd, *args, **kwargs)
815 def set_parameter_source(self, name: str, source: ParameterSource) -> None:
816 """Set the source of a parameter. This indicates the location
817 from which the value of the parameter was obtained.
819 :param name: The name of the parameter.
820 :param source: A member of :class:`~click.core.ParameterSource`.
821 """
822 self._parameter_source[name] = source
824 def get_parameter_source(self, name: str) -> ParameterSource | None:
825 """Get the source of a parameter. This indicates the location
826 from which the value of the parameter was obtained.
828 This can be useful for determining when a user specified a value
829 on the command line that is the same as the default value. It
830 will be :attr:`~click.core.ParameterSource.DEFAULT` only if the
831 value was actually taken from the default.
833 :param name: The name of the parameter.
834 :rtype: ParameterSource
836 .. versionchanged:: 8.0
837 Returns ``None`` if the parameter was not provided from any
838 source.
839 """
840 return self._parameter_source.get(name)
843class Command:
844 """Commands are the basic building block of command line interfaces in
845 Click. A basic command handles command line parsing and might dispatch
846 more parsing to commands nested below it.
848 :param name: the name of the command to use unless a group overrides it.
849 :param context_settings: an optional dictionary with defaults that are
850 passed to the context object.
851 :param callback: the callback to invoke. This is optional.
852 :param params: the parameters to register with this command. This can
853 be either :class:`Option` or :class:`Argument` objects.
854 :param help: the help string to use for this command.
855 :param epilog: like the help string but it's printed at the end of the
856 help page after everything else.
857 :param short_help: the short help to use for this command. This is
858 shown on the command listing of the parent command.
859 :param add_help_option: by default each command registers a ``--help``
860 option. This can be disabled by this parameter.
861 :param no_args_is_help: this controls what happens if no arguments are
862 provided. This option is disabled by default.
863 If enabled this will add ``--help`` as argument
864 if no arguments are passed
865 :param hidden: hide this command from help outputs.
866 :param deprecated: If ``True`` or non-empty string, issues a message
867 indicating that the command is deprecated and highlights
868 its deprecation in --help. The message can be customized
869 by using a string as the value.
871 .. versionchanged:: 8.2
872 This is the base class for all commands, not ``BaseCommand``.
873 ``deprecated`` can be set to a string as well to customize the
874 deprecation message.
876 .. versionchanged:: 8.1
877 ``help``, ``epilog``, and ``short_help`` are stored unprocessed,
878 all formatting is done when outputting help text, not at init,
879 and is done even if not using the ``@command`` decorator.
881 .. versionchanged:: 8.0
882 Added a ``repr`` showing the command name.
884 .. versionchanged:: 7.1
885 Added the ``no_args_is_help`` parameter.
887 .. versionchanged:: 2.0
888 Added the ``context_settings`` parameter.
889 """
891 #: The context class to create with :meth:`make_context`.
892 #:
893 #: .. versionadded:: 8.0
894 context_class: type[Context] = Context
896 #: the default for the :attr:`Context.allow_extra_args` flag.
897 allow_extra_args = False
899 #: the default for the :attr:`Context.allow_interspersed_args` flag.
900 allow_interspersed_args = True
902 #: the default for the :attr:`Context.ignore_unknown_options` flag.
903 ignore_unknown_options = False
905 def __init__(
906 self,
907 name: str | None,
908 context_settings: cabc.MutableMapping[str, t.Any] | None = None,
909 callback: t.Callable[..., t.Any] | None = None,
910 params: list[Parameter] | None = None,
911 help: str | None = None,
912 epilog: str | None = None,
913 short_help: str | None = None,
914 options_metavar: str | None = "[OPTIONS]",
915 add_help_option: bool = True,
916 no_args_is_help: bool = False,
917 hidden: bool = False,
918 deprecated: bool | str = False,
919 ) -> None:
920 #: the name the command thinks it has. Upon registering a command
921 #: on a :class:`Group` the group will default the command name
922 #: with this information. You should instead use the
923 #: :class:`Context`\'s :attr:`~Context.info_name` attribute.
924 self.name = name
926 if context_settings is None:
927 context_settings = {}
929 #: an optional dictionary with defaults passed to the context.
930 self.context_settings: cabc.MutableMapping[str, t.Any] = context_settings
932 #: the callback to execute when the command fires. This might be
933 #: `None` in which case nothing happens.
934 self.callback = callback
935 #: the list of parameters for this command in the order they
936 #: should show up in the help page and execute. Eager parameters
937 #: will automatically be handled before non eager ones.
938 self.params: list[Parameter] = params or []
939 self.help = help
940 self.epilog = epilog
941 self.options_metavar = options_metavar
942 self.short_help = short_help
943 self.add_help_option = add_help_option
944 self._help_option = None
945 self.no_args_is_help = no_args_is_help
946 self.hidden = hidden
947 self.deprecated = deprecated
949 def to_info_dict(self, ctx: Context) -> dict[str, t.Any]:
950 return {
951 "name": self.name,
952 "params": [param.to_info_dict() for param in self.get_params(ctx)],
953 "help": self.help,
954 "epilog": self.epilog,
955 "short_help": self.short_help,
956 "hidden": self.hidden,
957 "deprecated": self.deprecated,
958 }
960 def __repr__(self) -> str:
961 return f"<{self.__class__.__name__} {self.name}>"
963 def get_usage(self, ctx: Context) -> str:
964 """Formats the usage line into a string and returns it.
966 Calls :meth:`format_usage` internally.
967 """
968 formatter = ctx.make_formatter()
969 self.format_usage(ctx, formatter)
970 return formatter.getvalue().rstrip("\n")
972 def get_params(self, ctx: Context) -> list[Parameter]:
973 params = self.params
974 help_option = self.get_help_option(ctx)
976 if help_option is not None:
977 params = [*params, help_option]
979 if __debug__:
980 import warnings
982 opts = [opt for param in params for opt in param.opts]
983 opts_counter = Counter(opts)
984 duplicate_opts = (opt for opt, count in opts_counter.items() if count > 1)
986 for duplicate_opt in duplicate_opts:
987 warnings.warn(
988 (
989 f"The parameter {duplicate_opt} is used more than once. "
990 "Remove its duplicate as parameters should be unique."
991 ),
992 stacklevel=3,
993 )
995 return params
997 def format_usage(self, ctx: Context, formatter: HelpFormatter) -> None:
998 """Writes the usage line into the formatter.
1000 This is a low-level method called by :meth:`get_usage`.
1001 """
1002 pieces = self.collect_usage_pieces(ctx)
1003 formatter.write_usage(ctx.command_path, " ".join(pieces))
1005 def collect_usage_pieces(self, ctx: Context) -> list[str]:
1006 """Returns all the pieces that go into the usage line and returns
1007 it as a list of strings.
1008 """
1009 rv = [self.options_metavar] if self.options_metavar else []
1011 for param in self.get_params(ctx):
1012 rv.extend(param.get_usage_pieces(ctx))
1014 return rv
1016 def get_help_option_names(self, ctx: Context) -> list[str]:
1017 """Returns the names for the help option."""
1018 all_names = set(ctx.help_option_names)
1019 for param in self.params:
1020 all_names.difference_update(param.opts)
1021 all_names.difference_update(param.secondary_opts)
1022 return list(all_names)
1024 def get_help_option(self, ctx: Context) -> Option | None:
1025 """Returns the help option object.
1027 Skipped if :attr:`add_help_option` is ``False``.
1029 .. versionchanged:: 8.1.8
1030 The help option is now cached to avoid creating it multiple times.
1031 """
1032 help_option_names = self.get_help_option_names(ctx)
1034 if not help_option_names or not self.add_help_option:
1035 return None
1037 # Cache the help option object in private _help_option attribute to
1038 # avoid creating it multiple times. Not doing this will break the
1039 # callback odering by iter_params_for_processing(), which relies on
1040 # object comparison.
1041 if self._help_option is None:
1042 # Avoid circular import.
1043 from .decorators import help_option
1045 # Apply help_option decorator and pop resulting option
1046 help_option(*help_option_names)(self)
1047 self._help_option = self.params.pop() # type: ignore[assignment]
1049 return self._help_option
1051 def make_parser(self, ctx: Context) -> _OptionParser:
1052 """Creates the underlying option parser for this command."""
1053 parser = _OptionParser(ctx)
1054 for param in self.get_params(ctx):
1055 param.add_to_parser(parser, ctx)
1056 return parser
1058 def get_help(self, ctx: Context) -> str:
1059 """Formats the help into a string and returns it.
1061 Calls :meth:`format_help` internally.
1062 """
1063 formatter = ctx.make_formatter()
1064 self.format_help(ctx, formatter)
1065 return formatter.getvalue().rstrip("\n")
1067 def get_short_help_str(self, limit: int = 45) -> str:
1068 """Gets short help for the command or makes it by shortening the
1069 long help string.
1070 """
1071 if self.short_help:
1072 text = inspect.cleandoc(self.short_help)
1073 elif self.help:
1074 text = make_default_short_help(self.help, limit)
1075 else:
1076 text = ""
1078 if self.deprecated:
1079 deprecated_message = (
1080 f"(DEPRECATED: {self.deprecated})"
1081 if isinstance(self.deprecated, str)
1082 else "(DEPRECATED)"
1083 )
1084 text = _("{text} {deprecated_message}").format(
1085 text=text, deprecated_message=deprecated_message
1086 )
1088 return text.strip()
1090 def format_help(self, ctx: Context, formatter: HelpFormatter) -> None:
1091 """Writes the help into the formatter if it exists.
1093 This is a low-level method called by :meth:`get_help`.
1095 This calls the following methods:
1097 - :meth:`format_usage`
1098 - :meth:`format_help_text`
1099 - :meth:`format_options`
1100 - :meth:`format_epilog`
1101 """
1102 self.format_usage(ctx, formatter)
1103 self.format_help_text(ctx, formatter)
1104 self.format_options(ctx, formatter)
1105 self.format_epilog(ctx, formatter)
1107 def format_help_text(self, ctx: Context, formatter: HelpFormatter) -> None:
1108 """Writes the help text to the formatter if it exists."""
1109 if self.help is not None:
1110 # truncate the help text to the first form feed
1111 text = inspect.cleandoc(self.help).partition("\f")[0]
1112 else:
1113 text = ""
1115 if self.deprecated:
1116 deprecated_message = (
1117 f"(DEPRECATED: {self.deprecated})"
1118 if isinstance(self.deprecated, str)
1119 else "(DEPRECATED)"
1120 )
1121 text = _("{text} {deprecated_message}").format(
1122 text=text, deprecated_message=deprecated_message
1123 )
1125 if text:
1126 formatter.write_paragraph()
1128 with formatter.indentation():
1129 formatter.write_text(text)
1131 def format_options(self, ctx: Context, formatter: HelpFormatter) -> None:
1132 """Writes all the options into the formatter if they exist."""
1133 opts = []
1134 for param in self.get_params(ctx):
1135 rv = param.get_help_record(ctx)
1136 if rv is not None:
1137 opts.append(rv)
1139 if opts:
1140 with formatter.section(_("Options")):
1141 formatter.write_dl(opts)
1143 def format_epilog(self, ctx: Context, formatter: HelpFormatter) -> None:
1144 """Writes the epilog into the formatter if it exists."""
1145 if self.epilog:
1146 epilog = inspect.cleandoc(self.epilog)
1147 formatter.write_paragraph()
1149 with formatter.indentation():
1150 formatter.write_text(epilog)
1152 def make_context(
1153 self,
1154 info_name: str | None,
1155 args: list[str],
1156 parent: Context | None = None,
1157 **extra: t.Any,
1158 ) -> Context:
1159 """This function when given an info name and arguments will kick
1160 off the parsing and create a new :class:`Context`. It does not
1161 invoke the actual command callback though.
1163 To quickly customize the context class used without overriding
1164 this method, set the :attr:`context_class` attribute.
1166 :param info_name: the info name for this invocation. Generally this
1167 is the most descriptive name for the script or
1168 command. For the toplevel script it's usually
1169 the name of the script, for commands below it's
1170 the name of the command.
1171 :param args: the arguments to parse as list of strings.
1172 :param parent: the parent context if available.
1173 :param extra: extra keyword arguments forwarded to the context
1174 constructor.
1176 .. versionchanged:: 8.0
1177 Added the :attr:`context_class` attribute.
1178 """
1179 for key, value in self.context_settings.items():
1180 if key not in extra:
1181 extra[key] = value
1183 ctx = self.context_class(self, info_name=info_name, parent=parent, **extra)
1185 with ctx.scope(cleanup=False):
1186 self.parse_args(ctx, args)
1187 return ctx
1189 def parse_args(self, ctx: Context, args: list[str]) -> list[str]:
1190 if not args and self.no_args_is_help and not ctx.resilient_parsing:
1191 raise NoArgsIsHelpError(ctx)
1193 parser = self.make_parser(ctx)
1194 opts, args, param_order = parser.parse_args(args=args)
1196 for param in iter_params_for_processing(param_order, self.get_params(ctx)):
1197 value, args = param.handle_parse_result(ctx, opts, args)
1199 if args and not ctx.allow_extra_args and not ctx.resilient_parsing:
1200 ctx.fail(
1201 ngettext(
1202 "Got unexpected extra argument ({args})",
1203 "Got unexpected extra arguments ({args})",
1204 len(args),
1205 ).format(args=" ".join(map(str, args)))
1206 )
1208 ctx.args = args
1209 ctx._opt_prefixes.update(parser._opt_prefixes)
1210 return args
1212 def invoke(self, ctx: Context) -> t.Any:
1213 """Given a context, this invokes the attached callback (if it exists)
1214 in the right way.
1215 """
1216 if self.deprecated:
1217 extra_message = (
1218 f" {self.deprecated}" if isinstance(self.deprecated, str) else ""
1219 )
1220 message = _(
1221 "DeprecationWarning: The command {name!r} is deprecated.{extra_message}"
1222 ).format(name=self.name, extra_message=extra_message)
1223 echo(style(message, fg="red"), err=True)
1225 if self.callback is not None:
1226 return ctx.invoke(self.callback, **ctx.params)
1228 def shell_complete(self, ctx: Context, incomplete: str) -> list[CompletionItem]:
1229 """Return a list of completions for the incomplete value. Looks
1230 at the names of options and chained multi-commands.
1232 Any command could be part of a chained multi-command, so sibling
1233 commands are valid at any point during command completion.
1235 :param ctx: Invocation context for this command.
1236 :param incomplete: Value being completed. May be empty.
1238 .. versionadded:: 8.0
1239 """
1240 from click.shell_completion import CompletionItem
1242 results: list[CompletionItem] = []
1244 if incomplete and not incomplete[0].isalnum():
1245 for param in self.get_params(ctx):
1246 if (
1247 not isinstance(param, Option)
1248 or param.hidden
1249 or (
1250 not param.multiple
1251 and ctx.get_parameter_source(param.name) # type: ignore
1252 is ParameterSource.COMMANDLINE
1253 )
1254 ):
1255 continue
1257 results.extend(
1258 CompletionItem(name, help=param.help)
1259 for name in [*param.opts, *param.secondary_opts]
1260 if name.startswith(incomplete)
1261 )
1263 while ctx.parent is not None:
1264 ctx = ctx.parent
1266 if isinstance(ctx.command, Group) and ctx.command.chain:
1267 results.extend(
1268 CompletionItem(name, help=command.get_short_help_str())
1269 for name, command in _complete_visible_commands(ctx, incomplete)
1270 if name not in ctx._protected_args
1271 )
1273 return results
1275 @t.overload
1276 def main(
1277 self,
1278 args: cabc.Sequence[str] | None = None,
1279 prog_name: str | None = None,
1280 complete_var: str | None = None,
1281 standalone_mode: t.Literal[True] = True,
1282 **extra: t.Any,
1283 ) -> t.NoReturn: ...
1285 @t.overload
1286 def main(
1287 self,
1288 args: cabc.Sequence[str] | None = None,
1289 prog_name: str | None = None,
1290 complete_var: str | None = None,
1291 standalone_mode: bool = ...,
1292 **extra: t.Any,
1293 ) -> t.Any: ...
1295 def main(
1296 self,
1297 args: cabc.Sequence[str] | None = None,
1298 prog_name: str | None = None,
1299 complete_var: str | None = None,
1300 standalone_mode: bool = True,
1301 windows_expand_args: bool = True,
1302 **extra: t.Any,
1303 ) -> t.Any:
1304 """This is the way to invoke a script with all the bells and
1305 whistles as a command line application. This will always terminate
1306 the application after a call. If this is not wanted, ``SystemExit``
1307 needs to be caught.
1309 This method is also available by directly calling the instance of
1310 a :class:`Command`.
1312 :param args: the arguments that should be used for parsing. If not
1313 provided, ``sys.argv[1:]`` is used.
1314 :param prog_name: the program name that should be used. By default
1315 the program name is constructed by taking the file
1316 name from ``sys.argv[0]``.
1317 :param complete_var: the environment variable that controls the
1318 bash completion support. The default is
1319 ``"_<prog_name>_COMPLETE"`` with prog_name in
1320 uppercase.
1321 :param standalone_mode: the default behavior is to invoke the script
1322 in standalone mode. Click will then
1323 handle exceptions and convert them into
1324 error messages and the function will never
1325 return but shut down the interpreter. If
1326 this is set to `False` they will be
1327 propagated to the caller and the return
1328 value of this function is the return value
1329 of :meth:`invoke`.
1330 :param windows_expand_args: Expand glob patterns, user dir, and
1331 env vars in command line args on Windows.
1332 :param extra: extra keyword arguments are forwarded to the context
1333 constructor. See :class:`Context` for more information.
1335 .. versionchanged:: 8.0.1
1336 Added the ``windows_expand_args`` parameter to allow
1337 disabling command line arg expansion on Windows.
1339 .. versionchanged:: 8.0
1340 When taking arguments from ``sys.argv`` on Windows, glob
1341 patterns, user dir, and env vars are expanded.
1343 .. versionchanged:: 3.0
1344 Added the ``standalone_mode`` parameter.
1345 """
1346 if args is None:
1347 args = sys.argv[1:]
1349 if os.name == "nt" and windows_expand_args:
1350 args = _expand_args(args)
1351 else:
1352 args = list(args)
1354 if prog_name is None:
1355 prog_name = _detect_program_name()
1357 # Process shell completion requests and exit early.
1358 self._main_shell_completion(extra, prog_name, complete_var)
1360 try:
1361 try:
1362 with self.make_context(prog_name, args, **extra) as ctx:
1363 rv = self.invoke(ctx)
1364 if not standalone_mode:
1365 return rv
1366 # it's not safe to `ctx.exit(rv)` here!
1367 # note that `rv` may actually contain data like "1" which
1368 # has obvious effects
1369 # more subtle case: `rv=[None, None]` can come out of
1370 # chained commands which all returned `None` -- so it's not
1371 # even always obvious that `rv` indicates success/failure
1372 # by its truthiness/falsiness
1373 ctx.exit()
1374 except (EOFError, KeyboardInterrupt) as e:
1375 echo(file=sys.stderr)
1376 raise Abort() from e
1377 except ClickException as e:
1378 if not standalone_mode:
1379 raise
1380 e.show()
1381 sys.exit(e.exit_code)
1382 except OSError as e:
1383 if e.errno == errno.EPIPE:
1384 sys.stdout = t.cast(t.TextIO, PacifyFlushWrapper(sys.stdout))
1385 sys.stderr = t.cast(t.TextIO, PacifyFlushWrapper(sys.stderr))
1386 sys.exit(1)
1387 else:
1388 raise
1389 except Exit as e:
1390 if standalone_mode:
1391 sys.exit(e.exit_code)
1392 else:
1393 # in non-standalone mode, return the exit code
1394 # note that this is only reached if `self.invoke` above raises
1395 # an Exit explicitly -- thus bypassing the check there which
1396 # would return its result
1397 # the results of non-standalone execution may therefore be
1398 # somewhat ambiguous: if there are codepaths which lead to
1399 # `ctx.exit(1)` and to `return 1`, the caller won't be able to
1400 # tell the difference between the two
1401 return e.exit_code
1402 except Abort:
1403 if not standalone_mode:
1404 raise
1405 echo(_("Aborted!"), file=sys.stderr)
1406 sys.exit(1)
1408 def _main_shell_completion(
1409 self,
1410 ctx_args: cabc.MutableMapping[str, t.Any],
1411 prog_name: str,
1412 complete_var: str | None = None,
1413 ) -> None:
1414 """Check if the shell is asking for tab completion, process
1415 that, then exit early. Called from :meth:`main` before the
1416 program is invoked.
1418 :param prog_name: Name of the executable in the shell.
1419 :param complete_var: Name of the environment variable that holds
1420 the completion instruction. Defaults to
1421 ``_{PROG_NAME}_COMPLETE``.
1423 .. versionchanged:: 8.2.0
1424 Dots (``.``) in ``prog_name`` are replaced with underscores (``_``).
1425 """
1426 if complete_var is None:
1427 complete_name = prog_name.replace("-", "_").replace(".", "_")
1428 complete_var = f"_{complete_name}_COMPLETE".upper()
1430 instruction = os.environ.get(complete_var)
1432 if not instruction:
1433 return
1435 from .shell_completion import shell_complete
1437 rv = shell_complete(self, ctx_args, prog_name, complete_var, instruction)
1438 sys.exit(rv)
1440 def __call__(self, *args: t.Any, **kwargs: t.Any) -> t.Any:
1441 """Alias for :meth:`main`."""
1442 return self.main(*args, **kwargs)
1445class _FakeSubclassCheck(type):
1446 def __subclasscheck__(cls, subclass: type) -> bool:
1447 return issubclass(subclass, cls.__bases__[0])
1449 def __instancecheck__(cls, instance: t.Any) -> bool:
1450 return isinstance(instance, cls.__bases__[0])
1453class _BaseCommand(Command, metaclass=_FakeSubclassCheck):
1454 """
1455 .. deprecated:: 8.2
1456 Will be removed in Click 9.0. Use ``Command`` instead.
1457 """
1460class Group(Command):
1461 """A group is a command that nests other commands (or more groups).
1463 :param name: The name of the group command.
1464 :param commands: Map names to :class:`Command` objects. Can be a list, which
1465 will use :attr:`Command.name` as the keys.
1466 :param invoke_without_command: Invoke the group's callback even if a
1467 subcommand is not given.
1468 :param no_args_is_help: If no arguments are given, show the group's help and
1469 exit. Defaults to the opposite of ``invoke_without_command``.
1470 :param subcommand_metavar: How to represent the subcommand argument in help.
1471 The default will represent whether ``chain`` is set or not.
1472 :param chain: Allow passing more than one subcommand argument. After parsing
1473 a command's arguments, if any arguments remain another command will be
1474 matched, and so on.
1475 :param result_callback: A function to call after the group's and
1476 subcommand's callbacks. The value returned by the subcommand is passed.
1477 If ``chain`` is enabled, the value will be a list of values returned by
1478 all the commands. If ``invoke_without_command`` is enabled, the value
1479 will be the value returned by the group's callback, or an empty list if
1480 ``chain`` is enabled.
1481 :param kwargs: Other arguments passed to :class:`Command`.
1483 .. versionchanged:: 8.0
1484 The ``commands`` argument can be a list of command objects.
1486 .. versionchanged:: 8.2
1487 Merged with and replaces the ``MultiCommand`` base class.
1488 """
1490 allow_extra_args = True
1491 allow_interspersed_args = False
1493 #: If set, this is used by the group's :meth:`command` decorator
1494 #: as the default :class:`Command` class. This is useful to make all
1495 #: subcommands use a custom command class.
1496 #:
1497 #: .. versionadded:: 8.0
1498 command_class: type[Command] | None = None
1500 #: If set, this is used by the group's :meth:`group` decorator
1501 #: as the default :class:`Group` class. This is useful to make all
1502 #: subgroups use a custom group class.
1503 #:
1504 #: If set to the special value :class:`type` (literally
1505 #: ``group_class = type``), this group's class will be used as the
1506 #: default class. This makes a custom group class continue to make
1507 #: custom groups.
1508 #:
1509 #: .. versionadded:: 8.0
1510 group_class: type[Group] | type[type] | None = None
1511 # Literal[type] isn't valid, so use Type[type]
1513 def __init__(
1514 self,
1515 name: str | None = None,
1516 commands: cabc.MutableMapping[str, Command]
1517 | cabc.Sequence[Command]
1518 | None = None,
1519 invoke_without_command: bool = False,
1520 no_args_is_help: bool | None = None,
1521 subcommand_metavar: str | None = None,
1522 chain: bool = False,
1523 result_callback: t.Callable[..., t.Any] | None = None,
1524 **kwargs: t.Any,
1525 ) -> None:
1526 super().__init__(name, **kwargs)
1528 if commands is None:
1529 commands = {}
1530 elif isinstance(commands, abc.Sequence):
1531 commands = {c.name: c for c in commands if c.name is not None}
1533 #: The registered subcommands by their exported names.
1534 self.commands: cabc.MutableMapping[str, Command] = commands
1536 if no_args_is_help is None:
1537 no_args_is_help = not invoke_without_command
1539 self.no_args_is_help = no_args_is_help
1540 self.invoke_without_command = invoke_without_command
1542 if subcommand_metavar is None:
1543 if chain:
1544 subcommand_metavar = "COMMAND1 [ARGS]... [COMMAND2 [ARGS]...]..."
1545 else:
1546 subcommand_metavar = "COMMAND [ARGS]..."
1548 self.subcommand_metavar = subcommand_metavar
1549 self.chain = chain
1550 # The result callback that is stored. This can be set or
1551 # overridden with the :func:`result_callback` decorator.
1552 self._result_callback = result_callback
1554 if self.chain:
1555 for param in self.params:
1556 if isinstance(param, Argument) and not param.required:
1557 raise RuntimeError(
1558 "A group in chain mode cannot have optional arguments."
1559 )
1561 def to_info_dict(self, ctx: Context) -> dict[str, t.Any]:
1562 info_dict = super().to_info_dict(ctx)
1563 commands = {}
1565 for name in self.list_commands(ctx):
1566 command = self.get_command(ctx, name)
1568 if command is None:
1569 continue
1571 sub_ctx = ctx._make_sub_context(command)
1573 with sub_ctx.scope(cleanup=False):
1574 commands[name] = command.to_info_dict(sub_ctx)
1576 info_dict.update(commands=commands, chain=self.chain)
1577 return info_dict
1579 def add_command(self, cmd: Command, name: str | None = None) -> None:
1580 """Registers another :class:`Command` with this group. If the name
1581 is not provided, the name of the command is used.
1582 """
1583 name = name or cmd.name
1584 if name is None:
1585 raise TypeError("Command has no name.")
1586 _check_nested_chain(self, name, cmd, register=True)
1587 self.commands[name] = cmd
1589 @t.overload
1590 def command(self, __func: t.Callable[..., t.Any]) -> Command: ...
1592 @t.overload
1593 def command(
1594 self, *args: t.Any, **kwargs: t.Any
1595 ) -> t.Callable[[t.Callable[..., t.Any]], Command]: ...
1597 def command(
1598 self, *args: t.Any, **kwargs: t.Any
1599 ) -> t.Callable[[t.Callable[..., t.Any]], Command] | Command:
1600 """A shortcut decorator for declaring and attaching a command to
1601 the group. This takes the same arguments as :func:`command` and
1602 immediately registers the created command with this group by
1603 calling :meth:`add_command`.
1605 To customize the command class used, set the
1606 :attr:`command_class` attribute.
1608 .. versionchanged:: 8.1
1609 This decorator can be applied without parentheses.
1611 .. versionchanged:: 8.0
1612 Added the :attr:`command_class` attribute.
1613 """
1614 from .decorators import command
1616 func: t.Callable[..., t.Any] | None = None
1618 if args and callable(args[0]):
1619 assert len(args) == 1 and not kwargs, (
1620 "Use 'command(**kwargs)(callable)' to provide arguments."
1621 )
1622 (func,) = args
1623 args = ()
1625 if self.command_class and kwargs.get("cls") is None:
1626 kwargs["cls"] = self.command_class
1628 def decorator(f: t.Callable[..., t.Any]) -> Command:
1629 cmd: Command = command(*args, **kwargs)(f)
1630 self.add_command(cmd)
1631 return cmd
1633 if func is not None:
1634 return decorator(func)
1636 return decorator
1638 @t.overload
1639 def group(self, __func: t.Callable[..., t.Any]) -> Group: ...
1641 @t.overload
1642 def group(
1643 self, *args: t.Any, **kwargs: t.Any
1644 ) -> t.Callable[[t.Callable[..., t.Any]], Group]: ...
1646 def group(
1647 self, *args: t.Any, **kwargs: t.Any
1648 ) -> t.Callable[[t.Callable[..., t.Any]], Group] | Group:
1649 """A shortcut decorator for declaring and attaching a group to
1650 the group. This takes the same arguments as :func:`group` and
1651 immediately registers the created group with this group by
1652 calling :meth:`add_command`.
1654 To customize the group class used, set the :attr:`group_class`
1655 attribute.
1657 .. versionchanged:: 8.1
1658 This decorator can be applied without parentheses.
1660 .. versionchanged:: 8.0
1661 Added the :attr:`group_class` attribute.
1662 """
1663 from .decorators import group
1665 func: t.Callable[..., t.Any] | None = None
1667 if args and callable(args[0]):
1668 assert len(args) == 1 and not kwargs, (
1669 "Use 'group(**kwargs)(callable)' to provide arguments."
1670 )
1671 (func,) = args
1672 args = ()
1674 if self.group_class is not None and kwargs.get("cls") is None:
1675 if self.group_class is type:
1676 kwargs["cls"] = type(self)
1677 else:
1678 kwargs["cls"] = self.group_class
1680 def decorator(f: t.Callable[..., t.Any]) -> Group:
1681 cmd: Group = group(*args, **kwargs)(f)
1682 self.add_command(cmd)
1683 return cmd
1685 if func is not None:
1686 return decorator(func)
1688 return decorator
1690 def result_callback(self, replace: bool = False) -> t.Callable[[F], F]:
1691 """Adds a result callback to the command. By default if a
1692 result callback is already registered this will chain them but
1693 this can be disabled with the `replace` parameter. The result
1694 callback is invoked with the return value of the subcommand
1695 (or the list of return values from all subcommands if chaining
1696 is enabled) as well as the parameters as they would be passed
1697 to the main callback.
1699 Example::
1701 @click.group()
1702 @click.option('-i', '--input', default=23)
1703 def cli(input):
1704 return 42
1706 @cli.result_callback()
1707 def process_result(result, input):
1708 return result + input
1710 :param replace: if set to `True` an already existing result
1711 callback will be removed.
1713 .. versionchanged:: 8.0
1714 Renamed from ``resultcallback``.
1716 .. versionadded:: 3.0
1717 """
1719 def decorator(f: F) -> F:
1720 old_callback = self._result_callback
1722 if old_callback is None or replace:
1723 self._result_callback = f
1724 return f
1726 def function(value: t.Any, /, *args: t.Any, **kwargs: t.Any) -> t.Any:
1727 inner = old_callback(value, *args, **kwargs)
1728 return f(inner, *args, **kwargs)
1730 self._result_callback = rv = update_wrapper(t.cast(F, function), f)
1731 return rv # type: ignore[return-value]
1733 return decorator
1735 def get_command(self, ctx: Context, cmd_name: str) -> Command | None:
1736 """Given a context and a command name, this returns a :class:`Command`
1737 object if it exists or returns ``None``.
1738 """
1739 return self.commands.get(cmd_name)
1741 def list_commands(self, ctx: Context) -> list[str]:
1742 """Returns a list of subcommand names in the order they should appear."""
1743 return sorted(self.commands)
1745 def collect_usage_pieces(self, ctx: Context) -> list[str]:
1746 rv = super().collect_usage_pieces(ctx)
1747 rv.append(self.subcommand_metavar)
1748 return rv
1750 def format_options(self, ctx: Context, formatter: HelpFormatter) -> None:
1751 super().format_options(ctx, formatter)
1752 self.format_commands(ctx, formatter)
1754 def format_commands(self, ctx: Context, formatter: HelpFormatter) -> None:
1755 """Extra format methods for multi methods that adds all the commands
1756 after the options.
1757 """
1758 commands = []
1759 for subcommand in self.list_commands(ctx):
1760 cmd = self.get_command(ctx, subcommand)
1761 # What is this, the tool lied about a command. Ignore it
1762 if cmd is None:
1763 continue
1764 if cmd.hidden:
1765 continue
1767 commands.append((subcommand, cmd))
1769 # allow for 3 times the default spacing
1770 if len(commands):
1771 limit = formatter.width - 6 - max(len(cmd[0]) for cmd in commands)
1773 rows = []
1774 for subcommand, cmd in commands:
1775 help = cmd.get_short_help_str(limit)
1776 rows.append((subcommand, help))
1778 if rows:
1779 with formatter.section(_("Commands")):
1780 formatter.write_dl(rows)
1782 def parse_args(self, ctx: Context, args: list[str]) -> list[str]:
1783 if not args and self.no_args_is_help and not ctx.resilient_parsing:
1784 raise NoArgsIsHelpError(ctx)
1786 rest = super().parse_args(ctx, args)
1788 if self.chain:
1789 ctx._protected_args = rest
1790 ctx.args = []
1791 elif rest:
1792 ctx._protected_args, ctx.args = rest[:1], rest[1:]
1794 return ctx.args
1796 def invoke(self, ctx: Context) -> t.Any:
1797 def _process_result(value: t.Any) -> t.Any:
1798 if self._result_callback is not None:
1799 value = ctx.invoke(self._result_callback, value, **ctx.params)
1800 return value
1802 if not ctx._protected_args:
1803 if self.invoke_without_command:
1804 # No subcommand was invoked, so the result callback is
1805 # invoked with the group return value for regular
1806 # groups, or an empty list for chained groups.
1807 with ctx:
1808 rv = super().invoke(ctx)
1809 return _process_result([] if self.chain else rv)
1810 ctx.fail(_("Missing command."))
1812 # Fetch args back out
1813 args = [*ctx._protected_args, *ctx.args]
1814 ctx.args = []
1815 ctx._protected_args = []
1817 # If we're not in chain mode, we only allow the invocation of a
1818 # single command but we also inform the current context about the
1819 # name of the command to invoke.
1820 if not self.chain:
1821 # Make sure the context is entered so we do not clean up
1822 # resources until the result processor has worked.
1823 with ctx:
1824 cmd_name, cmd, args = self.resolve_command(ctx, args)
1825 assert cmd is not None
1826 ctx.invoked_subcommand = cmd_name
1827 super().invoke(ctx)
1828 sub_ctx = cmd.make_context(cmd_name, args, parent=ctx)
1829 with sub_ctx:
1830 return _process_result(sub_ctx.command.invoke(sub_ctx))
1832 # In chain mode we create the contexts step by step, but after the
1833 # base command has been invoked. Because at that point we do not
1834 # know the subcommands yet, the invoked subcommand attribute is
1835 # set to ``*`` to inform the command that subcommands are executed
1836 # but nothing else.
1837 with ctx:
1838 ctx.invoked_subcommand = "*" if args else None
1839 super().invoke(ctx)
1841 # Otherwise we make every single context and invoke them in a
1842 # chain. In that case the return value to the result processor
1843 # is the list of all invoked subcommand's results.
1844 contexts = []
1845 while args:
1846 cmd_name, cmd, args = self.resolve_command(ctx, args)
1847 assert cmd is not None
1848 sub_ctx = cmd.make_context(
1849 cmd_name,
1850 args,
1851 parent=ctx,
1852 allow_extra_args=True,
1853 allow_interspersed_args=False,
1854 )
1855 contexts.append(sub_ctx)
1856 args, sub_ctx.args = sub_ctx.args, []
1858 rv = []
1859 for sub_ctx in contexts:
1860 with sub_ctx:
1861 rv.append(sub_ctx.command.invoke(sub_ctx))
1862 return _process_result(rv)
1864 def resolve_command(
1865 self, ctx: Context, args: list[str]
1866 ) -> tuple[str | None, Command | None, list[str]]:
1867 cmd_name = make_str(args[0])
1868 original_cmd_name = cmd_name
1870 # Get the command
1871 cmd = self.get_command(ctx, cmd_name)
1873 # If we can't find the command but there is a normalization
1874 # function available, we try with that one.
1875 if cmd is None and ctx.token_normalize_func is not None:
1876 cmd_name = ctx.token_normalize_func(cmd_name)
1877 cmd = self.get_command(ctx, cmd_name)
1879 # If we don't find the command we want to show an error message
1880 # to the user that it was not provided. However, there is
1881 # something else we should do: if the first argument looks like
1882 # an option we want to kick off parsing again for arguments to
1883 # resolve things like --help which now should go to the main
1884 # place.
1885 if cmd is None and not ctx.resilient_parsing:
1886 if _split_opt(cmd_name)[0]:
1887 self.parse_args(ctx, args)
1888 ctx.fail(_("No such command {name!r}.").format(name=original_cmd_name))
1889 return cmd_name if cmd else None, cmd, args[1:]
1891 def shell_complete(self, ctx: Context, incomplete: str) -> list[CompletionItem]:
1892 """Return a list of completions for the incomplete value. Looks
1893 at the names of options, subcommands, and chained
1894 multi-commands.
1896 :param ctx: Invocation context for this command.
1897 :param incomplete: Value being completed. May be empty.
1899 .. versionadded:: 8.0
1900 """
1901 from click.shell_completion import CompletionItem
1903 results = [
1904 CompletionItem(name, help=command.get_short_help_str())
1905 for name, command in _complete_visible_commands(ctx, incomplete)
1906 ]
1907 results.extend(super().shell_complete(ctx, incomplete))
1908 return results
1911class _MultiCommand(Group, metaclass=_FakeSubclassCheck):
1912 """
1913 .. deprecated:: 8.2
1914 Will be removed in Click 9.0. Use ``Group`` instead.
1915 """
1918class CommandCollection(Group):
1919 """A :class:`Group` that looks up subcommands on other groups. If a command
1920 is not found on this group, each registered source is checked in order.
1921 Parameters on a source are not added to this group, and a source's callback
1922 is not invoked when invoking its commands. In other words, this "flattens"
1923 commands in many groups into this one group.
1925 :param name: The name of the group command.
1926 :param sources: A list of :class:`Group` objects to look up commands from.
1927 :param kwargs: Other arguments passed to :class:`Group`.
1929 .. versionchanged:: 8.2
1930 This is a subclass of ``Group``. Commands are looked up first on this
1931 group, then each of its sources.
1932 """
1934 def __init__(
1935 self,
1936 name: str | None = None,
1937 sources: list[Group] | None = None,
1938 **kwargs: t.Any,
1939 ) -> None:
1940 super().__init__(name, **kwargs)
1941 #: The list of registered groups.
1942 self.sources: list[Group] = sources or []
1944 def add_source(self, group: Group) -> None:
1945 """Add a group as a source of commands."""
1946 self.sources.append(group)
1948 def get_command(self, ctx: Context, cmd_name: str) -> Command | None:
1949 rv = super().get_command(ctx, cmd_name)
1951 if rv is not None:
1952 return rv
1954 for source in self.sources:
1955 rv = source.get_command(ctx, cmd_name)
1957 if rv is not None:
1958 if self.chain:
1959 _check_nested_chain(self, cmd_name, rv)
1961 return rv
1963 return None
1965 def list_commands(self, ctx: Context) -> list[str]:
1966 rv: set[str] = set(super().list_commands(ctx))
1968 for source in self.sources:
1969 rv.update(source.list_commands(ctx))
1971 return sorted(rv)
1974def _check_iter(value: t.Any) -> cabc.Iterator[t.Any]:
1975 """Check if the value is iterable but not a string. Raises a type
1976 error, or return an iterator over the value.
1977 """
1978 if isinstance(value, str):
1979 raise TypeError
1981 return iter(value)
1984class Parameter:
1985 r"""A parameter to a command comes in two versions: they are either
1986 :class:`Option`\s or :class:`Argument`\s. Other subclasses are currently
1987 not supported by design as some of the internals for parsing are
1988 intentionally not finalized.
1990 Some settings are supported by both options and arguments.
1992 :param param_decls: the parameter declarations for this option or
1993 argument. This is a list of flags or argument
1994 names.
1995 :param type: the type that should be used. Either a :class:`ParamType`
1996 or a Python type. The latter is converted into the former
1997 automatically if supported.
1998 :param required: controls if this is optional or not.
1999 :param default: the default value if omitted. This can also be a callable,
2000 in which case it's invoked when the default is needed
2001 without any arguments.
2002 :param callback: A function to further process or validate the value
2003 after type conversion. It is called as ``f(ctx, param, value)``
2004 and must return the value. It is called for all sources,
2005 including prompts.
2006 :param nargs: the number of arguments to match. If not ``1`` the return
2007 value is a tuple instead of single value. The default for
2008 nargs is ``1`` (except if the type is a tuple, then it's
2009 the arity of the tuple). If ``nargs=-1``, all remaining
2010 parameters are collected.
2011 :param metavar: how the value is represented in the help page.
2012 :param expose_value: if this is `True` then the value is passed onwards
2013 to the command callback and stored on the context,
2014 otherwise it's skipped.
2015 :param is_eager: eager values are processed before non eager ones. This
2016 should not be set for arguments or it will inverse the
2017 order of processing.
2018 :param envvar: a string or list of strings that are environment variables
2019 that should be checked.
2020 :param shell_complete: A function that returns custom shell
2021 completions. Used instead of the param's type completion if
2022 given. Takes ``ctx, param, incomplete`` and must return a list
2023 of :class:`~click.shell_completion.CompletionItem` or a list of
2024 strings.
2025 :param deprecated: If ``True`` or non-empty string, issues a message
2026 indicating that the argument is deprecated and highlights
2027 its deprecation in --help. The message can be customized
2028 by using a string as the value. A deprecated parameter
2029 cannot be required, a ValueError will be raised otherwise.
2031 .. versionchanged:: 8.2.0
2032 Introduction of ``deprecated``.
2034 .. versionchanged:: 8.2
2035 Adding duplicate parameter names to a :class:`~click.core.Command` will
2036 result in a ``UserWarning`` being shown.
2038 .. versionchanged:: 8.2
2039 Adding duplicate parameter names to a :class:`~click.core.Command` will
2040 result in a ``UserWarning`` being shown.
2042 .. versionchanged:: 8.0
2043 ``process_value`` validates required parameters and bounded
2044 ``nargs``, and invokes the parameter callback before returning
2045 the value. This allows the callback to validate prompts.
2046 ``full_process_value`` is removed.
2048 .. versionchanged:: 8.0
2049 ``autocompletion`` is renamed to ``shell_complete`` and has new
2050 semantics described above. The old name is deprecated and will
2051 be removed in 8.1, until then it will be wrapped to match the
2052 new requirements.
2054 .. versionchanged:: 8.0
2055 For ``multiple=True, nargs>1``, the default must be a list of
2056 tuples.
2058 .. versionchanged:: 8.0
2059 Setting a default is no longer required for ``nargs>1``, it will
2060 default to ``None``. ``multiple=True`` or ``nargs=-1`` will
2061 default to ``()``.
2063 .. versionchanged:: 7.1
2064 Empty environment variables are ignored rather than taking the
2065 empty string value. This makes it possible for scripts to clear
2066 variables if they can't unset them.
2068 .. versionchanged:: 2.0
2069 Changed signature for parameter callback to also be passed the
2070 parameter. The old callback format will still work, but it will
2071 raise a warning to give you a chance to migrate the code easier.
2072 """
2074 param_type_name = "parameter"
2076 def __init__(
2077 self,
2078 param_decls: cabc.Sequence[str] | None = None,
2079 type: types.ParamType | t.Any | None = None,
2080 required: bool = False,
2081 default: t.Any | t.Callable[[], t.Any] | None = None,
2082 callback: t.Callable[[Context, Parameter, t.Any], t.Any] | None = None,
2083 nargs: int | None = None,
2084 multiple: bool = False,
2085 metavar: str | None = None,
2086 expose_value: bool = True,
2087 is_eager: bool = False,
2088 envvar: str | cabc.Sequence[str] | None = None,
2089 shell_complete: t.Callable[
2090 [Context, Parameter, str], list[CompletionItem] | list[str]
2091 ]
2092 | None = None,
2093 deprecated: bool | str = False,
2094 ) -> None:
2095 self.name: str | None
2096 self.opts: list[str]
2097 self.secondary_opts: list[str]
2098 self.name, self.opts, self.secondary_opts = self._parse_decls(
2099 param_decls or (), expose_value
2100 )
2101 self.type: types.ParamType = types.convert_type(type, default)
2103 # Default nargs to what the type tells us if we have that
2104 # information available.
2105 if nargs is None:
2106 if self.type.is_composite:
2107 nargs = self.type.arity
2108 else:
2109 nargs = 1
2111 self.required = required
2112 self.callback = callback
2113 self.nargs = nargs
2114 self.multiple = multiple
2115 self.expose_value = expose_value
2116 self.default = default
2117 self.is_eager = is_eager
2118 self.metavar = metavar
2119 self.envvar = envvar
2120 self._custom_shell_complete = shell_complete
2121 self.deprecated = deprecated
2123 if __debug__:
2124 if self.type.is_composite and nargs != self.type.arity:
2125 raise ValueError(
2126 f"'nargs' must be {self.type.arity} (or None) for"
2127 f" type {self.type!r}, but it was {nargs}."
2128 )
2130 # Skip no default or callable default.
2131 check_default = default if not callable(default) else None
2133 if check_default is not None:
2134 if multiple:
2135 try:
2136 # Only check the first value against nargs.
2137 check_default = next(_check_iter(check_default), None)
2138 except TypeError:
2139 raise ValueError(
2140 "'default' must be a list when 'multiple' is true."
2141 ) from None
2143 # Can be None for multiple with empty default.
2144 if nargs != 1 and check_default is not None:
2145 try:
2146 _check_iter(check_default)
2147 except TypeError:
2148 if multiple:
2149 message = (
2150 "'default' must be a list of lists when 'multiple' is"
2151 " true and 'nargs' != 1."
2152 )
2153 else:
2154 message = "'default' must be a list when 'nargs' != 1."
2156 raise ValueError(message) from None
2158 if nargs > 1 and len(check_default) != nargs:
2159 subject = "item length" if multiple else "length"
2160 raise ValueError(
2161 f"'default' {subject} must match nargs={nargs}."
2162 )
2164 if required and deprecated:
2165 raise ValueError(
2166 f"The {self.param_type_name} '{self.human_readable_name}' "
2167 "is deprecated and still required. A deprecated "
2168 f"{self.param_type_name} cannot be required."
2169 )
2171 def to_info_dict(self) -> dict[str, t.Any]:
2172 """Gather information that could be useful for a tool generating
2173 user-facing documentation.
2175 Use :meth:`click.Context.to_info_dict` to traverse the entire
2176 CLI structure.
2178 .. versionadded:: 8.0
2179 """
2180 return {
2181 "name": self.name,
2182 "param_type_name": self.param_type_name,
2183 "opts": self.opts,
2184 "secondary_opts": self.secondary_opts,
2185 "type": self.type.to_info_dict(),
2186 "required": self.required,
2187 "nargs": self.nargs,
2188 "multiple": self.multiple,
2189 "default": self.default,
2190 "envvar": self.envvar,
2191 }
2193 def __repr__(self) -> str:
2194 return f"<{self.__class__.__name__} {self.name}>"
2196 def _parse_decls(
2197 self, decls: cabc.Sequence[str], expose_value: bool
2198 ) -> tuple[str | None, list[str], list[str]]:
2199 raise NotImplementedError()
2201 @property
2202 def human_readable_name(self) -> str:
2203 """Returns the human readable name of this parameter. This is the
2204 same as the name for options, but the metavar for arguments.
2205 """
2206 return self.name # type: ignore
2208 def make_metavar(self, ctx: Context) -> str:
2209 if self.metavar is not None:
2210 return self.metavar
2212 metavar = self.type.get_metavar(param=self, ctx=ctx)
2214 if metavar is None:
2215 metavar = self.type.name.upper()
2217 if self.nargs != 1:
2218 metavar += "..."
2220 return metavar
2222 @t.overload
2223 def get_default(
2224 self, ctx: Context, call: t.Literal[True] = True
2225 ) -> t.Any | None: ...
2227 @t.overload
2228 def get_default(
2229 self, ctx: Context, call: bool = ...
2230 ) -> t.Any | t.Callable[[], t.Any] | None: ...
2232 def get_default(
2233 self, ctx: Context, call: bool = True
2234 ) -> t.Any | t.Callable[[], t.Any] | None:
2235 """Get the default for the parameter. Tries
2236 :meth:`Context.lookup_default` first, then the local default.
2238 :param ctx: Current context.
2239 :param call: If the default is a callable, call it. Disable to
2240 return the callable instead.
2242 .. versionchanged:: 8.0.2
2243 Type casting is no longer performed when getting a default.
2245 .. versionchanged:: 8.0.1
2246 Type casting can fail in resilient parsing mode. Invalid
2247 defaults will not prevent showing help text.
2249 .. versionchanged:: 8.0
2250 Looks at ``ctx.default_map`` first.
2252 .. versionchanged:: 8.0
2253 Added the ``call`` parameter.
2254 """
2255 value = ctx.lookup_default(self.name, call=False) # type: ignore
2257 if value is None:
2258 value = self.default
2260 if call and callable(value):
2261 value = value()
2263 return value
2265 def add_to_parser(self, parser: _OptionParser, ctx: Context) -> None:
2266 raise NotImplementedError()
2268 def consume_value(
2269 self, ctx: Context, opts: cabc.Mapping[str, t.Any]
2270 ) -> tuple[t.Any, ParameterSource]:
2271 value = opts.get(self.name) # type: ignore
2272 source = ParameterSource.COMMANDLINE
2274 if value is None:
2275 value = self.value_from_envvar(ctx)
2276 source = ParameterSource.ENVIRONMENT
2278 if value is None:
2279 value = ctx.lookup_default(self.name) # type: ignore
2280 source = ParameterSource.DEFAULT_MAP
2282 if value is None:
2283 value = self.get_default(ctx)
2284 source = ParameterSource.DEFAULT
2286 return value, source
2288 def type_cast_value(self, ctx: Context, value: t.Any) -> t.Any:
2289 """Convert and validate a value against the option's
2290 :attr:`type`, :attr:`multiple`, and :attr:`nargs`.
2291 """
2292 if value is None:
2293 return () if self.multiple or self.nargs == -1 else None
2295 def check_iter(value: t.Any) -> cabc.Iterator[t.Any]:
2296 try:
2297 return _check_iter(value)
2298 except TypeError:
2299 # This should only happen when passing in args manually,
2300 # the parser should construct an iterable when parsing
2301 # the command line.
2302 raise BadParameter(
2303 _("Value must be an iterable."), ctx=ctx, param=self
2304 ) from None
2306 if self.nargs == 1 or self.type.is_composite:
2308 def convert(value: t.Any) -> t.Any:
2309 return self.type(value, param=self, ctx=ctx)
2311 elif self.nargs == -1:
2313 def convert(value: t.Any) -> t.Any: # tuple[t.Any, ...]
2314 return tuple(self.type(x, self, ctx) for x in check_iter(value))
2316 else: # nargs > 1
2318 def convert(value: t.Any) -> t.Any: # tuple[t.Any, ...]
2319 value = tuple(check_iter(value))
2321 if len(value) != self.nargs:
2322 raise BadParameter(
2323 ngettext(
2324 "Takes {nargs} values but 1 was given.",
2325 "Takes {nargs} values but {len} were given.",
2326 len(value),
2327 ).format(nargs=self.nargs, len=len(value)),
2328 ctx=ctx,
2329 param=self,
2330 )
2332 return tuple(self.type(x, self, ctx) for x in value)
2334 if self.multiple:
2335 return tuple(convert(x) for x in check_iter(value))
2337 return convert(value)
2339 def value_is_missing(self, value: t.Any) -> bool:
2340 if value is None:
2341 return True
2343 if (self.nargs != 1 or self.multiple) and value == ():
2344 return True
2346 return False
2348 def process_value(self, ctx: Context, value: t.Any) -> t.Any:
2349 value = self.type_cast_value(ctx, value)
2351 if self.required and self.value_is_missing(value):
2352 raise MissingParameter(ctx=ctx, param=self)
2354 if self.callback is not None:
2355 value = self.callback(ctx, self, value)
2357 return value
2359 def resolve_envvar_value(self, ctx: Context) -> str | None:
2360 if self.envvar is None:
2361 return None
2363 if isinstance(self.envvar, str):
2364 rv = os.environ.get(self.envvar)
2366 if rv:
2367 return rv
2368 else:
2369 for envvar in self.envvar:
2370 rv = os.environ.get(envvar)
2372 if rv:
2373 return rv
2375 return None
2377 def value_from_envvar(self, ctx: Context) -> t.Any | None:
2378 rv: t.Any | None = self.resolve_envvar_value(ctx)
2380 if rv is not None and self.nargs != 1:
2381 rv = self.type.split_envvar_value(rv)
2383 return rv
2385 def handle_parse_result(
2386 self, ctx: Context, opts: cabc.Mapping[str, t.Any], args: list[str]
2387 ) -> tuple[t.Any, list[str]]:
2388 with augment_usage_errors(ctx, param=self):
2389 value, source = self.consume_value(ctx, opts)
2391 if (
2392 self.deprecated
2393 and value is not None
2394 and source
2395 not in (
2396 ParameterSource.DEFAULT,
2397 ParameterSource.DEFAULT_MAP,
2398 )
2399 ):
2400 extra_message = (
2401 f" {self.deprecated}" if isinstance(self.deprecated, str) else ""
2402 )
2403 message = _(
2404 "DeprecationWarning: The {param_type} {name!r} is deprecated."
2405 "{extra_message}"
2406 ).format(
2407 param_type=self.param_type_name,
2408 name=self.human_readable_name,
2409 extra_message=extra_message,
2410 )
2411 echo(style(message, fg="red"), err=True)
2413 ctx.set_parameter_source(self.name, source) # type: ignore
2415 try:
2416 value = self.process_value(ctx, value)
2417 except Exception:
2418 if not ctx.resilient_parsing:
2419 raise
2421 value = None
2423 if self.expose_value:
2424 ctx.params[self.name] = value # type: ignore
2426 return value, args
2428 def get_help_record(self, ctx: Context) -> tuple[str, str] | None:
2429 pass
2431 def get_usage_pieces(self, ctx: Context) -> list[str]:
2432 return []
2434 def get_error_hint(self, ctx: Context) -> str:
2435 """Get a stringified version of the param for use in error messages to
2436 indicate which param caused the error.
2437 """
2438 hint_list = self.opts or [self.human_readable_name]
2439 return " / ".join(f"'{x}'" for x in hint_list)
2441 def shell_complete(self, ctx: Context, incomplete: str) -> list[CompletionItem]:
2442 """Return a list of completions for the incomplete value. If a
2443 ``shell_complete`` function was given during init, it is used.
2444 Otherwise, the :attr:`type`
2445 :meth:`~click.types.ParamType.shell_complete` function is used.
2447 :param ctx: Invocation context for this command.
2448 :param incomplete: Value being completed. May be empty.
2450 .. versionadded:: 8.0
2451 """
2452 if self._custom_shell_complete is not None:
2453 results = self._custom_shell_complete(ctx, self, incomplete)
2455 if results and isinstance(results[0], str):
2456 from click.shell_completion import CompletionItem
2458 results = [CompletionItem(c) for c in results]
2460 return t.cast("list[CompletionItem]", results)
2462 return self.type.shell_complete(ctx, self, incomplete)
2465class Option(Parameter):
2466 """Options are usually optional values on the command line and
2467 have some extra features that arguments don't have.
2469 All other parameters are passed onwards to the parameter constructor.
2471 :param show_default: Show the default value for this option in its
2472 help text. Values are not shown by default, unless
2473 :attr:`Context.show_default` is ``True``. If this value is a
2474 string, it shows that string in parentheses instead of the
2475 actual value. This is particularly useful for dynamic options.
2476 For single option boolean flags, the default remains hidden if
2477 its value is ``False``.
2478 :param show_envvar: Controls if an environment variable should be
2479 shown on the help page and error messages.
2480 Normally, environment variables are not shown.
2481 :param prompt: If set to ``True`` or a non empty string then the
2482 user will be prompted for input. If set to ``True`` the prompt
2483 will be the option name capitalized. A deprecated option cannot be
2484 prompted.
2485 :param confirmation_prompt: Prompt a second time to confirm the
2486 value if it was prompted for. Can be set to a string instead of
2487 ``True`` to customize the message.
2488 :param prompt_required: If set to ``False``, the user will be
2489 prompted for input only when the option was specified as a flag
2490 without a value.
2491 :param hide_input: If this is ``True`` then the input on the prompt
2492 will be hidden from the user. This is useful for password input.
2493 :param is_flag: forces this option to act as a flag. The default is
2494 auto detection.
2495 :param flag_value: which value should be used for this flag if it's
2496 enabled. This is set to a boolean automatically if
2497 the option string contains a slash to mark two options.
2498 :param multiple: if this is set to `True` then the argument is accepted
2499 multiple times and recorded. This is similar to ``nargs``
2500 in how it works but supports arbitrary number of
2501 arguments.
2502 :param count: this flag makes an option increment an integer.
2503 :param allow_from_autoenv: if this is enabled then the value of this
2504 parameter will be pulled from an environment
2505 variable in case a prefix is defined on the
2506 context.
2507 :param help: the help string.
2508 :param hidden: hide this option from help outputs.
2509 :param attrs: Other command arguments described in :class:`Parameter`.
2511 .. versionchanged:: 8.2
2512 ``envvar`` used with ``flag_value`` will always use the ``flag_value``,
2513 previously it would use the value of the environment variable.
2515 .. versionchanged:: 8.1
2516 Help text indentation is cleaned here instead of only in the
2517 ``@option`` decorator.
2519 .. versionchanged:: 8.1
2520 The ``show_default`` parameter overrides
2521 ``Context.show_default``.
2523 .. versionchanged:: 8.1
2524 The default of a single option boolean flag is not shown if the
2525 default value is ``False``.
2527 .. versionchanged:: 8.0.1
2528 ``type`` is detected from ``flag_value`` if given.
2529 """
2531 param_type_name = "option"
2533 def __init__(
2534 self,
2535 param_decls: cabc.Sequence[str] | None = None,
2536 show_default: bool | str | None = None,
2537 prompt: bool | str = False,
2538 confirmation_prompt: bool | str = False,
2539 prompt_required: bool = True,
2540 hide_input: bool = False,
2541 is_flag: bool | None = None,
2542 flag_value: t.Any | None = None,
2543 multiple: bool = False,
2544 count: bool = False,
2545 allow_from_autoenv: bool = True,
2546 type: types.ParamType | t.Any | None = None,
2547 help: str | None = None,
2548 hidden: bool = False,
2549 show_choices: bool = True,
2550 show_envvar: bool = False,
2551 deprecated: bool | str = False,
2552 **attrs: t.Any,
2553 ) -> None:
2554 if help:
2555 help = inspect.cleandoc(help)
2557 super().__init__(
2558 param_decls, type=type, multiple=multiple, deprecated=deprecated, **attrs
2559 )
2561 if prompt is True:
2562 if self.name is None:
2563 raise TypeError("'name' is required with 'prompt=True'.")
2565 prompt_text: str | None = self.name.replace("_", " ").capitalize()
2566 elif prompt is False:
2567 prompt_text = None
2568 else:
2569 prompt_text = prompt
2571 if deprecated:
2572 deprecated_message = (
2573 f"(DEPRECATED: {deprecated})"
2574 if isinstance(deprecated, str)
2575 else "(DEPRECATED)"
2576 )
2577 help = help + deprecated_message if help is not None else deprecated_message
2579 self.prompt = prompt_text
2580 self.confirmation_prompt = confirmation_prompt
2581 self.prompt_required = prompt_required
2582 self.hide_input = hide_input
2583 self.hidden = hidden
2585 # If prompt is enabled but not required, then the option can be
2586 # used as a flag to indicate using prompt or flag_value.
2587 self._flag_needs_value = self.prompt is not None and not self.prompt_required
2589 if is_flag is None:
2590 # Implicitly a flag because flag_value was set.
2591 if flag_value is not None:
2592 is_flag = True
2593 # Not a flag, but when used as a flag it shows a prompt.
2594 elif self._flag_needs_value:
2595 is_flag = False
2596 # Implicitly a flag because flag options were given.
2597 elif self.secondary_opts:
2598 is_flag = True
2599 elif is_flag is False and not self._flag_needs_value:
2600 # Not a flag, and prompt is not enabled, can be used as a
2601 # flag if flag_value is set.
2602 self._flag_needs_value = flag_value is not None
2604 self.default: t.Any | t.Callable[[], t.Any]
2606 if is_flag:
2607 # Set missing default for flags if not explicitly required or prompted.
2608 if self.default is None and not self.required and not self.prompt:
2609 if multiple:
2610 self.default = ()
2611 else:
2612 self.default = False
2614 if flag_value is None:
2615 # A boolean flag presence in the command line is enough to set
2616 # the value: to the default if it is not blank, or to True
2617 # otherwise.
2618 flag_value = self.default if self.default else True
2620 self.type: types.ParamType
2621 if is_flag and type is None:
2622 # Re-guess the type from the flag value instead of the
2623 # default.
2624 self.type = types.convert_type(None, flag_value)
2626 self.is_flag: bool = bool(is_flag)
2627 self.is_bool_flag: bool = bool(
2628 is_flag and isinstance(self.type, types.BoolParamType)
2629 )
2630 self.flag_value: t.Any = flag_value
2632 # Counting
2633 self.count = count
2634 if count:
2635 if type is None:
2636 self.type = types.IntRange(min=0)
2637 if self.default is None:
2638 self.default = 0
2640 self.allow_from_autoenv = allow_from_autoenv
2641 self.help = help
2642 self.show_default = show_default
2643 self.show_choices = show_choices
2644 self.show_envvar = show_envvar
2646 if __debug__:
2647 if deprecated and prompt:
2648 raise ValueError("`deprecated` options cannot use `prompt`.")
2650 if self.nargs == -1:
2651 raise TypeError("nargs=-1 is not supported for options.")
2653 if self.prompt and self.is_flag and not self.is_bool_flag:
2654 raise TypeError("'prompt' is not valid for non-boolean flag.")
2656 if not self.is_bool_flag and self.secondary_opts:
2657 raise TypeError("Secondary flag is not valid for non-boolean flag.")
2659 if self.is_bool_flag and self.hide_input and self.prompt is not None:
2660 raise TypeError(
2661 "'prompt' with 'hide_input' is not valid for boolean flag."
2662 )
2664 if self.count:
2665 if self.multiple:
2666 raise TypeError("'count' is not valid with 'multiple'.")
2668 if self.is_flag:
2669 raise TypeError("'count' is not valid with 'is_flag'.")
2671 def to_info_dict(self) -> dict[str, t.Any]:
2672 info_dict = super().to_info_dict()
2673 info_dict.update(
2674 help=self.help,
2675 prompt=self.prompt,
2676 is_flag=self.is_flag,
2677 flag_value=self.flag_value,
2678 count=self.count,
2679 hidden=self.hidden,
2680 )
2681 return info_dict
2683 def get_error_hint(self, ctx: Context) -> str:
2684 result = super().get_error_hint(ctx)
2685 if self.show_envvar:
2686 result += f" (env var: '{self.envvar}')"
2687 return result
2689 def _parse_decls(
2690 self, decls: cabc.Sequence[str], expose_value: bool
2691 ) -> tuple[str | None, list[str], list[str]]:
2692 opts = []
2693 secondary_opts = []
2694 name = None
2695 possible_names = []
2697 for decl in decls:
2698 if decl.isidentifier():
2699 if name is not None:
2700 raise TypeError(f"Name '{name}' defined twice")
2701 name = decl
2702 else:
2703 split_char = ";" if decl[:1] == "/" else "/"
2704 if split_char in decl:
2705 first, second = decl.split(split_char, 1)
2706 first = first.rstrip()
2707 if first:
2708 possible_names.append(_split_opt(first))
2709 opts.append(first)
2710 second = second.lstrip()
2711 if second:
2712 secondary_opts.append(second.lstrip())
2713 if first == second:
2714 raise ValueError(
2715 f"Boolean option {decl!r} cannot use the"
2716 " same flag for true/false."
2717 )
2718 else:
2719 possible_names.append(_split_opt(decl))
2720 opts.append(decl)
2722 if name is None and possible_names:
2723 possible_names.sort(key=lambda x: -len(x[0])) # group long options first
2724 name = possible_names[0][1].replace("-", "_").lower()
2725 if not name.isidentifier():
2726 name = None
2728 if name is None:
2729 if not expose_value:
2730 return None, opts, secondary_opts
2731 raise TypeError(
2732 f"Could not determine name for option with declarations {decls!r}"
2733 )
2735 if not opts and not secondary_opts:
2736 raise TypeError(
2737 f"No options defined but a name was passed ({name})."
2738 " Did you mean to declare an argument instead? Did"
2739 f" you mean to pass '--{name}'?"
2740 )
2742 return name, opts, secondary_opts
2744 def add_to_parser(self, parser: _OptionParser, ctx: Context) -> None:
2745 if self.multiple:
2746 action = "append"
2747 elif self.count:
2748 action = "count"
2749 else:
2750 action = "store"
2752 if self.is_flag:
2753 action = f"{action}_const"
2755 if self.is_bool_flag and self.secondary_opts:
2756 parser.add_option(
2757 obj=self, opts=self.opts, dest=self.name, action=action, const=True
2758 )
2759 parser.add_option(
2760 obj=self,
2761 opts=self.secondary_opts,
2762 dest=self.name,
2763 action=action,
2764 const=False,
2765 )
2766 else:
2767 parser.add_option(
2768 obj=self,
2769 opts=self.opts,
2770 dest=self.name,
2771 action=action,
2772 const=self.flag_value,
2773 )
2774 else:
2775 parser.add_option(
2776 obj=self,
2777 opts=self.opts,
2778 dest=self.name,
2779 action=action,
2780 nargs=self.nargs,
2781 )
2783 def get_help_record(self, ctx: Context) -> tuple[str, str] | None:
2784 if self.hidden:
2785 return None
2787 any_prefix_is_slash = False
2789 def _write_opts(opts: cabc.Sequence[str]) -> str:
2790 nonlocal any_prefix_is_slash
2792 rv, any_slashes = join_options(opts)
2794 if any_slashes:
2795 any_prefix_is_slash = True
2797 if not self.is_flag and not self.count:
2798 rv += f" {self.make_metavar(ctx=ctx)}"
2800 return rv
2802 rv = [_write_opts(self.opts)]
2804 if self.secondary_opts:
2805 rv.append(_write_opts(self.secondary_opts))
2807 help = self.help or ""
2809 extra = self.get_help_extra(ctx)
2810 extra_items = []
2811 if "envvars" in extra:
2812 extra_items.append(
2813 _("env var: {var}").format(var=", ".join(extra["envvars"]))
2814 )
2815 if "default" in extra:
2816 extra_items.append(_("default: {default}").format(default=extra["default"]))
2817 if "range" in extra:
2818 extra_items.append(extra["range"])
2819 if "required" in extra:
2820 extra_items.append(_(extra["required"]))
2822 if extra_items:
2823 extra_str = "; ".join(extra_items)
2824 help = f"{help} [{extra_str}]" if help else f"[{extra_str}]"
2826 return ("; " if any_prefix_is_slash else " / ").join(rv), help
2828 def get_help_extra(self, ctx: Context) -> types.OptionHelpExtra:
2829 extra: types.OptionHelpExtra = {}
2831 if self.show_envvar:
2832 envvar = self.envvar
2834 if envvar is None:
2835 if (
2836 self.allow_from_autoenv
2837 and ctx.auto_envvar_prefix is not None
2838 and self.name is not None
2839 ):
2840 envvar = f"{ctx.auto_envvar_prefix}_{self.name.upper()}"
2842 if envvar is not None:
2843 if isinstance(envvar, str):
2844 extra["envvars"] = (envvar,)
2845 else:
2846 extra["envvars"] = tuple(str(d) for d in envvar)
2848 # Temporarily enable resilient parsing to avoid type casting
2849 # failing for the default. Might be possible to extend this to
2850 # help formatting in general.
2851 resilient = ctx.resilient_parsing
2852 ctx.resilient_parsing = True
2854 try:
2855 default_value = self.get_default(ctx, call=False)
2856 finally:
2857 ctx.resilient_parsing = resilient
2859 show_default = False
2860 show_default_is_str = False
2862 if self.show_default is not None:
2863 if isinstance(self.show_default, str):
2864 show_default_is_str = show_default = True
2865 else:
2866 show_default = self.show_default
2867 elif ctx.show_default is not None:
2868 show_default = ctx.show_default
2870 if show_default_is_str or (show_default and (default_value is not None)):
2871 if show_default_is_str:
2872 default_string = f"({self.show_default})"
2873 elif isinstance(default_value, (list, tuple)):
2874 default_string = ", ".join(str(d) for d in default_value)
2875 elif inspect.isfunction(default_value):
2876 default_string = _("(dynamic)")
2877 elif self.is_bool_flag and self.secondary_opts:
2878 # For boolean flags that have distinct True/False opts,
2879 # use the opt without prefix instead of the value.
2880 default_string = _split_opt(
2881 (self.opts if default_value else self.secondary_opts)[0]
2882 )[1]
2883 elif self.is_bool_flag and not self.secondary_opts and not default_value:
2884 default_string = ""
2885 elif default_value == "":
2886 default_string = '""'
2887 else:
2888 default_string = str(default_value)
2890 if default_string:
2891 extra["default"] = default_string
2893 if (
2894 isinstance(self.type, types._NumberRangeBase)
2895 # skip count with default range type
2896 and not (self.count and self.type.min == 0 and self.type.max is None)
2897 ):
2898 range_str = self.type._describe_range()
2900 if range_str:
2901 extra["range"] = range_str
2903 if self.required:
2904 extra["required"] = "required"
2906 return extra
2908 @t.overload
2909 def get_default(
2910 self, ctx: Context, call: t.Literal[True] = True
2911 ) -> t.Any | None: ...
2913 @t.overload
2914 def get_default(
2915 self, ctx: Context, call: bool = ...
2916 ) -> t.Any | t.Callable[[], t.Any] | None: ...
2918 def get_default(
2919 self, ctx: Context, call: bool = True
2920 ) -> t.Any | t.Callable[[], t.Any] | None:
2921 # If we're a non boolean flag our default is more complex because
2922 # we need to look at all flags in the same group to figure out
2923 # if we're the default one in which case we return the flag
2924 # value as default.
2925 if self.is_flag and not self.is_bool_flag:
2926 for param in ctx.command.params:
2927 if param.name == self.name and param.default is not None:
2928 return t.cast(Option, param).default
2930 return None
2932 return super().get_default(ctx, call=call)
2934 def prompt_for_value(self, ctx: Context) -> t.Any:
2935 """This is an alternative flow that can be activated in the full
2936 value processing if a value does not exist. It will prompt the
2937 user until a valid value exists and then returns the processed
2938 value as result.
2939 """
2940 assert self.prompt is not None
2942 # Calculate the default before prompting anything to be stable.
2943 default = self.get_default(ctx)
2945 # If this is a prompt for a flag we need to handle this
2946 # differently.
2947 if self.is_bool_flag:
2948 return confirm(self.prompt, default)
2950 # If show_default is set to True/False, provide this to `prompt` as well. For
2951 # non-bool values of `show_default`, we use `prompt`'s default behavior
2952 prompt_kwargs: t.Any = {}
2953 if isinstance(self.show_default, bool):
2954 prompt_kwargs["show_default"] = self.show_default
2956 return prompt(
2957 self.prompt,
2958 default=default,
2959 type=self.type,
2960 hide_input=self.hide_input,
2961 show_choices=self.show_choices,
2962 confirmation_prompt=self.confirmation_prompt,
2963 value_proc=lambda x: self.process_value(ctx, x),
2964 **prompt_kwargs,
2965 )
2967 def resolve_envvar_value(self, ctx: Context) -> str | None:
2968 """Find which environment variable to read for this option and return
2969 its value.
2971 Returns the value of the environment variable if it exists, or ``None``
2972 if it does not.
2974 .. caution::
2976 The raw value extracted from the environment is not normalized and
2977 is returned as-is. Any normalization or reconciation with the
2978 option's type should happen later.
2979 """
2980 rv = super().resolve_envvar_value(ctx)
2982 if rv is not None:
2983 return rv
2985 if (
2986 self.allow_from_autoenv
2987 and ctx.auto_envvar_prefix is not None
2988 and self.name is not None
2989 ):
2990 envvar = f"{ctx.auto_envvar_prefix}_{self.name.upper()}"
2991 rv = os.environ.get(envvar)
2993 if rv:
2994 return rv
2996 return None
2998 def value_from_envvar(self, ctx: Context) -> t.Any | None:
2999 """Normalize the value from the environment variable, if it exists."""
3000 rv: str | None = self.resolve_envvar_value(ctx)
3002 if rv is None:
3003 return None
3005 # Non-boolean flags are more liberal in what they accept. But a flag being a
3006 # flag, its envvar value still needs to analyzed to determine if the flag is
3007 # activated or not.
3008 if self.is_flag and not self.is_bool_flag:
3009 # If the flag_value is set and match the envvar value, return it
3010 # directly.
3011 if self.flag_value is not None and rv == self.flag_value:
3012 return self.flag_value
3013 # Analyze the envvar value as a boolean to know if the flag is
3014 # activated or not.
3015 return types.BoolParamType.str_to_bool(rv)
3017 # Split the envvar value if it is allowed to be repeated.
3018 value_depth = (self.nargs != 1) + bool(self.multiple)
3019 if value_depth > 0:
3020 multi_rv = self.type.split_envvar_value(rv)
3021 if self.multiple and self.nargs != 1:
3022 multi_rv = batch(multi_rv, self.nargs) # type: ignore[assignment]
3024 return multi_rv
3026 return rv
3028 def consume_value(
3029 self, ctx: Context, opts: cabc.Mapping[str, Parameter]
3030 ) -> tuple[t.Any, ParameterSource]:
3031 value, source = super().consume_value(ctx, opts)
3033 # The parser will emit a sentinel value if the option can be
3034 # given as a flag without a value. This is different from None
3035 # to distinguish from the flag not being given at all.
3036 if value is _flag_needs_value:
3037 if self.prompt is not None and not ctx.resilient_parsing:
3038 value = self.prompt_for_value(ctx)
3039 source = ParameterSource.PROMPT
3040 else:
3041 value = self.flag_value
3042 source = ParameterSource.COMMANDLINE
3044 # A flag which is activated and has a flag_value set, should returns
3045 # the latter, unless the value comes from the explicitly sets default.
3046 elif (
3047 self.is_flag
3048 and value is True
3049 and not self.is_bool_flag
3050 and self.flag_value is not None
3051 and source is not ParameterSource.DEFAULT
3052 ):
3053 value = self.flag_value
3055 elif (
3056 self.multiple
3057 and value is not None
3058 and any(v is _flag_needs_value for v in value)
3059 ):
3060 value = [self.flag_value if v is _flag_needs_value else v for v in value]
3061 source = ParameterSource.COMMANDLINE
3063 # The value wasn't set, or used the param's default, prompt if
3064 # prompting is enabled.
3065 elif (
3066 source in {None, ParameterSource.DEFAULT}
3067 and self.prompt is not None
3068 and (self.required or self.prompt_required)
3069 and not ctx.resilient_parsing
3070 ):
3071 value = self.prompt_for_value(ctx)
3072 source = ParameterSource.PROMPT
3074 return value, source
3077class Argument(Parameter):
3078 """Arguments are positional parameters to a command. They generally
3079 provide fewer features than options but can have infinite ``nargs``
3080 and are required by default.
3082 All parameters are passed onwards to the constructor of :class:`Parameter`.
3083 """
3085 param_type_name = "argument"
3087 def __init__(
3088 self,
3089 param_decls: cabc.Sequence[str],
3090 required: bool | None = None,
3091 **attrs: t.Any,
3092 ) -> None:
3093 if required is None:
3094 if attrs.get("default") is not None:
3095 required = False
3096 else:
3097 required = attrs.get("nargs", 1) > 0
3099 if "multiple" in attrs:
3100 raise TypeError("__init__() got an unexpected keyword argument 'multiple'.")
3102 super().__init__(param_decls, required=required, **attrs)
3104 if __debug__:
3105 if self.default is not None and self.nargs == -1:
3106 raise TypeError("'default' is not supported for nargs=-1.")
3108 @property
3109 def human_readable_name(self) -> str:
3110 if self.metavar is not None:
3111 return self.metavar
3112 return self.name.upper() # type: ignore
3114 def make_metavar(self, ctx: Context) -> str:
3115 if self.metavar is not None:
3116 return self.metavar
3117 var = self.type.get_metavar(param=self, ctx=ctx)
3118 if not var:
3119 var = self.name.upper() # type: ignore
3120 if self.deprecated:
3121 var += "!"
3122 if not self.required:
3123 var = f"[{var}]"
3124 if self.nargs != 1:
3125 var += "..."
3126 return var
3128 def _parse_decls(
3129 self, decls: cabc.Sequence[str], expose_value: bool
3130 ) -> tuple[str | None, list[str], list[str]]:
3131 if not decls:
3132 if not expose_value:
3133 return None, [], []
3134 raise TypeError("Argument is marked as exposed, but does not have a name.")
3135 if len(decls) == 1:
3136 name = arg = decls[0]
3137 name = name.replace("-", "_").lower()
3138 else:
3139 raise TypeError(
3140 "Arguments take exactly one parameter declaration, got"
3141 f" {len(decls)}: {decls}."
3142 )
3143 return name, [arg], []
3145 def get_usage_pieces(self, ctx: Context) -> list[str]:
3146 return [self.make_metavar(ctx)]
3148 def get_error_hint(self, ctx: Context) -> str:
3149 return f"'{self.make_metavar(ctx)}'"
3151 def add_to_parser(self, parser: _OptionParser, ctx: Context) -> None:
3152 parser.add_argument(dest=self.name, nargs=self.nargs, obj=self)
3155def __getattr__(name: str) -> object:
3156 import warnings
3158 if name == "BaseCommand":
3159 warnings.warn(
3160 "'BaseCommand' is deprecated and will be removed in Click 9.0. Use"
3161 " 'Command' instead.",
3162 DeprecationWarning,
3163 stacklevel=2,
3164 )
3165 return _BaseCommand
3167 if name == "MultiCommand":
3168 warnings.warn(
3169 "'MultiCommand' is deprecated and will be removed in Click 9.0. Use"
3170 " 'Group' instead.",
3171 DeprecationWarning,
3172 stacklevel=2,
3173 )
3174 return _MultiCommand
3176 raise AttributeError(name)