Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/click/core.py: 31%
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 abc import ABC
11from abc import abstractmethod
12from collections import abc
13from collections import Counter
14from contextlib import AbstractContextManager
15from contextlib import contextmanager
16from contextlib import ExitStack
17from functools import update_wrapper
18from gettext import gettext as _
19from gettext import ngettext
20from itertools import repeat
21from types import TracebackType
23from . import types
24from ._utils import FLAG_NEEDS_VALUE
25from ._utils import UNSET
26from .exceptions import Abort
27from .exceptions import BadParameter
28from .exceptions import ClickException
29from .exceptions import Exit
30from .exceptions import MissingParameter
31from .exceptions import NoArgsIsHelpError
32from .exceptions import NoSuchCommand
33from .exceptions import UsageError
34from .formatting import HelpFormatter
35from .formatting import join_options
36from .globals import pop_context
37from .globals import push_context
38from .parser import _OptionParser
39from .parser import _split_opt
40from .termui import confirm
41from .termui import prompt
42from .termui import style
43from .utils import _detect_program_name
44from .utils import _expand_args
45from .utils import _make_default_short_help
46from .utils import _PacifyFlushWrapper
47from .utils import echo
48from .utils import make_str
50if t.TYPE_CHECKING:
51 from typing_extensions import Self
53 from .shell_completion import CompletionItem
55F = t.TypeVar("F", bound="t.Callable[..., t.Any]")
56V = t.TypeVar("V")
58# Reserved storage name of the automatic help option. No user parameter is
59# expected to claim it.
60_HELP_OPTION_STORAGE_NAME = "_click_default_help"
63def _complete_visible_commands(
64 ctx: Context, incomplete: str
65) -> cabc.Iterator[tuple[str, Command]]:
66 """List all the subcommands of a group that start with the
67 incomplete value and aren't hidden.
69 :param ctx: Invocation context for the group.
70 :param incomplete: Value being completed. May be empty.
71 """
72 multi = t.cast(Group, ctx.command)
74 for name in multi.list_commands(ctx):
75 if name.startswith(incomplete):
76 command = multi.get_command(ctx, name)
78 if command is not None and not command.hidden:
79 yield name, command
82def _check_nested_chain(
83 base_command: Group, cmd_name: str, cmd: Command, register: bool = False
84) -> None:
85 if not base_command.chain or not isinstance(cmd, Group):
86 return
88 if register:
89 message = (
90 f"It is not possible to add the group {cmd_name!r} to another"
91 f" group {base_command.name!r} that is in chain mode."
92 )
93 else:
94 message = (
95 f"Found the group {cmd_name!r} as subcommand to another group "
96 f" {base_command.name!r} that is in chain mode. This is not supported."
97 )
99 raise RuntimeError(message)
102def _echo_aborted() -> None:
103 """Write the final abort message to standard error."""
104 echo(_("Aborted!"), file=sys.stderr)
107def _format_deprecated_label(deprecated: bool | str) -> str:
108 """Return the parenthesized deprecation label shown in help text."""
109 label = _("deprecated").upper()
110 if isinstance(deprecated, str):
111 return f"({label}: {deprecated})"
112 return f"({label})"
115def _format_deprecated_suffix(deprecated: bool | str) -> str:
116 """Return the trailing reason for a ``DeprecationWarning`` message,
117 prefixed with a space, or an empty string when no reason was given.
118 """
119 if isinstance(deprecated, str):
120 return f" {deprecated}"
121 return ""
124def batch(iterable: cabc.Iterable[V], batch_size: int) -> list[tuple[V, ...]]:
125 return list(zip(*repeat(iter(iterable), batch_size), strict=False))
128@contextmanager
129def augment_usage_errors(
130 ctx: Context, param: Parameter | None = None
131) -> cabc.Generator[None]:
132 """Context manager that attaches extra information to exceptions."""
133 try:
134 yield
135 except BadParameter as e:
136 if e.ctx is None:
137 e.ctx = ctx
138 if param is not None and e.param is None:
139 e.param = param
140 raise
141 except UsageError as e:
142 if e.ctx is None:
143 e.ctx = ctx
144 raise
147def iter_params_for_processing(
148 invocation_order: cabc.Sequence[Parameter],
149 declaration_order: cabc.Sequence[Parameter],
150) -> list[Parameter]:
151 """Returns all declared parameters in the order they should be processed.
153 The declared parameters are re-shuffled depending on the order in which
154 they were invoked, as well as the eagerness of each parameters.
156 The invocation order takes precedence over the declaration order. I.e. the
157 order in which the user provided them to the CLI is respected.
159 This behavior and its effect on callback evaluation is detailed at:
160 https://click.palletsprojects.com/en/stable/advanced/#callback-evaluation-order
161 """
163 def sort_key(item: Parameter) -> tuple[bool, float]:
164 try:
165 idx: float = invocation_order.index(item)
166 except ValueError:
167 idx = float("inf")
169 return not item.is_eager, idx
171 return sorted(declaration_order, key=sort_key)
174class ParameterSource(enum.IntEnum):
175 """This is an :class:`~enum.IntEnum` that indicates the source of a
176 parameter's value.
178 Use :meth:`click.Context.get_parameter_source` to get the
179 source for a parameter by name.
181 Members are ordered from most explicit to least explicit source.
182 This allows comparison to check if a value was explicitly provided:
184 .. code-block:: python
186 source = ctx.get_parameter_source("port")
187 if source < click.ParameterSource.DEFAULT_MAP:
188 ... # value was explicitly set
190 .. versionchanged:: 8.3.3
191 Use :class:`~enum.IntEnum` and reorder members from most to
192 least explicit. Supports comparison operators.
194 .. versionchanged:: 8.0
195 Use :class:`~enum.Enum` and drop the ``validate`` method.
197 .. versionchanged:: 8.0
198 Added the ``PROMPT`` value.
199 """
201 PROMPT = enum.auto()
202 """Used a prompt to confirm a default or provide a value."""
203 COMMANDLINE = enum.auto()
204 """The value was provided by the command line args."""
205 ENVIRONMENT = enum.auto()
206 """The value was provided with an environment variable."""
207 DEFAULT_MAP = enum.auto()
208 """Used a default provided by :attr:`Context.default_map`."""
209 DEFAULT = enum.auto()
210 """Used the default specified by the parameter."""
213class Context:
214 """The context is a special internal object that holds state relevant
215 for the script execution at every single level. It's normally invisible
216 to commands unless they opt-in to getting access to it.
218 The context is useful as it can pass internal objects around and can
219 control special execution features such as reading data from
220 environment variables.
222 A context can be used as context manager in which case it will call
223 :meth:`close` on teardown.
225 :param command: the command class for this context.
226 :param parent: the parent context.
227 :param info_name: the info name for this invocation. Generally this
228 is the most descriptive name for the script or
229 command. For the toplevel script it is usually
230 the name of the script, for commands below that it's
231 the name of the script.
232 :param obj: an arbitrary object of user data.
233 :param auto_envvar_prefix: the prefix to use for automatic environment
234 variables. If this is `None` then reading
235 from environment variables is disabled. This
236 does not affect manually set environment
237 variables which are always read.
238 :param default_map: a dictionary (like object) with default values
239 for parameters.
240 :param terminal_width: the width of the terminal. The default is
241 inherit from parent context. If no context
242 defines the terminal width then auto
243 detection will be applied.
244 :param max_content_width: the maximum width for content rendered by
245 Click (this currently only affects help
246 pages). This defaults to 80 characters if
247 not overridden. In other words: even if the
248 terminal is larger than that, Click will not
249 format things wider than 80 characters by
250 default. In addition to that, formatters might
251 add some safety mapping on the right.
252 :param resilient_parsing: if this flag is enabled then Click will
253 parse without any interactivity or callback
254 invocation. Default values will also be
255 ignored. This is useful for implementing
256 things such as completion support.
257 :param allow_extra_args: if this is set to `True` then extra arguments
258 at the end will not raise an error and will be
259 kept on the context. The default is to inherit
260 from the command.
261 :param allow_interspersed_args: if this is set to `False` then options
262 and arguments cannot be mixed. The
263 default is to inherit from the command.
264 :param ignore_unknown_options: instructs click to ignore options it does
265 not know and keeps them for later
266 processing.
267 :param help_option_names: optionally a list of strings that define how
268 the default help parameter is named. The
269 default is ``['--help']``.
270 :param token_normalize_func: an optional function that is used to
271 normalize tokens (options, choices,
272 etc.). This for instance can be used to
273 implement case insensitive behavior.
274 :param color: controls if the terminal supports ANSI colors or not. The
275 default is autodetection. This is only needed if ANSI
276 codes are used in texts that Click prints which is by
277 default not the case. This for instance would affect
278 help output.
279 :param show_default: Show the default value for commands. If this
280 value is not set, it defaults to the value from the parent
281 context. ``Command.show_default`` overrides this default for the
282 specific command.
284 .. versionchanged:: 8.2
285 The ``protected_args`` attribute is deprecated and will be removed in
286 Click 9.0. ``args`` will contain remaining unparsed tokens.
288 .. versionchanged:: 8.1
289 The ``show_default`` parameter is overridden by
290 ``Command.show_default``, instead of the other way around.
292 .. versionchanged:: 8.0
293 The ``show_default`` parameter defaults to the value from the
294 parent context.
296 .. versionchanged:: 7.1
297 Added the ``show_default`` parameter.
299 .. versionchanged:: 4.0
300 Added the ``color``, ``ignore_unknown_options``, and
301 ``max_content_width`` parameters.
303 .. versionchanged:: 3.0
304 Added the ``allow_extra_args`` and ``allow_interspersed_args``
305 parameters.
307 .. versionchanged:: 2.0
308 Added the ``resilient_parsing``, ``help_option_names``, and
309 ``token_normalize_func`` parameters.
310 """
312 #: The formatter class to create with :meth:`make_formatter`.
313 #:
314 #: .. versionadded:: 8.0
315 formatter_class: type[HelpFormatter] = HelpFormatter
317 parent: Context | None
318 command: Command
319 info_name: str | None
320 params: dict[str, t.Any]
321 args: list[str]
322 _protected_args: list[str]
323 _opt_prefixes: set[str]
324 obj: t.Any
325 _meta: dict[str, t.Any]
326 default_map: cabc.MutableMapping[str, t.Any] | None
327 invoked_subcommand: str | None
328 terminal_width: int | None
329 max_content_width: int | None
330 allow_extra_args: bool
331 allow_interspersed_args: bool
332 ignore_unknown_options: bool
333 help_option_names: list[str]
334 token_normalize_func: t.Callable[[str], str] | None
335 resilient_parsing: bool
336 auto_envvar_prefix: str | None
337 color: bool | None
338 show_default: bool | None
339 _close_callbacks: list[t.Callable[[], t.Any]]
340 _depth: int
341 _parameter_source: dict[str, ParameterSource]
342 _param_default_explicit: dict[str, bool]
343 _exit_stack: ExitStack
345 def __init__(
346 self,
347 command: Command,
348 parent: Context | None = None,
349 info_name: str | None = None,
350 obj: t.Any | None = None,
351 auto_envvar_prefix: str | None = None,
352 default_map: cabc.MutableMapping[str, t.Any] | None = None,
353 terminal_width: int | None = None,
354 max_content_width: int | None = None,
355 resilient_parsing: bool = False,
356 allow_extra_args: bool | None = None,
357 allow_interspersed_args: bool | None = None,
358 ignore_unknown_options: bool | None = None,
359 help_option_names: list[str] | None = None,
360 token_normalize_func: t.Callable[[str], str] | None = None,
361 color: bool | None = None,
362 show_default: bool | None = None,
363 ) -> None:
364 #: the parent context or `None` if none exists.
365 self.parent = parent
366 #: the :class:`Command` for this context.
367 self.command = command
368 #: the descriptive information name
369 self.info_name = info_name
370 #: Map of parameter names to their parsed values. Parameters
371 #: with ``expose_value=False`` are not stored.
372 self.params = {}
373 #: the leftover arguments.
374 self.args = []
375 #: protected arguments. These are arguments that are prepended
376 #: to `args` when certain parsing scenarios are encountered but
377 #: must be never propagated to another arguments. This is used
378 #: to implement nested parsing.
379 self._protected_args = []
380 #: the collected prefixes of the command's options.
381 self._opt_prefixes = set(parent._opt_prefixes) if parent else set()
383 if obj is None and parent is not None:
384 obj = parent.obj
386 #: the user object stored.
387 self.obj = obj
388 self._meta = getattr(parent, "meta", {})
390 #: A dictionary (-like object) with defaults for parameters.
391 if (
392 default_map is None
393 and info_name is not None
394 and parent is not None
395 and parent.default_map is not None
396 ):
397 default_map = parent.default_map.get(info_name)
399 self.default_map = default_map
401 #: This flag indicates if a subcommand is going to be executed. A
402 #: group callback can use this information to figure out if it's
403 #: being executed directly or because the execution flow passes
404 #: onwards to a subcommand. By default it's None, but it can be
405 #: the name of the subcommand to execute.
406 #:
407 #: If chaining is enabled this will be set to ``'*'`` in case
408 #: any commands are executed. It is however not possible to
409 #: figure out which ones. If you require this knowledge you
410 #: should use a :func:`result_callback`.
411 self.invoked_subcommand = None
413 if terminal_width is None and parent is not None:
414 terminal_width = parent.terminal_width
416 #: The width of the terminal (None is autodetection).
417 self.terminal_width = terminal_width
419 if max_content_width is None and parent is not None:
420 max_content_width = parent.max_content_width
422 #: The maximum width of formatted content (None implies a sensible
423 #: default which is 80 for most things).
424 self.max_content_width = max_content_width
426 if allow_extra_args is None:
427 allow_extra_args = command.allow_extra_args
429 #: Indicates if the context allows extra args or if it should
430 #: fail on parsing.
431 #:
432 #: .. versionadded:: 3.0
433 self.allow_extra_args = allow_extra_args
435 if allow_interspersed_args is None:
436 allow_interspersed_args = command.allow_interspersed_args
438 #: Indicates if the context allows mixing of arguments and
439 #: options or not.
440 #:
441 #: .. versionadded:: 3.0
442 self.allow_interspersed_args = allow_interspersed_args
444 if ignore_unknown_options is None:
445 ignore_unknown_options = command.ignore_unknown_options
447 #: Instructs click to ignore options that a command does not
448 #: understand and will store it on the context for later
449 #: processing. This is primarily useful for situations where you
450 #: want to call into external programs. Generally this pattern is
451 #: strongly discouraged because it's not possibly to losslessly
452 #: forward all arguments.
453 #:
454 #: .. versionadded:: 4.0
455 self.ignore_unknown_options = ignore_unknown_options
457 if help_option_names is None:
458 if parent is not None:
459 help_option_names = parent.help_option_names
460 else:
461 help_option_names = ["--help"]
463 #: The names for the help options.
464 self.help_option_names = help_option_names
466 if token_normalize_func is None and parent is not None:
467 token_normalize_func = parent.token_normalize_func
469 #: An optional normalization function for tokens. This is
470 #: options, choices, commands etc.
471 self.token_normalize_func = token_normalize_func
473 #: Indicates if resilient parsing is enabled. In that case Click
474 #: will do its best to not cause any failures and default values
475 #: will be ignored. Useful for completion.
476 self.resilient_parsing = resilient_parsing
478 # If there is no envvar prefix yet, but the parent has one and
479 # the command on this level has a name, we can expand the envvar
480 # prefix automatically.
481 if auto_envvar_prefix is None:
482 if (
483 parent is not None
484 and parent.auto_envvar_prefix is not None
485 and self.info_name is not None
486 ):
487 auto_envvar_prefix = (
488 f"{parent.auto_envvar_prefix}_{self.info_name.upper()}"
489 )
490 else:
491 auto_envvar_prefix = auto_envvar_prefix.upper()
493 if auto_envvar_prefix is not None:
494 auto_envvar_prefix = auto_envvar_prefix.replace("-", "_")
496 self.auto_envvar_prefix = auto_envvar_prefix
498 if color is None and parent is not None:
499 color = parent.color
501 #: Controls if styling output is wanted or not.
502 self.color = color
504 if show_default is None and parent is not None:
505 show_default = parent.show_default
507 #: Show option default values when formatting help text.
508 self.show_default = show_default
510 self._close_callbacks = []
511 self._depth = 0
512 self._parameter_source = {}
513 # Tracks whether the option that currently owns each parameter slot in
514 # :attr:`params` had its ``default`` set explicitly by the user. Used to
515 # tie-break feature-switch groups where multiple options share a parameter name
516 # and both fall back to their default value.
517 self._param_default_explicit = {}
518 self._exit_stack = ExitStack()
520 @property
521 def protected_args(self) -> list[str]:
522 import warnings
524 warnings.warn(
525 "'protected_args' is deprecated and will be removed in Click 9.0."
526 " 'args' will contain remaining unparsed tokens.",
527 DeprecationWarning,
528 stacklevel=2,
529 )
530 return self._protected_args
532 def to_info_dict(self) -> dict[str, t.Any]:
533 """Gather information that could be useful for a tool generating
534 user-facing documentation. This traverses the entire CLI
535 structure.
537 .. code-block:: python
539 with Context(cli) as ctx:
540 info = ctx.to_info_dict()
542 .. versionadded:: 8.0
543 """
544 return {
545 "command": self.command.to_info_dict(self),
546 "info_name": self.info_name,
547 "allow_extra_args": self.allow_extra_args,
548 "allow_interspersed_args": self.allow_interspersed_args,
549 "ignore_unknown_options": self.ignore_unknown_options,
550 "auto_envvar_prefix": self.auto_envvar_prefix,
551 }
553 def __enter__(self) -> Self:
554 self._depth += 1
555 push_context(self)
556 return self
558 def __exit__(
559 self,
560 exc_type: type[BaseException] | None,
561 exc_value: BaseException | None,
562 tb: TracebackType | None,
563 ) -> bool | None:
564 self._depth -= 1
565 exit_result: bool | None = None
566 if self._depth == 0:
567 exit_result = self._close_with_exception_info(exc_type, exc_value, tb)
568 pop_context()
570 return exit_result
572 @contextmanager
573 def scope(self, cleanup: bool = True) -> cabc.Generator[Context]:
574 """This helper method can be used with the context object to promote
575 it to the current thread local (see :func:`get_current_context`).
576 The default behavior of this is to invoke the cleanup functions which
577 can be disabled by setting `cleanup` to `False`. The cleanup
578 functions are typically used for things such as closing file handles.
580 If the cleanup is intended the context object can also be directly
581 used as a context manager.
583 Example usage::
585 with ctx.scope():
586 assert get_current_context() is ctx
588 This is equivalent::
590 with ctx:
591 assert get_current_context() is ctx
593 .. versionadded:: 5.0
595 :param cleanup: controls if the cleanup functions should be run or
596 not. The default is to run these functions. In
597 some situations the context only wants to be
598 temporarily pushed in which case this can be disabled.
599 Nested pushes automatically defer the cleanup.
600 """
601 if not cleanup:
602 self._depth += 1
603 try:
604 with self as rv:
605 yield rv
606 finally:
607 if not cleanup:
608 self._depth -= 1
610 @property
611 def meta(self) -> dict[str, t.Any]:
612 """This is a dictionary which is shared with all the contexts
613 that are nested. It exists so that click utilities can store some
614 state here if they need to. It is however the responsibility of
615 that code to manage this dictionary well.
617 The keys are supposed to be unique dotted strings. For instance
618 module paths are a good choice for it. What is stored in there is
619 irrelevant for the operation of click. However what is important is
620 that code that places data here adheres to the general semantics of
621 the system.
623 Example usage::
625 LANG_KEY = f'{__name__}.lang'
627 def set_language(value):
628 ctx = get_current_context()
629 ctx.meta[LANG_KEY] = value
631 def get_language():
632 return get_current_context().meta.get(LANG_KEY, 'en_US')
634 .. versionadded:: 5.0
635 """
636 return self._meta
638 def make_formatter(self) -> HelpFormatter:
639 """Creates the :class:`~click.HelpFormatter` for the help and
640 usage output.
642 To quickly customize the formatter class used without overriding
643 this method, set the :attr:`formatter_class` attribute.
645 .. versionchanged:: 8.0
646 Added the :attr:`formatter_class` attribute.
647 """
648 return self.formatter_class(
649 width=self.terminal_width, max_width=self.max_content_width
650 )
652 def with_resource(self, context_manager: AbstractContextManager[V]) -> V:
653 """Register a resource as if it were used in a ``with``
654 statement. The resource will be cleaned up when the context is
655 popped.
657 Uses :meth:`contextlib.ExitStack.enter_context`. It calls the
658 resource's ``__enter__()`` method and returns the result. When
659 the context is popped, it closes the stack, which calls the
660 resource's ``__exit__()`` method.
662 To register a cleanup function for something that isn't a
663 context manager, use :meth:`call_on_close`. Or use something
664 from :mod:`contextlib` to turn it into a context manager first.
666 .. code-block:: python
668 @click.group()
669 @click.option("--name")
670 @click.pass_context
671 def cli(ctx):
672 ctx.obj = ctx.with_resource(connect_db(name))
674 :param context_manager: The context manager to enter.
675 :return: Whatever ``context_manager.__enter__()`` returns.
677 .. versionadded:: 8.0
678 """
679 return self._exit_stack.enter_context(context_manager)
681 def call_on_close(self, f: t.Callable[..., t.Any]) -> t.Callable[..., t.Any]:
682 """Register a function to be called when the context tears down.
684 This can be used to close resources opened during the script
685 execution. Resources that support Python's context manager
686 protocol which would be used in a ``with`` statement should be
687 registered with :meth:`with_resource` instead.
689 :param f: The function to execute on teardown.
690 """
691 return self._exit_stack.callback(f)
693 def close(self) -> None:
694 """Invoke all close callbacks registered with
695 :meth:`call_on_close`, and exit all context managers entered
696 with :meth:`with_resource`.
697 """
698 self._close_with_exception_info(None, None, None)
700 def _close_with_exception_info(
701 self,
702 exc_type: type[BaseException] | None,
703 exc_value: BaseException | None,
704 tb: TracebackType | None,
705 ) -> bool | None:
706 """Unwind the exit stack by calling its :meth:`__exit__` providing the exception
707 information to allow for exception handling by the various resources registered
708 using :meth;`with_resource`
710 :return: Whatever ``exit_stack.__exit__()`` returns.
711 """
712 exit_result = self._exit_stack.__exit__(exc_type, exc_value, tb)
713 # In case the context is reused, create a new exit stack.
714 self._exit_stack = ExitStack()
716 return exit_result
718 @property
719 def command_path(self) -> str:
720 """The computed command path. This is used for the ``usage``
721 information on the help page. It's automatically created by
722 combining the info names of the chain of contexts to the root.
723 """
724 rv = ""
725 if self.info_name is not None:
726 rv = self.info_name
727 if self.parent is not None:
728 parent_command_path = [self.parent.command_path]
730 if isinstance(self.parent.command, Command):
731 for param in self.parent.command.get_params(self):
732 parent_command_path.extend(param.get_usage_pieces(self))
734 rv = f"{' '.join(parent_command_path)} {rv}"
735 return rv.lstrip()
737 def find_root(self) -> Context:
738 """Finds the outermost context."""
739 node = self
740 while node.parent is not None:
741 node = node.parent
742 return node
744 def find_object(self, object_type: type[V]) -> V | None:
745 """Finds the closest object of a given type."""
746 node: Context | None = self
748 while node is not None:
749 if isinstance(node.obj, object_type):
750 return node.obj
752 node = node.parent
754 return None
756 def ensure_object(self, object_type: type[V]) -> V:
757 """Like :meth:`find_object` but sets the innermost object to a
758 new instance of `object_type` if it does not exist.
759 """
760 rv = self.find_object(object_type)
761 if rv is None:
762 self.obj = rv = object_type()
763 return rv
765 def _default_map_has(self, name: str | None) -> bool:
766 """Check if :attr:`default_map` contains a real value for ``name``.
768 Returns ``False`` when the key is absent, the map is ``None``,
769 ``name`` is ``None``, or the stored value is the internal
770 :data:`UNSET` sentinel.
771 """
772 return (
773 name is not None
774 and self.default_map is not None
775 and name in self.default_map
776 and self.default_map[name] is not UNSET
777 )
779 @t.overload
780 def lookup_default(
781 self, name: str, call: t.Literal[True] = True
782 ) -> t.Any | None: ...
784 @t.overload
785 def lookup_default(
786 self, name: str, call: t.Literal[False] = ...
787 ) -> t.Any | t.Callable[[], t.Any] | None: ...
789 def lookup_default(self, name: str, call: bool = True) -> t.Any | None:
790 """Get the default for a parameter from :attr:`default_map`.
792 :param name: Name of the parameter.
793 :param call: If the default is a callable, call it. Disable to
794 return the callable instead.
796 .. versionchanged:: 8.0
797 Added the ``call`` parameter.
798 """
799 if not self._default_map_has(name):
800 return None
802 # Assert to make the type checker happy.
803 assert self.default_map is not None
804 value = self.default_map[name]
806 if call and callable(value):
807 return value()
809 return value
811 def fail(self, message: str) -> t.NoReturn:
812 """Aborts the execution of the program with a specific error
813 message.
815 :param message: the error message to fail with.
816 """
817 raise UsageError(message, self)
819 def abort(self) -> t.NoReturn:
820 """Aborts the script."""
821 raise Abort()
823 def exit(self, code: int = 0) -> t.NoReturn:
824 """Exits the application with a given exit code.
826 .. versionchanged:: 8.2
827 Callbacks and context managers registered with :meth:`call_on_close`
828 and :meth:`with_resource` are closed before exiting.
829 """
830 self.close()
831 raise Exit(code)
833 def get_usage(self) -> str:
834 """Helper method to get formatted usage string for the current
835 context and command.
836 """
837 return self.command.get_usage(self)
839 def get_help(self) -> str:
840 """Helper method to get formatted help page for the current
841 context and command.
842 """
843 return self.command.get_help(self)
845 def _make_sub_context(self, command: Command) -> Context:
846 """Create a new context of the same type as this context, but
847 for a new command.
849 :meta private:
850 """
851 return type(self)(command, info_name=command.name, parent=self)
853 @t.overload
854 def invoke(
855 self, callback: t.Callable[..., V], /, *args: t.Any, **kwargs: t.Any
856 ) -> V: ...
858 @t.overload
859 def invoke(self, callback: Command, /, *args: t.Any, **kwargs: t.Any) -> t.Any: ...
861 def invoke(
862 self, callback: Command | t.Callable[..., V], /, *args: t.Any, **kwargs: t.Any
863 ) -> t.Any | V:
864 """Invokes a command callback in exactly the way it expects. There
865 are two ways to invoke this method:
867 1. the first argument can be a callback and all other arguments and
868 keyword arguments are forwarded directly to the function.
869 2. the first argument is a click command object. In that case all
870 arguments are forwarded as well but proper click parameters
871 (options and click arguments) must be keyword arguments and Click
872 will fill in defaults.
874 .. versionchanged:: 8.0
875 All ``kwargs`` are tracked in :attr:`params` so they will be
876 passed if :meth:`forward` is called at multiple levels.
878 .. versionchanged:: 3.2
879 A new context is created, and missing arguments use default values.
880 """
881 if isinstance(callback, Command):
882 other_cmd = callback
884 if other_cmd.callback is None:
885 raise TypeError(
886 "The given command does not have a callback that can be invoked."
887 )
888 else:
889 callback = t.cast("t.Callable[..., V]", other_cmd.callback)
891 ctx = self._make_sub_context(other_cmd)
893 for param in other_cmd.params:
894 if param.name not in kwargs and param.expose_value:
895 default_value = param.get_default(ctx)
896 # We explicitly hide the :attr:`UNSET` value to the user, as we
897 # choose to make it an implementation detail. And because ``invoke``
898 # has been designed as part of Click public API, we return ``None``
899 # instead.
900 if default_value is UNSET:
901 default_value = None
902 kwargs[param.name] = param.type_cast_value(ctx, default_value)
904 # Track all kwargs as params, so that forward() will pass
905 # them on in subsequent calls.
906 ctx.params.update(kwargs)
907 else:
908 ctx = self
910 with augment_usage_errors(self), ctx:
911 return callback(*args, **kwargs)
913 def forward(self, cmd: Command, /, *args: t.Any, **kwargs: t.Any) -> t.Any:
914 """Similar to :meth:`invoke` but fills in default keyword
915 arguments from the current context if the other command expects
916 it. This cannot invoke callbacks directly, only other commands.
918 .. versionchanged:: 8.0
919 All ``kwargs`` are tracked in :attr:`params` so they will be
920 passed if ``forward`` is called at multiple levels.
921 """
922 # Can only forward to other commands, not direct callbacks.
923 if not isinstance(cmd, Command):
924 raise TypeError("Callback is not a command.")
926 for param in self.params:
927 if param not in kwargs:
928 kwargs[param] = self.params[param]
930 return self.invoke(cmd, *args, **kwargs)
932 def set_parameter_source(self, name: str, source: ParameterSource) -> None:
933 """Set the source of a parameter. This indicates the location
934 from which the value of the parameter was obtained.
936 :param name: The name of the parameter.
937 :param source: A member of :class:`~click.core.ParameterSource`.
938 """
939 self._parameter_source[name] = source
941 def get_parameter_source(self, name: str) -> ParameterSource | None:
942 """Get the source of a parameter. This indicates the location
943 from which the value of the parameter was obtained.
945 This can be useful for determining when a user specified a value
946 on the command line that is the same as the default value. It
947 will be :attr:`~click.core.ParameterSource.DEFAULT` only if the
948 value was actually taken from the default.
950 :param name: The name of the parameter.
951 :rtype: ParameterSource
953 .. versionchanged:: 8.0
954 Returns ``None`` if the parameter was not provided from any
955 source.
956 """
957 return self._parameter_source.get(name)
960class Command:
961 """Commands are the basic building block of command line interfaces in
962 Click. A basic command handles command line parsing and might dispatch
963 more parsing to commands nested below it.
965 :param name: the name of the command to use unless a group overrides it.
966 :param context_settings: an optional dictionary with defaults that are
967 passed to the context object.
968 :param callback: the callback to invoke. This is optional.
969 :param params: the parameters to register with this command. This can
970 be either :class:`Option` or :class:`Argument` objects.
971 :param help: the help string to use for this command.
972 :param epilog: like the help string but it's printed at the end of the
973 help page after everything else.
974 :param short_help: the short help to use for this command. This is
975 shown on the command listing of the parent command.
976 :param add_help_option: by default each command registers a ``--help``
977 option. This can be disabled by this parameter.
978 :param no_args_is_help: this controls what happens if no arguments are
979 provided. This option is disabled by default.
980 If enabled this will add ``--help`` as argument
981 if no arguments are passed
982 :param hidden: hide this command from help outputs.
983 :param deprecated: If ``True`` or non-empty string, issues a message
984 indicating that the command is deprecated and highlights
985 its deprecation in --help. The message can be customized
986 by using a string as the value.
988 .. versionchanged:: 8.2
989 This is the base class for all commands, not ``BaseCommand``.
990 ``deprecated`` can be set to a string as well to customize the
991 deprecation message.
993 .. versionchanged:: 8.1
994 ``help``, ``epilog``, and ``short_help`` are stored unprocessed,
995 all formatting is done when outputting help text, not at init,
996 and is done even if not using the ``@command`` decorator.
998 .. versionchanged:: 8.0
999 Added a ``repr`` showing the command name.
1001 .. versionchanged:: 7.1
1002 Added the ``no_args_is_help`` parameter.
1004 .. versionchanged:: 2.0
1005 Added the ``context_settings`` parameter.
1006 """
1008 #: The context class to create with :meth:`make_context`.
1009 #:
1010 #: .. versionadded:: 8.0
1011 context_class: type[Context] = Context
1013 #: the default for the :attr:`Context.allow_extra_args` flag.
1014 allow_extra_args = False
1016 #: the default for the :attr:`Context.allow_interspersed_args` flag.
1017 allow_interspersed_args = True
1019 #: the default for the :attr:`Context.ignore_unknown_options` flag.
1020 ignore_unknown_options = False
1022 name: str | None
1023 context_settings: cabc.MutableMapping[str, t.Any]
1024 callback: t.Callable[..., t.Any] | None
1025 params: list[Parameter]
1026 help: str | None
1027 epilog: str | None
1028 options_metavar: str | None
1029 short_help: str | None
1030 add_help_option: bool
1031 _help_option: Option | None
1032 no_args_is_help: bool
1033 hidden: bool
1034 deprecated: bool | str
1036 def __init__(
1037 self,
1038 name: str | None,
1039 context_settings: cabc.MutableMapping[str, t.Any] | None = None,
1040 callback: t.Callable[..., t.Any] | None = None,
1041 params: list[Parameter] | None = None,
1042 help: str | None = None,
1043 epilog: str | None = None,
1044 short_help: str | None = None,
1045 options_metavar: str | None = "[OPTIONS]",
1046 add_help_option: bool = True,
1047 no_args_is_help: bool = False,
1048 hidden: bool = False,
1049 deprecated: bool | str = False,
1050 ) -> None:
1051 #: the name the command thinks it has. Upon registering a command
1052 #: on a :class:`Group` the group will default the command name
1053 #: with this information. You should instead use the
1054 #: :class:`Context`\'s :attr:`~Context.info_name` attribute.
1055 self.name = name
1057 if context_settings is None:
1058 context_settings = {}
1060 #: an optional dictionary with defaults passed to the context.
1061 self.context_settings = context_settings
1063 #: the callback to execute when the command fires. This might be
1064 #: `None` in which case nothing happens.
1065 self.callback = callback
1066 #: the list of parameters for this command in the order they
1067 #: should show up in the help page and execute. Eager parameters
1068 #: will automatically be handled before non eager ones.
1069 self.params = params or []
1070 self.help = help
1071 self.epilog = epilog
1072 self.options_metavar = options_metavar
1073 self.short_help = short_help
1074 self.add_help_option = add_help_option
1075 self._help_option = None
1076 self.no_args_is_help = no_args_is_help
1077 self.hidden = hidden
1078 self.deprecated = deprecated
1080 def to_info_dict(self, ctx: Context) -> dict[str, t.Any]:
1081 return {
1082 "name": self.name,
1083 "params": [param.to_info_dict() for param in self.get_params(ctx)],
1084 "help": self.help,
1085 "epilog": self.epilog,
1086 "short_help": self.short_help,
1087 "hidden": self.hidden,
1088 "deprecated": self.deprecated,
1089 }
1091 def __repr__(self) -> str:
1092 return f"<{self.__class__.__name__} {self.name}>"
1094 def get_usage(self, ctx: Context) -> str:
1095 """Formats the usage line into a string and returns it.
1097 Calls :meth:`format_usage` internally.
1098 """
1099 formatter = ctx.make_formatter()
1100 self.format_usage(ctx, formatter)
1101 return formatter.getvalue().rstrip("\n")
1103 def get_params(self, ctx: Context) -> list[Parameter]:
1104 params = self.params
1105 help_option = self.get_help_option(ctx)
1107 if help_option is not None:
1108 params = [*params, help_option]
1110 if __debug__:
1111 import warnings
1113 opts = [opt for param in params for opt in param.opts]
1114 opts_counter = Counter(opts)
1115 duplicate_opts = (opt for opt, count in opts_counter.items() if count > 1)
1117 for duplicate_opt in duplicate_opts:
1118 warnings.warn(
1119 (
1120 f"The parameter {duplicate_opt} is used more than once. "
1121 "Remove its duplicate as parameters should be unique."
1122 ),
1123 stacklevel=3,
1124 )
1126 # Options may deliberately share a storage name to compete for
1127 # the same value (feature switches), but an argument sharing a
1128 # name silently overwrites the other parameter's value.
1129 names_counter = Counter(param.name for param in params)
1130 duplicate_names = (
1131 name for name, count in names_counter.items() if count > 1
1132 )
1134 for duplicate_name in duplicate_names:
1135 sharers = [param for param in params if param.name == duplicate_name]
1137 if help_option in sharers:
1138 warnings.warn(
1139 (
1140 f"The name {duplicate_name!r} is reserved for the "
1141 "automatic help option. Give the parameter a "
1142 "different name."
1143 ),
1144 stacklevel=3,
1145 )
1146 elif any(isinstance(param, Argument) for param in sharers):
1147 warnings.warn(
1148 (
1149 f"The name {duplicate_name!r} is used by an argument "
1150 "and another parameter. They will overwrite each "
1151 "other's value during parsing. Give each parameter "
1152 "a unique name."
1153 ),
1154 stacklevel=3,
1155 )
1157 return params
1159 def format_usage(self, ctx: Context, formatter: HelpFormatter) -> None:
1160 """Writes the usage line into the formatter.
1162 This is a low-level method called by :meth:`get_usage`.
1163 """
1164 pieces = self.collect_usage_pieces(ctx)
1165 formatter.write_usage(ctx.command_path, " ".join(pieces))
1167 def collect_usage_pieces(self, ctx: Context) -> list[str]:
1168 """Returns all the pieces that go into the usage line and returns
1169 it as a list of strings.
1170 """
1171 rv = [self.options_metavar] if self.options_metavar else []
1173 for param in self.get_params(ctx):
1174 rv.extend(param.get_usage_pieces(ctx))
1176 return rv
1178 def get_help_option_names(self, ctx: Context) -> list[str]:
1179 """Returns the names for the help option.
1181 Drops duplicates and names already reserved by another parameter. Order of
1182 :attr:`Context.help_option_names` is preserved, so the result is stable.
1184 .. versionchanged:: 8.5.0
1185 Names keep their declaration order.
1186 """
1187 all_names = dict.fromkeys(ctx.help_option_names)
1188 for param in self.params:
1189 for name in (*param.opts, *param.secondary_opts):
1190 all_names.pop(name, None)
1191 return list(all_names)
1193 def get_help_option(self, ctx: Context) -> Option | None:
1194 """Returns the help option object.
1196 Skipped if :attr:`add_help_option` is ``False``.
1198 .. versionchanged:: 8.5.0
1199 The help option stores its value under the reserved name
1200 ``_click_default_help``, so a parameter named ``help`` no
1201 longer breaks parsing.
1203 .. versionchanged:: 8.1.8
1204 The help option is now cached to avoid creating it multiple times.
1205 """
1206 help_option_names = self.get_help_option_names(ctx)
1208 if not help_option_names or not self.add_help_option:
1209 return None
1211 # Cache the help option object in private _help_option attribute to
1212 # avoid creating it multiple times. Not doing this will break the
1213 # callback ordering by iter_params_for_processing(), which relies on
1214 # object comparison.
1215 if self._help_option is None:
1216 # Avoid circular import.
1217 from .decorators import help_option
1219 # The help option never exposes its value, so it uses a reserved
1220 # storage name, keeping it clear of user parameters (like an
1221 # argument named "help") that would otherwise clobber its value.
1222 help_option(*help_option_names, _HELP_OPTION_STORAGE_NAME)(self)
1223 self._help_option = self.params.pop() # type: ignore[assignment]
1225 return self._help_option
1227 def make_parser(self, ctx: Context) -> _OptionParser:
1228 """Creates the underlying option parser for this command."""
1229 parser = _OptionParser(ctx)
1230 for param in self.get_params(ctx):
1231 param.add_to_parser(parser, ctx)
1232 return parser
1234 def get_help(self, ctx: Context) -> str:
1235 """Formats the help into a string and returns it.
1237 Calls :meth:`format_help` internally.
1238 """
1239 formatter = ctx.make_formatter()
1240 self.format_help(ctx, formatter)
1241 return formatter.getvalue().rstrip("\n")
1243 def get_short_help_str(self, limit: int = 45) -> str:
1244 """Gets short help for the command or makes it by shortening the
1245 long help string.
1246 """
1247 if self.short_help:
1248 text = inspect.cleandoc(self.short_help)
1249 elif self.help:
1250 text = _make_default_short_help(self.help, limit)
1251 else:
1252 text = ""
1254 if self.deprecated:
1255 text = f"{text} {_format_deprecated_label(self.deprecated)}"
1257 return text.strip()
1259 def format_help(self, ctx: Context, formatter: HelpFormatter) -> None:
1260 """Writes the help into the formatter if it exists.
1262 This is a low-level method called by :meth:`get_help`.
1264 This calls the following methods:
1266 - :meth:`format_usage`
1267 - :meth:`format_help_text`
1268 - :meth:`format_arguments`
1269 - :meth:`format_options`
1270 - :meth:`format_epilog`
1271 """
1272 self.format_usage(ctx, formatter)
1273 self.format_help_text(ctx, formatter)
1274 self.format_arguments(ctx, formatter)
1275 self.format_options(ctx, formatter)
1276 self.format_epilog(ctx, formatter)
1278 def format_help_text(self, ctx: Context, formatter: HelpFormatter) -> None:
1279 """Writes the help text to the formatter if it exists."""
1280 if self.help is not None:
1281 # truncate the help text to the first form feed
1282 text = inspect.cleandoc(self.help).partition("\f")[0]
1283 else:
1284 text = ""
1286 if self.deprecated:
1287 label = _format_deprecated_label(self.deprecated)
1288 text = f"{text} {label}" if text else label
1290 if text:
1291 formatter.write_paragraph()
1293 with formatter.indentation():
1294 formatter.write_text(text)
1296 def format_options(self, ctx: Context, formatter: HelpFormatter) -> None:
1297 """Writes all the options into the formatter if they exist."""
1298 opts = []
1299 for param in self.get_params(ctx):
1300 rv = param.get_help_record(ctx)
1301 if rv is not None and not isinstance(param, Argument):
1302 opts.append(rv)
1304 if opts:
1305 with formatter.section(_("Options")):
1306 formatter.write_dl(opts)
1308 def format_arguments(self, ctx: Context, formatter: HelpFormatter) -> None:
1309 """Writes all arguments into the formatter, if at least one is documented.
1311 An argument with no help gets an empty description, the same way an option
1312 with no help does. That keeps the section an exhaustive list of the
1313 positional arguments, matching the usage line.
1314 """
1315 args = [param for param in self.get_params(ctx) if isinstance(param, Argument)]
1317 if any(arg.help is not None for arg in args):
1318 with formatter.section(_("Positional arguments")):
1319 formatter.write_dl([arg.get_help_record(ctx) for arg in args])
1321 def format_epilog(self, ctx: Context, formatter: HelpFormatter) -> None:
1322 """Writes the epilog into the formatter if it exists."""
1323 if self.epilog:
1324 epilog = inspect.cleandoc(self.epilog)
1325 formatter.write_paragraph()
1327 with formatter.indentation():
1328 formatter.write_text(epilog)
1330 def make_context(
1331 self,
1332 info_name: str | None,
1333 args: list[str],
1334 parent: Context | None = None,
1335 **extra: t.Any,
1336 ) -> Context:
1337 """This function when given an info name and arguments will kick
1338 off the parsing and create a new :class:`Context`. It does not
1339 invoke the actual command callback though.
1341 To quickly customize the context class used without overriding
1342 this method, set the :attr:`context_class` attribute.
1344 :param info_name: the info name for this invocation. Generally this
1345 is the most descriptive name for the script or
1346 command. For the toplevel script it's usually
1347 the name of the script, for commands below it's
1348 the name of the command.
1349 :param args: the arguments to parse as list of strings.
1350 :param parent: the parent context if available.
1351 :param extra: extra keyword arguments forwarded to the context
1352 constructor.
1354 .. versionchanged:: 8.0
1355 Added the :attr:`context_class` attribute.
1356 """
1357 for key, value in self.context_settings.items():
1358 if key not in extra:
1359 extra[key] = value
1361 ctx = self.context_class(self, info_name=info_name, parent=parent, **extra)
1363 with ctx.scope(cleanup=False):
1364 self.parse_args(ctx, args)
1365 return ctx
1367 def parse_args(self, ctx: Context, args: list[str]) -> list[str]:
1368 if not args and self.no_args_is_help and not ctx.resilient_parsing:
1369 raise NoArgsIsHelpError(ctx)
1371 parser = self.make_parser(ctx)
1372 opts, args, param_order = parser.parse_args(args=args)
1374 for param in iter_params_for_processing(param_order, self.get_params(ctx)):
1375 _, args = param.handle_parse_result(ctx, opts, args)
1377 # We now have all parameters' values into `ctx.params`, but the data may contain
1378 # the `UNSET` sentinel.
1379 # Convert `UNSET` to `None` to ensure that the user doesn't see `UNSET`.
1380 #
1381 # Waiting until after the initial parse to convert allows us to treat `UNSET`
1382 # more like a missing value when multiple params use the same name.
1383 for name, value in ctx.params.items():
1384 if value is UNSET:
1385 ctx.params[name] = None
1387 if args and not ctx.allow_extra_args and not ctx.resilient_parsing:
1388 ctx.fail(
1389 ngettext(
1390 "Got unexpected extra argument ({args})",
1391 "Got unexpected extra arguments ({args})",
1392 len(args),
1393 ).format(args=" ".join(map(str, args)))
1394 )
1396 ctx.args = args
1397 ctx._opt_prefixes.update(parser._opt_prefixes)
1398 return args
1400 def invoke(self, ctx: Context) -> t.Any:
1401 """Given a context, this invokes the attached callback (if it exists)
1402 in the right way.
1403 """
1404 if self.deprecated:
1405 message = _(
1406 "DeprecationWarning: The command {name!r} is deprecated.{extra_message}"
1407 ).format(
1408 name=self.name,
1409 extra_message=_format_deprecated_suffix(self.deprecated),
1410 )
1411 echo(style(message, fg="red"), err=True)
1413 if self.callback is not None:
1414 return ctx.invoke(self.callback, **ctx.params)
1416 def shell_complete(self, ctx: Context, incomplete: str) -> list[CompletionItem]:
1417 """Return a list of completions for the incomplete value. Looks
1418 at the names of options and chained multi-commands.
1420 Any command could be part of a chained multi-command, so sibling
1421 commands are valid at any point during command completion.
1423 :param ctx: Invocation context for this command.
1424 :param incomplete: Value being completed. May be empty.
1426 .. versionadded:: 8.0
1427 """
1428 from click.shell_completion import CompletionItem
1430 results: list[CompletionItem] = []
1432 if incomplete and not incomplete[0].isalnum():
1433 for param in self.get_params(ctx):
1434 if (
1435 not isinstance(param, Option)
1436 or param.hidden
1437 or (
1438 not param.multiple
1439 and ctx.get_parameter_source(param.name)
1440 is ParameterSource.COMMANDLINE
1441 )
1442 ):
1443 continue
1445 results.extend(
1446 CompletionItem(name, help=param.help)
1447 for name in [*param.opts, *param.secondary_opts]
1448 if name.startswith(incomplete)
1449 )
1451 while ctx.parent is not None:
1452 ctx = ctx.parent
1454 if isinstance(ctx.command, Group) and ctx.command.chain:
1455 results.extend(
1456 CompletionItem(name, help=command.get_short_help_str())
1457 for name, command in _complete_visible_commands(ctx, incomplete)
1458 if name not in ctx._protected_args
1459 )
1461 return results
1463 @t.overload
1464 def main(
1465 self,
1466 args: cabc.Sequence[str] | None = None,
1467 prog_name: str | None = None,
1468 complete_var: str | None = None,
1469 standalone_mode: t.Literal[True] = True,
1470 **extra: t.Any,
1471 ) -> t.NoReturn: ...
1473 @t.overload
1474 def main(
1475 self,
1476 args: cabc.Sequence[str] | None = None,
1477 prog_name: str | None = None,
1478 complete_var: str | None = None,
1479 standalone_mode: bool = ...,
1480 **extra: t.Any,
1481 ) -> t.Any: ...
1483 def main(
1484 self,
1485 args: cabc.Sequence[str] | None = None,
1486 prog_name: str | None = None,
1487 complete_var: str | None = None,
1488 standalone_mode: bool = True,
1489 windows_expand_args: bool = True,
1490 **extra: t.Any,
1491 ) -> t.Any:
1492 """This is the way to invoke a script with all the bells and
1493 whistles as a command line application. This will always terminate
1494 the application after a call. If this is not wanted, ``SystemExit``
1495 needs to be caught.
1497 This method is also available by directly calling the instance of
1498 a :class:`Command`.
1500 :param args: the arguments that should be used for parsing. If not
1501 provided, ``sys.argv[1:]`` is used.
1502 :param prog_name: the program name that should be used. By default
1503 the program name is constructed by taking the file
1504 name from ``sys.argv[0]``.
1505 :param complete_var: the environment variable that controls the
1506 bash completion support. The default is
1507 ``"_<prog_name>_COMPLETE"`` with prog_name in
1508 uppercase.
1509 :param standalone_mode: the default behavior is to invoke the script
1510 in standalone mode. Click will then
1511 handle exceptions and convert them into
1512 error messages and the function will never
1513 return but shut down the interpreter. If
1514 this is set to `False` they will be
1515 propagated to the caller and the return
1516 value of this function is the return value
1517 of :meth:`invoke`.
1518 :param windows_expand_args: Expand glob patterns, user dir, and
1519 env vars in command line args on Windows.
1520 :param extra: extra keyword arguments are forwarded to the context
1521 constructor. See :class:`Context` for more information.
1523 .. versionchanged:: 8.0.1
1524 Added the ``windows_expand_args`` parameter to allow
1525 disabling command line arg expansion on Windows.
1527 .. versionchanged:: 8.0
1528 When taking arguments from ``sys.argv`` on Windows, glob
1529 patterns, user dir, and env vars are expanded.
1531 .. versionchanged:: 3.0
1532 Added the ``standalone_mode`` parameter.
1533 """
1534 if args is None:
1535 args = sys.argv[1:]
1537 if os.name == "nt" and windows_expand_args:
1538 args = _expand_args(args)
1539 else:
1540 args = list(args)
1542 if prog_name is None:
1543 prog_name = _detect_program_name()
1545 # Process shell completion requests and exit early.
1546 self._main_shell_completion(extra, prog_name, complete_var)
1548 # Every handler below takes the same two steps: propagate when
1549 # standalone mode is disabled, otherwise collect the message and the
1550 # exit code, and leave both to the teardown after the ``try``. The
1551 # teardown writes the message and exits, and the outermost handler
1552 # holds one policy for every interrupt arriving that late: the
1553 # message may be lost, the intended exit code still wins.
1554 report: cabc.Callable[[], None] | None = None
1555 exit_code = 1
1557 try:
1558 try:
1559 with self.make_context(prog_name, args, **extra) as ctx:
1560 rv = self.invoke(ctx)
1561 if not standalone_mode:
1562 return rv
1563 # it's not safe to `ctx.exit(rv)` here!
1564 # note that `rv` may actually contain data like "1" which
1565 # has obvious effects
1566 # more subtle case: `rv=[None, None]` can come out of
1567 # chained commands which all returned `None` -- so it's not
1568 # even always obvious that `rv` indicates success/failure
1569 # by its truthiness/falsiness
1570 ctx.exit()
1571 except Exit as e:
1572 if not standalone_mode:
1573 # in non-standalone mode, return the exit code
1574 # note that this is only reached if `self.invoke` above raises
1575 # an Exit explicitly -- thus bypassing the check there which
1576 # would return its result
1577 # the results of non-standalone execution may therefore be
1578 # somewhat ambiguous: if there are codepaths which lead to
1579 # `ctx.exit(1)` and to `return 1`, the caller won't be able to
1580 # tell the difference between the two
1581 return e.exit_code
1583 exit_code = e.exit_code
1584 except Abort:
1585 if not standalone_mode:
1586 raise
1588 report = _echo_aborted
1589 except (EOFError, KeyboardInterrupt) as e:
1590 # The blank line closes the terminal's ``^C`` echo.
1591 echo(file=sys.stderr)
1593 if not standalone_mode:
1594 raise Abort() from e
1596 report = _echo_aborted
1597 except ClickException as e:
1598 if not standalone_mode:
1599 raise
1601 report, exit_code = e.show, e.exit_code
1602 except OSError as e:
1603 if e.errno != errno.EPIPE:
1604 raise
1606 sys.stdout = t.cast(t.TextIO, _PacifyFlushWrapper(sys.stdout))
1607 sys.stderr = t.cast(t.TextIO, _PacifyFlushWrapper(sys.stderr))
1609 if report is not None:
1610 report()
1612 sys.exit(exit_code)
1613 except (EOFError, KeyboardInterrupt):
1614 if not standalone_mode:
1615 raise
1617 sys.exit(exit_code)
1619 def _main_shell_completion(
1620 self,
1621 ctx_args: cabc.MutableMapping[str, t.Any],
1622 prog_name: str,
1623 complete_var: str | None = None,
1624 ) -> None:
1625 """Check if the shell is asking for tab completion, process
1626 that, then exit early. Called from :meth:`main` before the
1627 program is invoked.
1629 :param prog_name: Name of the executable in the shell.
1630 :param complete_var: Name of the environment variable that holds
1631 the completion instruction. Defaults to
1632 ``_{PROG_NAME}_COMPLETE``.
1634 .. versionchanged:: 8.2.0
1635 Dots (``.``) in ``prog_name`` are replaced with underscores (``_``).
1636 """
1637 if complete_var is None:
1638 complete_name = prog_name.replace("-", "_").replace(".", "_")
1639 complete_var = f"_{complete_name}_COMPLETE".upper()
1641 instruction = os.environ.get(complete_var)
1643 if not instruction:
1644 return
1646 from .shell_completion import shell_complete
1648 rv = shell_complete(self, ctx_args, prog_name, complete_var, instruction)
1649 sys.exit(rv)
1651 def __call__(self, *args: t.Any, **kwargs: t.Any) -> t.Any:
1652 """Alias for :meth:`main`."""
1653 return self.main(*args, **kwargs)
1656class _FakeSubclassCheck(type):
1657 def __subclasscheck__(cls, subclass: type) -> bool:
1658 return issubclass(subclass, cls.__bases__[0])
1660 def __instancecheck__(cls, instance: t.Any) -> bool:
1661 return isinstance(instance, cls.__bases__[0])
1664class _BaseCommand(Command, metaclass=_FakeSubclassCheck):
1665 """
1666 .. deprecated:: 8.2
1667 Will be removed in Click 9.0. Use ``Command`` instead.
1668 """
1671class Group(Command):
1672 """A group is a command that nests other commands (or more groups).
1674 :param name: The name of the group command.
1675 :param commands: Map names to :class:`Command` objects. Can be a list, which
1676 will use :attr:`Command.name` as the keys.
1677 :param invoke_without_command: Invoke the group's callback even if a
1678 subcommand is not given.
1679 :param no_args_is_help: If no arguments are given, show the group's help and
1680 exit. Defaults to the opposite of ``invoke_without_command``.
1681 :param subcommand_metavar: How to represent the subcommand argument in help.
1682 The default will represent whether ``chain`` is set or not.
1683 :param chain: Allow passing more than one subcommand argument. After parsing
1684 a command's arguments, if any arguments remain another command will be
1685 matched, and so on.
1686 :param result_callback: A function to call after the group's and
1687 subcommand's callbacks. The value returned by the subcommand is passed.
1688 If ``chain`` is enabled, the value will be a list of values returned by
1689 all the commands. If ``invoke_without_command`` is enabled, the value
1690 will be the value returned by the group's callback, or an empty list if
1691 ``chain`` is enabled.
1692 :param kwargs: Other arguments passed to :class:`Command`.
1694 .. versionchanged:: 8.0
1695 The ``commands`` argument can be a list of command objects.
1697 .. versionchanged:: 8.2
1698 Merged with and replaces the ``MultiCommand`` base class.
1699 """
1701 allow_extra_args = True
1702 allow_interspersed_args = False
1704 #: If set, this is used by the group's :meth:`command` decorator
1705 #: as the default :class:`Command` class. This is useful to make all
1706 #: subcommands use a custom command class.
1707 #:
1708 #: .. versionadded:: 8.0
1709 command_class: type[Command] | None = None
1711 #: If set, this is used by the group's :meth:`group` decorator
1712 #: as the default :class:`Group` class. This is useful to make all
1713 #: subgroups use a custom group class.
1714 #:
1715 #: If set to the special value :class:`type` (literally
1716 #: ``group_class = type``), this group's class will be used as the
1717 #: default class. This makes a custom group class continue to make
1718 #: custom groups.
1719 #:
1720 #: .. versionadded:: 8.0
1721 group_class: type[Group | type] | None = None
1722 # Literal[type] isn't valid, so use Type[type]
1724 commands: cabc.MutableMapping[str, Command]
1725 invoke_without_command: bool
1726 subcommand_metavar: str
1727 chain: bool
1728 _result_callback: t.Callable[..., t.Any] | None
1730 def __init__(
1731 self,
1732 name: str | None = None,
1733 commands: cabc.MutableMapping[str, Command]
1734 | cabc.Sequence[Command]
1735 | None = None,
1736 invoke_without_command: bool = False,
1737 no_args_is_help: bool | None = None,
1738 subcommand_metavar: str | None = None,
1739 chain: bool = False,
1740 result_callback: t.Callable[..., t.Any] | None = None,
1741 **kwargs: t.Any,
1742 ) -> None:
1743 super().__init__(name, **kwargs)
1745 if commands is None:
1746 commands = {}
1747 elif isinstance(commands, abc.Sequence):
1748 commands = {c.name: c for c in commands if c.name is not None}
1750 #: The registered subcommands by their exported names.
1751 self.commands = commands
1753 if no_args_is_help is None:
1754 no_args_is_help = not invoke_without_command
1756 self.no_args_is_help = no_args_is_help
1757 self.invoke_without_command = invoke_without_command
1759 if subcommand_metavar is None:
1760 # When the group can run without a subcommand, the leading command
1761 # token is optional, so wrap it in brackets to reflect that.
1762 if chain:
1763 if invoke_without_command:
1764 subcommand_metavar = "[COMMAND1] [ARGS]... [COMMAND2 [ARGS]...]..."
1765 else:
1766 subcommand_metavar = "COMMAND1 [ARGS]... [COMMAND2 [ARGS]...]..."
1767 elif invoke_without_command:
1768 subcommand_metavar = "[COMMAND] [ARGS]..."
1769 else:
1770 subcommand_metavar = "COMMAND [ARGS]..."
1772 self.subcommand_metavar = subcommand_metavar
1773 self.chain = chain
1774 # The result callback that is stored. This can be set or
1775 # overridden with the :func:`result_callback` decorator.
1776 self._result_callback = result_callback
1778 if self.chain:
1779 for param in self.params:
1780 if isinstance(param, Argument) and not param.required:
1781 raise RuntimeError(
1782 "A group in chain mode cannot have optional arguments."
1783 )
1785 def to_info_dict(self, ctx: Context) -> dict[str, t.Any]:
1786 info_dict = super().to_info_dict(ctx)
1787 commands = {}
1789 for name in self.list_commands(ctx):
1790 command = self.get_command(ctx, name)
1792 if command is None:
1793 continue
1795 sub_ctx = ctx._make_sub_context(command)
1797 with sub_ctx.scope(cleanup=False):
1798 commands[name] = command.to_info_dict(sub_ctx)
1800 info_dict.update(commands=commands, chain=self.chain)
1801 return info_dict
1803 def add_command(self, cmd: Command, name: str | None = None) -> None:
1804 """Registers another :class:`Command` with this group. If the name
1805 is not provided, the name of the command is used.
1806 """
1807 name = name or cmd.name
1808 if name is None:
1809 raise TypeError("Command has no name.")
1810 _check_nested_chain(self, name, cmd, register=True)
1811 self.commands[name] = cmd
1813 @t.overload
1814 def command(self, __func: t.Callable[..., t.Any]) -> Command: ...
1816 @t.overload
1817 def command(
1818 self, *args: t.Any, **kwargs: t.Any
1819 ) -> t.Callable[[t.Callable[..., t.Any]], Command]: ...
1821 def command(
1822 self, *args: t.Any, **kwargs: t.Any
1823 ) -> t.Callable[[t.Callable[..., t.Any]], Command] | Command:
1824 """A shortcut decorator for declaring and attaching a command to
1825 the group. This takes the same arguments as :func:`command` and
1826 immediately registers the created command with this group by
1827 calling :meth:`add_command`.
1829 To customize the command class used, set the
1830 :attr:`command_class` attribute.
1832 .. versionchanged:: 8.1
1833 This decorator can be applied without parentheses.
1835 .. versionchanged:: 8.0
1836 Added the :attr:`command_class` attribute.
1837 """
1838 from .decorators import command
1840 func: t.Callable[..., t.Any] | None = None
1842 if args and callable(args[0]):
1843 assert len(args) == 1 and not kwargs, (
1844 "Use 'command(**kwargs)(callable)' to provide arguments."
1845 )
1846 (func,) = args
1847 args = ()
1849 if self.command_class and kwargs.get("cls") is None:
1850 kwargs["cls"] = self.command_class
1852 def decorator(f: t.Callable[..., t.Any]) -> Command:
1853 cmd: Command = command(*args, **kwargs)(f)
1854 self.add_command(cmd)
1855 return cmd
1857 if func is not None:
1858 return decorator(func)
1860 return decorator
1862 @t.overload
1863 def group(self, __func: t.Callable[..., t.Any]) -> Group: ...
1865 @t.overload
1866 def group(
1867 self, *args: t.Any, **kwargs: t.Any
1868 ) -> t.Callable[[t.Callable[..., t.Any]], Group]: ...
1870 def group(
1871 self, *args: t.Any, **kwargs: t.Any
1872 ) -> t.Callable[[t.Callable[..., t.Any]], Group] | Group:
1873 """A shortcut decorator for declaring and attaching a group to
1874 the group. This takes the same arguments as :func:`group` and
1875 immediately registers the created group with this group by
1876 calling :meth:`add_command`.
1878 To customize the group class used, set the :attr:`group_class`
1879 attribute.
1881 .. versionchanged:: 8.1
1882 This decorator can be applied without parentheses.
1884 .. versionchanged:: 8.0
1885 Added the :attr:`group_class` attribute.
1886 """
1887 from .decorators import group
1889 func: t.Callable[..., t.Any] | None = None
1891 if args and callable(args[0]):
1892 assert len(args) == 1 and not kwargs, (
1893 "Use 'group(**kwargs)(callable)' to provide arguments."
1894 )
1895 (func,) = args
1896 args = ()
1898 if self.group_class is not None and kwargs.get("cls") is None:
1899 if self.group_class is type:
1900 kwargs["cls"] = type(self)
1901 else:
1902 kwargs["cls"] = self.group_class
1904 def decorator(f: t.Callable[..., t.Any]) -> Group:
1905 cmd: Group = group(*args, **kwargs)(f)
1906 self.add_command(cmd)
1907 return cmd
1909 if func is not None:
1910 return decorator(func)
1912 return decorator
1914 def result_callback(self, replace: bool = False) -> t.Callable[[F], F]:
1915 """Adds a result callback to the command. By default if a
1916 result callback is already registered this will chain them but
1917 this can be disabled with the `replace` parameter. The result
1918 callback is invoked with the return value of the subcommand
1919 (or the list of return values from all subcommands if chaining
1920 is enabled) as well as the parameters as they would be passed
1921 to the main callback.
1923 Example::
1925 @click.group()
1926 @click.option('-i', '--input', default=23)
1927 def cli(input):
1928 return 42
1930 @cli.result_callback()
1931 def process_result(result, input):
1932 return result + input
1934 :param replace: if set to `True` an already existing result
1935 callback will be removed.
1937 .. versionchanged:: 8.0
1938 Renamed from ``resultcallback``.
1940 .. versionadded:: 3.0
1941 """
1943 def decorator(f: F) -> F:
1944 old_callback = self._result_callback
1946 if old_callback is None or replace:
1947 self._result_callback = f
1948 return f
1950 def function(value: t.Any, /, *args: t.Any, **kwargs: t.Any) -> t.Any:
1951 inner = old_callback(value, *args, **kwargs)
1952 return f(inner, *args, **kwargs)
1954 self._result_callback = rv = update_wrapper(t.cast(F, function), f)
1955 return rv # type: ignore[return-value]
1957 return decorator
1959 def get_command(self, ctx: Context, cmd_name: str) -> Command | None:
1960 """Given a context and a command name, this returns a :class:`Command`
1961 object if it exists or returns ``None``.
1962 """
1963 return self.commands.get(cmd_name)
1965 def list_commands(self, ctx: Context) -> list[str]:
1966 """Returns a list of subcommand names in the order they should appear."""
1967 return sorted(self.commands)
1969 def collect_usage_pieces(self, ctx: Context) -> list[str]:
1970 rv = super().collect_usage_pieces(ctx)
1971 rv.append(self.subcommand_metavar)
1972 return rv
1974 def format_options(self, ctx: Context, formatter: HelpFormatter) -> None:
1975 super().format_options(ctx, formatter)
1976 self.format_commands(ctx, formatter)
1978 def format_commands(self, ctx: Context, formatter: HelpFormatter) -> None:
1979 """Extra format methods for multi methods that adds all the commands
1980 after the options.
1981 """
1982 commands = []
1983 for subcommand in self.list_commands(ctx):
1984 cmd = self.get_command(ctx, subcommand)
1985 # What is this, the tool lied about a command. Ignore it
1986 if cmd is None:
1987 continue
1988 if cmd.hidden:
1989 continue
1991 commands.append((subcommand, cmd))
1993 # allow for 3 times the default spacing
1994 if len(commands):
1995 limit = formatter.width - 6 - max(len(cmd[0]) for cmd in commands)
1997 rows = []
1998 for subcommand, cmd in commands:
1999 help = cmd.get_short_help_str(limit)
2000 rows.append((subcommand, help))
2002 if rows:
2003 with formatter.section(_("Commands")):
2004 formatter.write_dl(rows)
2006 def parse_args(self, ctx: Context, args: list[str]) -> list[str]:
2007 if not args and self.no_args_is_help and not ctx.resilient_parsing:
2008 raise NoArgsIsHelpError(ctx)
2010 rest = super().parse_args(ctx, args)
2012 if self.chain:
2013 ctx._protected_args = rest
2014 ctx.args = []
2015 elif rest:
2016 ctx._protected_args, ctx.args = rest[:1], rest[1:]
2018 return ctx.args
2020 def invoke(self, ctx: Context) -> t.Any:
2021 def _process_result(value: t.Any) -> t.Any:
2022 if self._result_callback is not None:
2023 value = ctx.invoke(self._result_callback, value, **ctx.params)
2024 return value
2026 if not ctx._protected_args:
2027 if self.invoke_without_command:
2028 # No subcommand was invoked, so the result callback is
2029 # invoked with the group return value for regular
2030 # groups, or an empty list for chained groups.
2031 with ctx:
2032 rv = super().invoke(ctx)
2033 return _process_result([] if self.chain else rv)
2034 ctx.fail(_("Missing command."))
2036 # Fetch args back out
2037 args = [*ctx._protected_args, *ctx.args]
2038 ctx.args = []
2039 ctx._protected_args = []
2041 # If we're not in chain mode, we only allow the invocation of a
2042 # single command but we also inform the current context about the
2043 # name of the command to invoke.
2044 if not self.chain:
2045 # Make sure the context is entered so we do not clean up
2046 # resources until the result processor has worked.
2047 with ctx:
2048 cmd_name, cmd, args = self.resolve_command(ctx, args)
2049 assert cmd is not None
2050 ctx.invoked_subcommand = cmd_name
2051 super().invoke(ctx)
2052 sub_ctx = cmd.make_context(cmd_name, args, parent=ctx)
2053 with sub_ctx:
2054 return _process_result(sub_ctx.command.invoke(sub_ctx))
2056 # In chain mode we create the contexts step by step, but after the
2057 # base command has been invoked. Because at that point we do not
2058 # know the subcommands yet, the invoked subcommand attribute is
2059 # set to ``*`` to inform the command that subcommands are executed
2060 # but nothing else.
2061 with ctx:
2062 ctx.invoked_subcommand = "*" if args else None
2063 super().invoke(ctx)
2065 # Otherwise we make every single context and invoke them in a
2066 # chain. In that case the return value to the result processor
2067 # is the list of all invoked subcommand's results.
2068 contexts = []
2069 while args:
2070 cmd_name, cmd, args = self.resolve_command(ctx, args)
2071 assert cmd is not None
2072 sub_ctx = cmd.make_context(
2073 cmd_name,
2074 args,
2075 parent=ctx,
2076 allow_extra_args=True,
2077 allow_interspersed_args=False,
2078 )
2079 contexts.append(sub_ctx)
2080 args, sub_ctx.args = sub_ctx.args, []
2082 rv = []
2083 for sub_ctx in contexts:
2084 with sub_ctx:
2085 rv.append(sub_ctx.command.invoke(sub_ctx))
2086 return _process_result(rv)
2088 def resolve_command(
2089 self, ctx: Context, args: list[str]
2090 ) -> tuple[str | None, Command | None, list[str]]:
2091 cmd_name = make_str(args[0])
2093 # Get the command
2094 cmd = self.get_command(ctx, cmd_name)
2096 # If we can't find the command but there is a normalization
2097 # function available, we try with that one.
2098 if cmd is None and ctx.token_normalize_func is not None:
2099 cmd_name = ctx.token_normalize_func(cmd_name)
2100 cmd = self.get_command(ctx, cmd_name)
2102 # If we don't find the command we want to show an error message
2103 # to the user that it was not provided. However, there is
2104 # something else we should do: if the first argument looks like
2105 # an option we want to kick off parsing again for arguments to
2106 # resolve things like --help which now should go to the main
2107 # place.
2108 if cmd is None and not ctx.resilient_parsing:
2109 if _split_opt(cmd_name)[0]:
2110 self.parse_args(ctx, args)
2111 raise NoSuchCommand(cmd_name, possibilities=self.commands, ctx=ctx)
2112 return cmd_name if cmd else None, cmd, args[1:]
2114 def shell_complete(self, ctx: Context, incomplete: str) -> list[CompletionItem]:
2115 """Return a list of completions for the incomplete value. Looks
2116 at the names of options, subcommands, and chained
2117 multi-commands.
2119 :param ctx: Invocation context for this command.
2120 :param incomplete: Value being completed. May be empty.
2122 .. versionadded:: 8.0
2123 """
2124 from click.shell_completion import CompletionItem
2126 results = [
2127 CompletionItem(name, help=command.get_short_help_str())
2128 for name, command in _complete_visible_commands(ctx, incomplete)
2129 ]
2130 results.extend(super().shell_complete(ctx, incomplete))
2131 return results
2134class _MultiCommand(Group, metaclass=_FakeSubclassCheck):
2135 """
2136 .. deprecated:: 8.2
2137 Will be removed in Click 9.0. Use ``Group`` instead.
2138 """
2141class CommandCollection(Group):
2142 """A :class:`Group` that looks up subcommands on other groups. If a command
2143 is not found on this group, each registered source is checked in order.
2144 Parameters on a source are not added to this group, and a source's callback
2145 is not invoked when invoking its commands. In other words, this "flattens"
2146 commands in many groups into this one group.
2148 :param name: The name of the group command.
2149 :param sources: A list of :class:`Group` objects to look up commands from.
2150 :param kwargs: Other arguments passed to :class:`Group`.
2152 .. versionchanged:: 8.2
2153 This is a subclass of ``Group``. Commands are looked up first on this
2154 group, then each of its sources.
2155 """
2157 sources: list[Group]
2159 def __init__(
2160 self,
2161 name: str | None = None,
2162 sources: list[Group] | None = None,
2163 **kwargs: t.Any,
2164 ) -> None:
2165 super().__init__(name, **kwargs)
2166 #: The list of registered groups.
2167 self.sources = sources or []
2169 def add_source(self, group: Group) -> None:
2170 """Add a group as a source of commands."""
2171 self.sources.append(group)
2173 def get_command(self, ctx: Context, cmd_name: str) -> Command | None:
2174 rv = super().get_command(ctx, cmd_name)
2176 if rv is not None:
2177 return rv
2179 for source in self.sources:
2180 rv = source.get_command(ctx, cmd_name)
2182 if rv is not None:
2183 if self.chain:
2184 _check_nested_chain(self, cmd_name, rv)
2186 return rv
2188 return None
2190 def list_commands(self, ctx: Context) -> list[str]:
2191 rv: set[str] = set(super().list_commands(ctx))
2193 for source in self.sources:
2194 rv.update(source.list_commands(ctx))
2196 return sorted(rv)
2199def _check_iter(value: cabc.Iterable[V]) -> cabc.Iterator[V]:
2200 """Check if the value is iterable but not a string. Raises a type
2201 error, or return an iterator over the value.
2202 """
2203 if isinstance(value, str):
2204 raise TypeError
2206 return iter(value)
2209class Parameter(ABC):
2210 r"""A parameter to a command comes in two versions: they are either
2211 :class:`Option`\s or :class:`Argument`\s. Other subclasses are currently
2212 not supported by design as some of the internals for parsing are
2213 intentionally not finalized.
2215 Some settings are supported by both options and arguments.
2217 :param param_decls: the parameter declarations for this option or
2218 argument. This is a list of flags or argument
2219 names.
2220 :param type: the type that should be used. Either a :class:`ParamType`
2221 or a Python type. The latter is converted into the former
2222 automatically if supported.
2223 :param required: controls if this is optional or not.
2224 :param default: the default value if omitted. This can also be a callable,
2225 in which case it's invoked when the default is needed
2226 without any arguments.
2227 :param callback: A function to further process or validate the value
2228 after type conversion. It is called as ``f(ctx, param, value)``
2229 and must return the value. It is called for all sources,
2230 including prompts.
2231 :param nargs: the number of arguments to match. If not ``1`` the return
2232 value is a tuple instead of single value. The default for
2233 nargs is ``1`` (except if the type is a tuple, then it's
2234 the arity of the tuple). If ``nargs=-1``, all remaining
2235 parameters are collected.
2236 :param metavar: how the value is represented in the help page.
2237 :param expose_value: if this is `True` then the value is passed onwards
2238 to the command callback and stored on the context,
2239 otherwise it's skipped.
2240 :param is_eager: eager values are processed before non eager ones. This
2241 should not be set for arguments or it will inverse the
2242 order of processing.
2243 :param envvar: environment variable(s) that are used to provide a default value for
2244 this parameter. This can be a string or a sequence of strings. If a sequence is
2245 given, only the first non-empty environment variable is used for the parameter.
2246 :param shell_complete: A function that returns custom shell
2247 completions. Used instead of the param's type completion if
2248 given. Takes ``ctx, param, incomplete`` and must return a list
2249 of :class:`~click.shell_completion.CompletionItem` or a list of
2250 strings.
2251 :param deprecated: If ``True`` or non-empty string, issues a message
2252 indicating that the argument is deprecated and highlights
2253 its deprecation in --help. The message can be customized
2254 by using a string as the value. A deprecated parameter
2255 cannot be required, a ValueError will be raised otherwise.
2256 :param help: the help string. It is dedented and get a deprecated label if
2257 appropriate.
2259 .. versionchanged:: 8.5.1
2260 New ``help`` parameter to replace the one from :class:`Option` and
2261 :class:`Argument`.
2263 .. versionchanged:: 8.2.0
2264 Introduction of ``deprecated``.
2266 .. versionchanged:: 8.2
2267 Adding duplicate parameter names to a :class:`~click.core.Command` will
2268 result in a ``UserWarning`` being shown.
2270 .. versionchanged:: 8.2
2271 Adding duplicate parameter names to a :class:`~click.core.Command` will
2272 result in a ``UserWarning`` being shown.
2274 .. versionchanged:: 8.0
2275 ``process_value`` validates required parameters and bounded
2276 ``nargs``, and invokes the parameter callback before returning
2277 the value. This allows the callback to validate prompts.
2278 ``full_process_value`` is removed.
2280 .. versionchanged:: 8.0
2281 ``autocompletion`` is renamed to ``shell_complete`` and has new
2282 semantics described above. The old name is deprecated and will
2283 be removed in 8.1, until then it will be wrapped to match the
2284 new requirements.
2286 .. versionchanged:: 8.0
2287 For ``multiple=True, nargs>1``, the default must be a list of
2288 tuples.
2290 .. versionchanged:: 8.0
2291 Setting a default is no longer required for ``nargs>1``, it will
2292 default to ``None``. ``multiple=True`` or ``nargs=-1`` will
2293 default to ``()``.
2295 .. versionchanged:: 7.1
2296 Empty environment variables are ignored rather than taking the
2297 empty string value. This makes it possible for scripts to clear
2298 variables if they can't unset them.
2300 .. versionchanged:: 2.0
2301 Changed signature for parameter callback to also be passed the
2302 parameter. The old callback format will still work, but it will
2303 raise a warning to give you a chance to migrate the code easier.
2304 """
2306 param_type_name = "parameter"
2308 name: str
2309 opts: list[str]
2310 secondary_opts: list[str]
2311 # `Parameter.type` is annotated in `__init__` to avoid confusing mypy
2312 required: bool
2313 callback: t.Callable[[Context, Parameter, t.Any], t.Any] | None
2314 nargs: int
2315 multiple: bool
2316 expose_value: bool
2317 default: t.Any | t.Callable[[], t.Any] | None
2318 _default_explicit: bool
2319 is_eager: bool
2320 metavar: str | None
2321 envvar: str | cabc.Sequence[str] | None
2322 _custom_shell_complete: (
2323 t.Callable[[Context, Parameter, str], list[CompletionItem] | list[str]] | None
2324 )
2325 deprecated: bool | str
2326 help: str | None
2328 def __init__(
2329 self,
2330 param_decls: cabc.Sequence[str] | None = None,
2331 type: types.ParamType[t.Any] | t.Any | None = None,
2332 required: bool = False,
2333 # XXX The default historically embed two concepts:
2334 # - the declaration of a Parameter object carrying the default (handy to
2335 # arbitrage the default value of coupled Parameters sharing the same
2336 # self.name, like flag options),
2337 # - and the actual value of the default.
2338 # It is confusing and is the source of many issues. In the future, we might
2339 # think of splitting it in two, not unlike Option.is_flag and Option.flag_value:
2340 # we could have something like Parameter.is_default and Parameter.default_value.
2341 default: t.Any | t.Callable[[], t.Any] | None = UNSET,
2342 callback: t.Callable[[Context, Parameter, t.Any], t.Any] | None = None,
2343 nargs: int | None = None,
2344 multiple: bool = False,
2345 metavar: str | None = None,
2346 expose_value: bool = True,
2347 is_eager: bool = False,
2348 envvar: str | cabc.Sequence[str] | None = None,
2349 shell_complete: t.Callable[
2350 [Context, Parameter, str], list[CompletionItem] | list[str]
2351 ]
2352 | None = None,
2353 deprecated: bool | str = False,
2354 help: str | None = None,
2355 ) -> None:
2356 self.name, self.opts, self.secondary_opts = self._parse_decls(
2357 param_decls or (), expose_value
2358 )
2359 self.type: types.ParamType[t.Any] = types.convert_type(type, default)
2361 # Default nargs to what the type tells us if we have that
2362 # information available.
2363 if nargs is None:
2364 if self.type.is_composite:
2365 nargs = self.type.arity
2366 else:
2367 nargs = 1
2369 self.required = required
2370 self.callback = callback
2371 self.nargs = nargs
2372 self.multiple = multiple
2373 self.expose_value = expose_value
2374 self.default = default
2375 # Whether the user passed ``default`` explicitly to the constructor. Captured
2376 # before any auto-derived default (like ``0`` for a ``count`` :class:`Option`)
2377 # replaces the :data:`UNSET` sentinel, so it remains ``False`` when the default
2378 # was inferred rather than chosen.
2379 self._default_explicit = default is not UNSET
2380 self.is_eager = is_eager
2381 self.metavar = metavar
2382 self.envvar = envvar
2383 self._custom_shell_complete = shell_complete
2384 self.deprecated = deprecated
2386 if help:
2387 help = inspect.cleandoc(help)
2389 if deprecated:
2390 label = _format_deprecated_label(deprecated)
2391 help = f"{help} {label}" if help else label
2393 self.help = help
2395 if __debug__:
2396 if self.type.is_composite and nargs != self.type.arity:
2397 raise ValueError(
2398 f"'nargs' must be {self.type.arity} (or None) for"
2399 f" type {self.type!r}, but it was {nargs}."
2400 )
2402 if required and deprecated:
2403 raise ValueError(
2404 f"The {self.param_type_name} '{self.human_readable_name}' "
2405 "is deprecated and still required. A deprecated "
2406 f"{self.param_type_name} cannot be required."
2407 )
2409 @staticmethod
2410 def _hide_unset(value: t.Any) -> t.Any:
2411 """Present the internal :data:`UNSET` sentinel as ``None`` at a boundary that
2412 exposes a parameter's value (introspection, prompts), keeping the sentinel an
2413 implementation detail.
2414 """
2415 return None if value is UNSET else value
2417 def to_info_dict(self) -> dict[str, t.Any]:
2418 """Gather information that could be useful for a tool generating
2419 user-facing documentation.
2421 Use :meth:`click.Context.to_info_dict` to traverse the entire
2422 CLI structure.
2424 .. versionchanged:: 8.3.0
2425 Returns ``None`` for the :attr:`default` if it was not set.
2427 .. versionadded:: 8.0
2428 """
2429 return {
2430 "name": self.name,
2431 "param_type_name": self.param_type_name,
2432 "opts": self.opts,
2433 "secondary_opts": self.secondary_opts,
2434 "type": self.type.to_info_dict(),
2435 "required": self.required,
2436 "nargs": self.nargs,
2437 "multiple": self.multiple,
2438 "default": self._hide_unset(self.default),
2439 "envvar": self.envvar,
2440 "help": self.help,
2441 }
2443 def __repr__(self) -> str:
2444 return f"<{self.__class__.__name__} {self.name}>"
2446 @abstractmethod
2447 def _parse_decls(
2448 self, decls: cabc.Sequence[str], expose_value: bool
2449 ) -> tuple[str, list[str], list[str]]: ...
2451 @property
2452 def human_readable_name(self) -> str:
2453 """Returns the human readable name of this parameter. This is the
2454 same as the name for options, but the metavar for arguments.
2455 """
2456 return self.name
2458 def make_metavar(self, ctx: Context) -> str:
2459 if self.metavar is not None:
2460 return self.metavar
2462 metavar = self.type.get_metavar(param=self, ctx=ctx)
2464 if metavar is None:
2465 metavar = self.type.name.upper()
2467 if self.nargs != 1:
2468 metavar += "..."
2470 return metavar
2472 @t.overload
2473 def get_default(
2474 self, ctx: Context, call: t.Literal[True] = True
2475 ) -> t.Any | None: ...
2477 @t.overload
2478 def get_default(
2479 self, ctx: Context, call: bool = ...
2480 ) -> t.Any | t.Callable[[], t.Any] | None: ...
2482 def get_default(
2483 self, ctx: Context, call: bool = True
2484 ) -> t.Any | t.Callable[[], t.Any] | None:
2485 """Get the default for the parameter. Tries
2486 :meth:`Context.lookup_default` first, then the local default.
2488 :param ctx: Current context.
2489 :param call: If the default is a callable, call it. Disable to
2490 return the callable instead.
2492 .. versionchanged:: 8.0.2
2493 Type casting is no longer performed when getting a default.
2495 .. versionchanged:: 8.0.1
2496 Type casting can fail in resilient parsing mode. Invalid
2497 defaults will not prevent showing help text.
2499 .. versionchanged:: 8.0
2500 Looks at ``ctx.default_map`` first.
2502 .. versionchanged:: 8.0
2503 Added the ``call`` parameter.
2504 """
2505 value = ctx.lookup_default(self.name, call=False)
2507 if value is None and not ctx._default_map_has(self.name):
2508 value = self.default
2510 if call and callable(value):
2511 value = value()
2513 return value
2515 @abstractmethod
2516 def add_to_parser(self, parser: _OptionParser, ctx: Context) -> None: ...
2518 def consume_value(
2519 self, ctx: Context, opts: cabc.Mapping[str, t.Any]
2520 ) -> tuple[t.Any, ParameterSource]:
2521 """Returns the parameter value produced by the parser.
2523 If the parser did not produce a value from user input, the value is either
2524 sourced from the environment variable, the default map, or the parameter's
2525 default value. In that order of precedence.
2527 If no value is found, an internal sentinel value is returned.
2529 :meta private:
2530 """
2531 # Collect from the parse the value passed by the user to the CLI.
2532 value = opts.get(self.name, UNSET)
2533 # If the value is set, it means it was sourced from the command line by the
2534 # parser, otherwise it left unset by default.
2535 source = (
2536 ParameterSource.COMMANDLINE
2537 if value is not UNSET
2538 else ParameterSource.DEFAULT
2539 )
2541 if value is UNSET:
2542 envvar_value = self.value_from_envvar(ctx)
2543 if envvar_value is not None:
2544 value = envvar_value
2545 source = ParameterSource.ENVIRONMENT
2547 if value is UNSET:
2548 default_map_value = ctx.lookup_default(self.name)
2549 if default_map_value is not None or ctx._default_map_has(self.name):
2550 value = default_map_value
2551 source = ParameterSource.DEFAULT_MAP
2553 # A string from default_map must be split for multi-value
2554 # parameters, matching value_from_envvar behavior.
2555 if isinstance(value, str) and self.nargs != 1:
2556 value = self.type.split_envvar_value(value)
2558 if value is UNSET:
2559 default_value = self.get_default(ctx)
2560 if default_value is not UNSET:
2561 value = default_value
2562 source = ParameterSource.DEFAULT
2564 return value, source
2566 def type_cast_value(self, ctx: Context, value: t.Any) -> t.Any:
2567 """Convert and validate a value against the parameter's
2568 :attr:`type`, :attr:`multiple`, and :attr:`nargs`.
2569 """
2570 if value is None:
2571 if self.multiple or self.nargs == -1:
2572 return ()
2573 else:
2574 return value
2576 def check_iter(value: t.Any) -> cabc.Iterator[t.Any]:
2577 try:
2578 return _check_iter(value)
2579 except TypeError:
2580 # This should only happen when passing in args manually,
2581 # the parser should construct an iterable when parsing
2582 # the command line.
2583 raise BadParameter(
2584 _("Value must be an iterable."), ctx=ctx, param=self
2585 ) from None
2587 # Define the conversion function based on nargs and type.
2589 if self.nargs == 1 or self.type.is_composite:
2591 def convert(value: t.Any) -> t.Any:
2592 return self.type(value, param=self, ctx=ctx)
2594 elif self.nargs == -1:
2596 def convert(value: t.Any) -> t.Any: # tuple[t.Any, ...]
2597 return tuple(self.type(x, self, ctx) for x in check_iter(value))
2599 else: # nargs > 1
2601 def convert(value: t.Any) -> t.Any: # tuple[t.Any, ...]
2602 value = tuple(check_iter(value))
2604 if len(value) != self.nargs:
2605 raise BadParameter(
2606 ngettext(
2607 "Takes {nargs} values but 1 was given.",
2608 "Takes {nargs} values but {len} were given.",
2609 len(value),
2610 ).format(nargs=self.nargs, len=len(value)),
2611 ctx=ctx,
2612 param=self,
2613 )
2615 return tuple(self.type(x, self, ctx) for x in value)
2617 if self.multiple:
2618 return tuple(convert(x) for x in check_iter(value))
2620 return convert(value)
2622 def value_is_missing(self, value: t.Any) -> bool:
2623 """A value is considered missing if:
2625 - it is :attr:`UNSET`,
2626 - or if it is an empty sequence while the parameter is suppose to have
2627 non-single value (i.e. :attr:`nargs` is not ``1`` or :attr:`multiple` is
2628 set).
2630 :meta private:
2631 """
2632 if value is UNSET:
2633 return True
2635 if (self.nargs != 1 or self.multiple) and value == ():
2636 return True
2638 return False
2640 def process_value(self, ctx: Context, value: t.Any) -> t.Any:
2641 """Process the value of this parameter:
2643 1. Type cast the value using :meth:`type_cast_value`.
2644 2. Check if the value is missing (see: :meth:`value_is_missing`), and raise
2645 :exc:`MissingParameter` if it is required.
2646 3. If a :attr:`callback` is set, call it to have the value replaced by the
2647 result of the callback. If the value was not set, the callback receive
2648 ``None``. This keep the legacy behavior as it was before the introduction of
2649 the :attr:`UNSET` sentinel.
2651 :meta private:
2652 """
2653 # shelter `type_cast_value` from ever seeing an `UNSET` value by handling the
2654 # cases in which `UNSET` gets special treatment explicitly at this layer.
2655 # Subclasses can override the public `type_cast_value`, so the internal sentinel
2656 # must not reach it. A missing value skips the call rather than passing `None`,
2657 # which `value_is_missing` would not detect.
2658 if value is UNSET:
2659 if self.multiple or self.nargs == -1:
2660 value = ()
2661 else:
2662 value = self.type_cast_value(ctx, value)
2664 if self.required and self.value_is_missing(value):
2665 raise MissingParameter(ctx=ctx, param=self)
2667 if self.callback is not None:
2668 # Legacy case: UNSET is not exposed directly to the callback, but converted
2669 # to None.
2670 if value is UNSET:
2671 value = None
2673 # Search for parameters with UNSET values in the context.
2674 unset_keys = {k: None for k, v in ctx.params.items() if v is UNSET}
2675 # No UNSET values, call the callback as usual.
2676 if not unset_keys:
2677 value = self.callback(ctx, self, value)
2679 # Legacy case: provide a temporarily manipulated context to the callback to
2680 # hide UNSET values as None.
2681 else:
2682 # Add another layer to the context stack to clearly hint that the
2683 # context is temporarily modified.
2684 with ctx:
2685 # Update the context parameters to replace UNSET with None.
2686 ctx.params.update(unset_keys)
2687 # Feed these fake context parameters to the callback.
2688 value = self.callback(ctx, self, value)
2689 # Restore the UNSET values in the context parameters.
2690 ctx.params.update(
2691 {
2692 k: UNSET
2693 for k in unset_keys
2694 # Only restore keys that are present and still None, in case
2695 # the callback modified other parameters.
2696 if k in ctx.params and ctx.params[k] is None
2697 }
2698 )
2700 return value
2702 def resolve_envvar_value(self, ctx: Context) -> str | None:
2703 """Returns the value found in the environment variable(s) attached to this
2704 parameter.
2706 Environment variables values are `always returned as strings
2707 <https://docs.python.org/3/library/os.html#os.environ>`_.
2709 This method returns ``None`` if:
2711 - the :attr:`envvar` property is not set on the :class:`Parameter`,
2712 - the environment variable is not found in the environment,
2713 - the variable is found in the environment but its value is empty (i.e. the
2714 environment variable is present but has an empty string).
2716 If :attr:`envvar` is setup with multiple environment variables,
2717 then only the first non-empty value is returned.
2719 .. caution::
2721 The raw value extracted from the environment is not normalized and is
2722 returned as-is. Any normalization or reconciliation is performed later by
2723 the :class:`Parameter`'s :attr:`type`.
2725 :meta private:
2726 """
2727 if not self.envvar:
2728 return None
2730 if isinstance(self.envvar, str):
2731 rv = os.environ.get(self.envvar)
2733 if rv:
2734 return rv
2735 else:
2736 for envvar in self.envvar:
2737 rv = os.environ.get(envvar)
2739 # Return the first non-empty value of the list of environment variables.
2740 if rv:
2741 return rv
2742 # Else, absence of value is interpreted as an environment variable that
2743 # is not set, so proceed to the next one.
2745 return None
2747 def value_from_envvar(self, ctx: Context) -> str | cabc.Sequence[str] | None:
2748 """Process the raw environment variable string for this parameter.
2750 Returns the string as-is or splits it into a sequence of strings if the
2751 parameter is expecting multiple values (i.e. its :attr:`nargs` property is set
2752 to a value other than ``1``).
2754 :meta private:
2755 """
2756 rv = self.resolve_envvar_value(ctx)
2758 if rv is not None and self.nargs != 1:
2759 return self.type.split_envvar_value(rv)
2761 return rv
2763 def handle_parse_result(
2764 self, ctx: Context, opts: cabc.Mapping[str, t.Any], args: list[str]
2765 ) -> tuple[t.Any, list[str]]:
2766 """Process the value produced by the parser from user input.
2768 Always process the value through the Parameter's :attr:`type`, wherever it
2769 comes from.
2771 If the parameter is deprecated, this method warn the user about it. But only if
2772 the value has been explicitly set by the user (and as such, is not coming from
2773 a default).
2775 :meta private:
2776 """
2777 # Capture the slot's existing state before we mutate
2778 # ``_parameter_source`` so the write decision below can compare our
2779 # incoming source against the source of the option that already wrote
2780 # the slot (if any).
2781 existing_value = ctx.params.get(self.name, UNSET)
2782 existing_source = ctx.get_parameter_source(self.name)
2783 existing_default_explicit = ctx._param_default_explicit.get(self.name, False)
2785 with augment_usage_errors(ctx, param=self):
2786 value, source = self.consume_value(ctx, opts)
2788 # Record the source before processing so eager callbacks and type
2789 # conversion can inspect it. Restored after arbitration if this
2790 # option loses a feature-switch group.
2791 ctx.set_parameter_source(self.name, source)
2793 # Display a deprecation warning if necessary.
2794 if (
2795 self.deprecated
2796 and value is not UNSET
2797 and source < ParameterSource.DEFAULT_MAP
2798 ):
2799 message = _(
2800 "DeprecationWarning: The {param_type} {name!r} is deprecated."
2801 "{extra_message}"
2802 ).format(
2803 param_type=self.param_type_name,
2804 name=self.human_readable_name,
2805 extra_message=_format_deprecated_suffix(self.deprecated),
2806 )
2807 echo(style(message, fg="red"), err=True)
2809 # Process the value through the parameter's type.
2810 try:
2811 value = self.process_value(ctx, value)
2812 except Exception:
2813 if not ctx.resilient_parsing:
2814 raise
2815 # In resilient parsing mode, we do not want to fail the command if the
2816 # value is incompatible with the parameter type, so we reset the value
2817 # to UNSET, which will be interpreted as a missing value.
2818 value = UNSET
2820 # Arbitrate the slot when several parameters target the same variable name
2821 # (feature-switch groups).
2822 slot_empty = existing_value is UNSET
2823 more_explicit = existing_source is not None and source < existing_source
2824 same_source = existing_source is not None and source == existing_source
2825 auto_would_downgrade_explicit = (
2826 same_source
2827 and source == ParameterSource.DEFAULT
2828 and existing_default_explicit
2829 and not self._default_explicit
2830 )
2831 is_winner = (
2832 slot_empty
2833 or more_explicit
2834 or (same_source and not auto_would_downgrade_explicit)
2835 )
2837 if is_winner:
2838 if self.expose_value:
2839 ctx.params[self.name] = value
2840 ctx._param_default_explicit[self.name] = self._default_explicit
2841 elif existing_source is not None:
2842 # Lost arbitration; restore the winning option's source.
2843 ctx.set_parameter_source(self.name, existing_source)
2844 # else: ctx.params[self.name] was populated by code that bypassed
2845 # handle_parse_result (from another option's callback for example). Keep
2846 # the provisional source recorded before process_value so downstream
2847 # lookups don't return ``None``.
2849 return value, args
2851 def get_help_record(self, ctx: Context) -> tuple[str, str] | None:
2852 return None
2854 def get_usage_pieces(self, ctx: Context) -> list[str]:
2855 return []
2857 def get_error_hint(self, ctx: Context | None) -> str:
2858 """Get a stringified version of the param for use in error messages to
2859 indicate which param caused the error.
2861 .. versionchanged:: 8.4.0
2862 ``ctx`` can be ``None``.
2863 """
2864 hint_list = self.opts or [self.human_readable_name]
2865 return " / ".join(f"'{x}'" for x in hint_list)
2867 def shell_complete(self, ctx: Context, incomplete: str) -> list[CompletionItem]:
2868 """Return a list of completions for the incomplete value. If a
2869 ``shell_complete`` function was given during init, it is used.
2870 Otherwise, the :attr:`type`
2871 :meth:`~click.types.ParamType[t.Any].shell_complete` function is used.
2873 :param ctx: Invocation context for this command.
2874 :param incomplete: Value being completed. May be empty.
2876 .. versionadded:: 8.0
2877 """
2878 if self._custom_shell_complete is not None:
2879 results = self._custom_shell_complete(ctx, self, incomplete)
2881 if results and isinstance(results[0], str):
2882 from click.shell_completion import CompletionItem
2884 results = [CompletionItem(c) for c in results]
2886 return t.cast("list[CompletionItem]", results)
2888 return self.type.shell_complete(ctx, self, incomplete)
2891class Option(Parameter):
2892 """Options are usually optional values on the command line and
2893 have some extra features that arguments don't have.
2895 All other parameters are passed onwards to the parameter constructor.
2897 :param show_default: Show the default value for this option in its
2898 help text. Values are not shown by default, unless
2899 :attr:`Context.show_default` is ``True``. If this value is a
2900 string, it shows that string in parentheses instead of the
2901 actual value. This is particularly useful for dynamic options.
2902 For single option boolean flags, the default remains hidden if
2903 its value is ``False``.
2904 :param show_envvar: Controls if an environment variable should be
2905 shown on the help page and error messages.
2906 Normally, environment variables are not shown.
2907 :param prompt: If set to ``True`` or a non empty string then the
2908 user will be prompted for input. If set to ``True`` the prompt
2909 will be the option name capitalized. A deprecated option cannot be
2910 prompted.
2911 :param confirmation_prompt: Prompt a second time to confirm the
2912 value if it was prompted for. Can be set to a string instead of
2913 ``True`` to customize the message.
2914 :param prompt_required: If set to ``False``, the user will be
2915 prompted for input only when the option was specified as a flag
2916 without a value.
2917 :param hide_input: If this is ``True`` then the input on the prompt
2918 will be hidden from the user. This is useful for password input.
2919 :param is_flag: forces this option to act as a flag. The default is
2920 auto detection.
2921 :param flag_value: which value should be used for this flag if it's
2922 enabled. This is set to a boolean automatically if
2923 the option string contains a slash to mark two options.
2924 :param multiple: if this is set to `True` then the argument is accepted
2925 multiple times and recorded. This is similar to ``nargs``
2926 in how it works but supports arbitrary number of
2927 arguments.
2928 :param count: this flag makes an option increment an integer.
2929 :param allow_from_autoenv: if this is enabled then the value of this
2930 parameter will be pulled from an environment
2931 variable in case a prefix is defined on the
2932 context.
2933 :param help: the help string.
2934 :param hidden: hide this option from help outputs.
2935 :param attrs: Other command arguments described in :class:`Parameter`.
2937 .. versionchanged:: 8.4.0
2938 Non-basic ``flag_value`` types (not ``str``, ``int``, ``float``, or
2939 ``bool``) are passed through unchanged instead of being stringified.
2940 Previously, ``type=click.UNPROCESSED`` was required to preserve them.
2942 .. versionchanged:: 8.2
2943 ``envvar`` used with ``flag_value`` will always use the ``flag_value``,
2944 previously it would use the value of the environment variable.
2946 .. versionchanged:: 8.1
2947 Help text indentation is cleaned here instead of only in the
2948 ``@option`` decorator.
2950 .. versionchanged:: 8.1
2951 The ``show_default`` parameter overrides
2952 ``Context.show_default``.
2954 .. versionchanged:: 8.1
2955 The default of a single option boolean flag is not shown if the
2956 default value is ``False``.
2958 .. versionchanged:: 8.0.1
2959 ``type`` is detected from ``flag_value`` if given, for basic Python
2960 types (``str``, ``int``, ``float``, ``bool``).
2961 """
2963 param_type_name = "option"
2965 prompt: str | None
2966 confirmation_prompt: bool | str
2967 prompt_required: bool
2968 hide_input: bool
2969 hidden: bool
2971 _flag_needs_value: bool
2972 is_flag: bool
2973 flag_value: t.Any
2974 type: types.ParamType[t.Any]
2975 default: t.Any | t.Callable[[], t.Any] | None
2977 count: bool
2978 allow_from_autoenv: bool
2979 show_default: bool | str | None
2980 show_choices: bool
2981 show_envvar: bool
2983 def __init__(
2984 self,
2985 param_decls: cabc.Sequence[str] | None = None,
2986 show_default: bool | str | None = None,
2987 prompt: bool | str = False,
2988 confirmation_prompt: bool | str = False,
2989 prompt_required: bool = True,
2990 hide_input: bool = False,
2991 is_flag: bool | None = None,
2992 flag_value: t.Any = UNSET,
2993 multiple: bool = False,
2994 count: bool = False,
2995 allow_from_autoenv: bool = True,
2996 type: types.ParamType[t.Any] | t.Any | None = None,
2997 help: str | None = None,
2998 hidden: bool = False,
2999 show_choices: bool = True,
3000 show_envvar: bool = False,
3001 deprecated: bool | str = False,
3002 **attrs: t.Any,
3003 ) -> None:
3004 super().__init__(
3005 param_decls,
3006 type=type,
3007 multiple=multiple,
3008 deprecated=deprecated,
3009 help=help,
3010 **attrs,
3011 )
3013 # Phase 1: prompt-related attributes. ``_infer_flag_kind`` reads ``self.prompt``
3014 # and ``self.prompt_required`` so this must run first.
3015 if prompt is True:
3016 if not self.name:
3017 raise TypeError("'name' is required with 'prompt=True'.")
3019 prompt_text = self.name.replace("_", " ").capitalize()
3020 elif prompt is False:
3021 prompt_text = None
3022 else:
3023 prompt_text = prompt
3025 self.prompt = prompt_text
3026 self.confirmation_prompt = confirmation_prompt
3027 self.prompt_required = prompt_required
3028 self.hide_input = hide_input
3029 self.hidden = hidden
3031 # Phase 2: flag-kind inference.
3032 self.is_flag, self._flag_needs_value = self._infer_flag_kind(
3033 is_flag, flag_value
3034 )
3036 # Phase 3: type inference. Override the type set by :meth:`Parameter.__init__`
3037 # when this option is a flag or a count.
3038 self.type = self._pick_type(type, flag_value, count, self.is_flag)
3040 # Phase 4: store the raw ``flag_value`` and ``count`` settings.
3041 # ``self.flag_value`` and ``self.default`` deliberately keep the :data:`UNSET`
3042 # sentinel when the user didn't pass them. Auto-derived values are resolved
3043 # lazily in :meth:`_resolve_lazy_default` and :attr:`flag_activation_value`.
3044 # Keeping the raw values means ``is UNSET`` reliably answers "did the user pass
3045 # this?", and any future feature needing the same distinction can reuse it
3046 # without reintroducing parallel "was it explicit?" tracking.
3047 self.flag_value = flag_value
3048 self.count = count
3049 if count and self.default is UNSET:
3050 self.default = 0
3052 self.allow_from_autoenv = allow_from_autoenv
3053 self.show_default = show_default
3054 self.show_choices = show_choices
3055 self.show_envvar = show_envvar
3057 # Phase 5: validate. Raises on illegal kwarg combinations.
3058 self._validate(prompt, deprecated)
3060 @property
3061 def is_bool_flag(self) -> bool:
3062 """``True`` when this option is a flag with a boolean type.
3064 Derived from :attr:`is_flag` and :attr:`type`; computed on access so it cannot
3065 drift if a subclass replaces :attr:`type` after construction.
3066 """
3067 return self.is_flag and isinstance(self.type, types.BoolParamType)
3069 @property
3070 def flag_activation_value(self) -> t.Any:
3071 """Value the function receives when this flag is activated on the command line.
3073 Resolves a missing :attr:`flag_value` to ``True`` for actual flag options and
3074 ``None`` otherwise. Used by the parser bridge (:meth:`add_to_parser`) and the
3075 runtime (:meth:`consume_value`) so :attr:`flag_value` can keep the :data:`UNSET`
3076 sentinel for "did the user pass one?" introspection.
3077 """
3078 if self.flag_value is UNSET:
3079 return True if self.is_flag else None
3080 return self.flag_value
3082 def _infer_flag_kind(
3083 self, is_flag: bool | None, flag_value: t.Any
3084 ) -> tuple[bool, bool]:
3085 """Resolve ``is_flag`` and the parser hint ``_flag_needs_value``.
3087 Returns ``(is_flag, flag_needs_value)``, where ``_flag_needs_value`` tells the
3088 parser that the value of this option can be omitted: the option then prompts for
3089 a value if ``prompt`` is set, and otherwise uses its flag value. The parser uses
3090 it to decide whether to treat the next CLI token as the option's value or as a
3091 new option. If ``prompt`` is enabled with ``prompt_required=False``, it opens
3092 the door for an interactive value, hence the initial condition.
3093 """
3094 needs_value = self.prompt is not None and not self.prompt_required
3096 if is_flag is None:
3097 # Implicitly a flag because flag_value was set.
3098 if flag_value is not UNSET:
3099 return True, needs_value
3100 # Not a flag, but when used as a flag it shows a prompt.
3101 if needs_value:
3102 return False, needs_value
3103 # Implicitly a flag because secondary options names were given.
3104 if self.secondary_opts:
3105 return True, needs_value
3106 return False, needs_value
3108 if is_flag is False and not needs_value:
3109 # Explicit ``is_flag=False`` with a flag-like value/default still makes the
3110 # option flag-shaped to the parser.
3111 needs_value = flag_value is not UNSET or self.default is UNSET
3113 return bool(is_flag), needs_value
3115 def _pick_type(
3116 self,
3117 type_arg: t.Any,
3118 flag_value: t.Any,
3119 count: bool,
3120 is_flag: bool,
3121 ) -> types.ParamType[t.Any]:
3122 """Pick the final :class:`ParamType` for this option.
3124 :meth:`Parameter.__init__` already stored ``self.type`` from the explicit
3125 ``type`` argument or from ``default``. This method either returns that as-is, or
3126 overrides it for flag and count options (which are inferred from ``flag_value``
3127 rather than ``default``).
3128 """
3129 if type_arg is not None:
3130 return self.type
3132 if count:
3133 return types.IntRange(min=0)
3135 if not is_flag:
3136 return self.type
3138 # A flag without a flag_value is a boolean flag.
3139 if flag_value is UNSET or isinstance(flag_value, bool):
3140 return types.BoolParamType()
3142 guessed: types.ParamType[t.Any] = types.convert_type(None, flag_value)
3143 if (
3144 isinstance(guessed, types.StringParamType)
3145 and not isinstance(flag_value, str)
3146 and flag_value is not None
3147 ):
3148 # The flag_value type couldn't be auto-detected (not str, int, float, or
3149 # bool). Since flag_value is a programmer-provided Python object, not CLI
3150 # input, pass it through unchanged instead of stringifying it.
3151 return types.UNPROCESSED
3152 return guessed
3154 def _resolve_lazy_default(self, value: t.Any) -> t.Any:
3155 """Apply lazy auto-derivations to a default-style value.
3157 Shared between :meth:`get_default` (the runtime path) and :meth:`to_info_dict`
3158 (the introspection path) so the two views cannot drift apart. Callables are
3159 *not* invoked here: that is :meth:`get_default`'s responsibility. Rules:
3161 * ``UNSET`` resolves to ``False`` for a non-required boolean flag, and to ``()``
3162 for a non-required, non-prompted multi flag.
3163 * ``True`` resolves to :attr:`flag_value` for a non-boolean flag (the "activate
3164 this flag by default" shorthand). Boolean flags keep ``True`` as a literal.
3165 """
3166 if value is UNSET and self.is_flag:
3167 if self.multiple and not self.required and not self.prompt:
3168 return ()
3169 if self.is_bool_flag and not self.required:
3170 return False
3171 if value is True and self.is_flag and not self.is_bool_flag:
3172 # Use ``flag_activation_value`` so an unset ``flag_value`` resolves to
3173 # ``True`` (the bool-flag activation value) rather than leaking the
3174 # :data:`UNSET` sentinel.
3175 return self.flag_activation_value
3176 return value
3178 def _validate(self, prompt: bool | str, deprecated: bool | str) -> None:
3179 """Raise :class:`TypeError` / :class:`ValueError` on illegal kwarg combinations.
3181 Called once, after every other attribute has been assigned, so each check can
3182 read the final state.
3183 """
3184 if not __debug__:
3185 return
3186 if deprecated and prompt:
3187 raise ValueError("`deprecated` options cannot use `prompt`.")
3188 if self.nargs == -1:
3189 raise TypeError("nargs=-1 is not supported for options.")
3190 if not self.is_bool_flag and self.secondary_opts:
3191 raise TypeError("Secondary flag is not valid for non-boolean flag.")
3192 if self.is_bool_flag and self.hide_input and self.prompt is not None:
3193 raise TypeError("'prompt' with 'hide_input' is not valid for boolean flag.")
3194 if self.count:
3195 if self.multiple:
3196 raise TypeError("'count' is not valid with 'multiple'.")
3197 if self.is_flag:
3198 raise TypeError("'count' is not valid with 'is_flag'.")
3200 def to_info_dict(self) -> dict[str, t.Any]:
3201 """
3202 .. versionchanged:: 8.5.0
3203 ``default`` and ``flag_value`` reflect the auto-derived values (``False``
3204 for unset boolean-flag defaults, ``True`` for unset boolean-flag activation
3205 values, etc.) when no explicit value was passed, matching what the function
3206 would receive at call time.
3208 .. versionchanged:: 8.3.0
3209 Returns ``None`` for the :attr:`flag_value` if it was not set.
3210 """
3211 info_dict = super().to_info_dict()
3212 info_dict.update(
3213 default=self._hide_unset(self._resolve_lazy_default(self.default)),
3214 prompt=self.prompt,
3215 is_flag=self.is_flag,
3216 flag_value=self.flag_activation_value,
3217 count=self.count,
3218 hidden=self.hidden,
3219 )
3220 return info_dict
3222 def get_default(
3223 self, ctx: Context, call: bool = True
3224 ) -> t.Any | t.Callable[[], t.Any] | None:
3225 """Return the default value for this option.
3227 Several auto-derived defaults are resolved lazily here rather than eagerly in
3228 :meth:`__init__`. This keeps :attr:`default` raw at construction time, so
3229 ``self.default is UNSET`` reliably answers "did the user pass a default?" for
3230 anything that needs to distinguish "absent" from a chosen value. The resolution
3231 rules live in :meth:`_resolve_lazy_default`.
3233 .. versionchanged:: 8.5.0
3234 ``UNSET`` defaults for boolean and multi flags are now resolved here instead
3235 of being coerced in :meth:`__init__`. Reading :attr:`default` directly
3236 returns the user-supplied value (or ``UNSET`` if none was passed) rather
3237 than the auto-derived one.
3239 .. versionchanged:: 8.3.3
3240 ``default=True`` is no longer substituted with ``flag_value`` for boolean
3241 flags, fixing negative boolean flags like
3242 ``flag_value=False, default=True``.
3243 """
3244 raw = super().get_default(ctx, call=False)
3245 value = self._resolve_lazy_default(raw)
3246 # Only invoke the value as a callable when the lazy resolver passed it through
3247 # unchanged. If the resolver substituted ``True`` -> :attr:`flag_value`, the
3248 # result is the programmer-supplied ``flag_value`` (often a class or enum),
3249 # which must NOT be instantiated here.
3250 if value is raw and call and callable(value):
3251 value = value()
3252 return value
3254 def get_error_hint(self, ctx: Context | None) -> str:
3255 result = super().get_error_hint(ctx)
3256 if self.show_envvar and self.envvar:
3257 envvars = [self.envvar] if isinstance(self.envvar, str) else self.envvar
3258 # An environment variable is allowed to feature a space or a comma on all
3259 # platforms, hence the quotes around each.
3260 var_str = ", ".join(f"'{var}'" for var in envvars)
3261 result += f" (env var: {var_str})"
3262 return result
3264 def _parse_decls(
3265 self, decls: cabc.Sequence[str], expose_value: bool
3266 ) -> tuple[str, list[str], list[str]]:
3267 opts = []
3268 secondary_opts = []
3269 name = None
3270 possible_names = []
3272 for decl in decls:
3273 if decl.isidentifier():
3274 if name is not None:
3275 raise TypeError(_("Name '{name}' defined twice").format(name=name))
3276 name = decl
3277 else:
3278 split_char = ";" if decl[:1] == "/" else "/"
3279 if split_char in decl:
3280 first, second = decl.split(split_char, 1)
3281 first = first.rstrip()
3282 if first:
3283 possible_names.append(_split_opt(first))
3284 opts.append(first)
3285 second = second.lstrip()
3286 if second:
3287 secondary_opts.append(second.lstrip())
3288 if first == second:
3289 raise ValueError(
3290 _(
3291 "Boolean option {decl!r} cannot use the"
3292 " same flag for true/false."
3293 ).format(decl=decl)
3294 )
3295 else:
3296 possible_names.append(_split_opt(decl))
3297 opts.append(decl)
3299 if name is None and possible_names:
3300 possible_names.sort(key=lambda x: -len(x[0])) # group long options first
3301 name = possible_names[0][1].replace("-", "_").lower()
3302 if not name.isidentifier():
3303 name = None
3305 if name is None:
3306 if not expose_value:
3307 return "", opts, secondary_opts
3308 raise TypeError(
3309 _(
3310 "Could not determine name for option with declarations {decls!r}"
3311 ).format(decls=decls)
3312 )
3314 if not opts and not secondary_opts:
3315 raise TypeError(
3316 _(
3317 "No options defined but a name was passed ({name})."
3318 " Did you mean to declare an argument instead? Did"
3319 " you mean to pass '--{name}'?"
3320 ).format(name=name)
3321 )
3323 return name, opts, secondary_opts
3325 def add_to_parser(self, parser: _OptionParser, ctx: Context) -> None:
3326 if self.multiple:
3327 action = "append"
3328 elif self.count:
3329 action = "count"
3330 else:
3331 action = "store"
3333 if self.is_flag:
3334 action = f"{action}_const"
3336 if self.is_bool_flag and self.secondary_opts:
3337 parser.add_option(
3338 obj=self, opts=self.opts, dest=self.name, action=action, const=True
3339 )
3340 parser.add_option(
3341 obj=self,
3342 opts=self.secondary_opts,
3343 dest=self.name,
3344 action=action,
3345 const=False,
3346 )
3347 else:
3348 parser.add_option(
3349 obj=self,
3350 opts=self.opts,
3351 dest=self.name,
3352 action=action,
3353 # ``flag_activation_value`` resolves UNSET to the right parser-store
3354 # constant (``True`` for bool flags) so the raw :attr:`flag_value`
3355 # can keep the sentinel.
3356 const=self.flag_activation_value,
3357 )
3358 else:
3359 parser.add_option(
3360 obj=self,
3361 opts=self.opts,
3362 dest=self.name,
3363 action=action,
3364 nargs=self.nargs,
3365 )
3367 def get_help_spec(self, ctx: Context) -> str:
3368 """Returns the left column of the option's help record: its spellings
3369 and metavar, like ``-v, --verbose`` or ``-c, --config TEXT``.
3371 Unlike :meth:`get_help_record`, the spec is produced even when the
3372 option is :attr:`hidden`.
3374 .. versionadded:: 8.5.1
3375 """
3376 any_prefix_is_slash = False
3378 def _write_opts(opts: cabc.Sequence[str]) -> str:
3379 nonlocal any_prefix_is_slash
3381 rv, any_slashes = join_options(opts)
3383 if any_slashes:
3384 any_prefix_is_slash = True
3386 if not self.is_flag and not self.count:
3387 rv += f" {self.make_metavar(ctx=ctx)}"
3389 return rv
3391 rv = [_write_opts(self.opts)]
3393 if self.secondary_opts:
3394 rv.append(_write_opts(self.secondary_opts))
3396 return ("; " if any_prefix_is_slash else " / ").join(rv)
3398 def get_help_record(self, ctx: Context) -> tuple[str, str] | None:
3399 if self.hidden:
3400 return None
3402 help = self.help or ""
3404 extra = self.get_help_extra(ctx)
3405 extra_items = []
3406 if "envvars" in extra:
3407 extra_items.append(
3408 _("env var: {var}").format(var=", ".join(extra["envvars"]))
3409 )
3410 if "default" in extra:
3411 extra_items.append(_("default: {default}").format(default=extra["default"]))
3412 if "range" in extra:
3413 extra_items.append(extra["range"])
3414 if "required" in extra:
3415 extra_items.append(_(extra["required"]))
3417 if extra_items:
3418 extra_str = "; ".join(extra_items)
3419 help = f"{help} [{extra_str}]" if help else f"[{extra_str}]"
3421 return self.get_help_spec(ctx), help
3423 def get_help_extra(self, ctx: Context) -> types.OptionHelpExtra:
3424 extra: types.OptionHelpExtra = {}
3426 if self.show_envvar:
3427 envvar = self.envvar
3429 if not envvar and (
3430 self.allow_from_autoenv
3431 and ctx.auto_envvar_prefix is not None
3432 and self.name
3433 ):
3434 envvar = f"{ctx.auto_envvar_prefix}_{self.name.upper()}"
3436 if envvar:
3437 if isinstance(envvar, str):
3438 extra["envvars"] = (envvar,)
3439 else:
3440 extra["envvars"] = tuple(str(d) for d in envvar)
3442 # Temporarily enable resilient parsing to avoid type casting
3443 # failing for the default. Might be possible to extend this to
3444 # help formatting in general.
3445 resilient = ctx.resilient_parsing
3446 ctx.resilient_parsing = True
3448 try:
3449 default_value = self.get_default(ctx, call=False)
3450 finally:
3451 ctx.resilient_parsing = resilient
3453 show_default = False
3454 show_default_is_str = False
3456 if self.show_default is not None:
3457 if isinstance(self.show_default, str):
3458 show_default_is_str = show_default = True
3459 else:
3460 show_default = self.show_default
3461 elif ctx.show_default is not None:
3462 show_default = ctx.show_default
3464 if show_default_is_str or (
3465 show_default and (default_value not in (None, UNSET))
3466 ):
3467 if show_default_is_str:
3468 default_string = f"({self.show_default})"
3469 elif isinstance(default_value, (list, tuple)):
3470 default_string = ", ".join(str(d) for d in default_value)
3471 elif isinstance(default_value, enum.Enum):
3472 default_string = default_value.name
3473 elif inspect.isfunction(default_value):
3474 default_string = _("(dynamic)")
3475 elif self.is_bool_flag and self.secondary_opts:
3476 # For boolean flags that have distinct True/False opts,
3477 # use the opt without prefix instead of the value.
3478 default_string = _split_opt(
3479 (self.opts if default_value else self.secondary_opts)[0]
3480 )[1]
3481 elif self.is_bool_flag and not self.secondary_opts and not default_value:
3482 default_string = ""
3483 elif isinstance(default_value, str) and default_value == "":
3484 default_string = '""'
3485 else:
3486 default_string = str(default_value)
3488 if default_string:
3489 extra["default"] = default_string
3491 if (
3492 isinstance(self.type, types._NumberRangeBase)
3493 # skip count with default range type
3494 and not (self.count and self.type.min == 0 and self.type.max is None)
3495 ):
3496 range_str = self.type._describe_range()
3498 if range_str:
3499 extra["range"] = range_str
3501 if self.required:
3502 extra["required"] = "required"
3504 return extra
3506 def prompt_for_value(self, ctx: Context) -> t.Any:
3507 """This is an alternative flow that can be activated in the full
3508 value processing if a value does not exist. It will prompt the
3509 user until a valid value exists and then returns the processed
3510 value as result.
3511 """
3512 assert self.prompt is not None
3514 # Calculate the default before prompting anything to lock in the value before
3515 # attempting any user interaction.
3516 default = self.get_default(ctx)
3518 # A boolean flag can use a simplified [y/n] confirmation prompt.
3519 if self.is_bool_flag:
3520 # If we have no boolean default, we force the user to explicitly provide
3521 # one.
3522 if default in (UNSET, None):
3523 default = None
3524 # Nothing prevent you to declare an option that is simultaneously:
3525 # 1) auto-detected as a boolean flag,
3526 # 2) allowed to prompt, and
3527 # 3) still declare a non-boolean default.
3528 # This forced casting into a boolean is necessary to align any non-boolean
3529 # default to the prompt, which is going to be a [y/n]-style confirmation
3530 # because the option is still a boolean flag. That way, instead of [y/n], we
3531 # get [Y/n] or [y/N] depending on the truthy value of the default.
3532 else:
3533 default = bool(default)
3534 return confirm(self.prompt, default)
3536 # If show_default is given, provide this to `prompt` as well,
3537 # otherwise we use `prompt`'s default behavior
3538 prompt_kwargs: t.Any = {}
3539 if self.show_default is not None:
3540 prompt_kwargs["show_default"] = self.show_default
3542 return prompt(
3543 self.prompt,
3544 # Use ``None`` to inform the prompt() function to reiterate until a valid
3545 # value is provided by the user if we have no default.
3546 default=self._hide_unset(default),
3547 type=self.type,
3548 hide_input=self.hide_input,
3549 show_choices=self.show_choices,
3550 confirmation_prompt=self.confirmation_prompt,
3551 value_proc=lambda x: self.process_value(ctx, x),
3552 **prompt_kwargs,
3553 )
3555 def resolve_envvar_value(self, ctx: Context) -> str | None:
3556 """:class:`Option` resolves its environment variable the same way as
3557 :func:`Parameter.resolve_envvar_value`, but it also supports
3558 :attr:`Context.auto_envvar_prefix`. If we could not find an environment from
3559 the :attr:`envvar` property, we fallback on :attr:`Context.auto_envvar_prefix`
3560 to build dynamiccaly the environment variable name using the
3561 :python:`{ctx.auto_envvar_prefix}_{self.name.upper()}` template.
3563 :meta private:
3564 """
3565 rv = super().resolve_envvar_value(ctx)
3567 if rv is not None:
3568 return rv
3570 if self.allow_from_autoenv and ctx.auto_envvar_prefix is not None and self.name:
3571 envvar = f"{ctx.auto_envvar_prefix}_{self.name.upper()}"
3572 rv = os.environ.get(envvar)
3574 if rv:
3575 return rv
3577 return None
3579 def value_from_envvar(self, ctx: Context) -> t.Any:
3580 """For :class:`Option`, this method processes the raw environment variable
3581 string the same way as :func:`Parameter.value_from_envvar` does.
3583 But in the case of non-boolean flags, the value is analyzed to determine if the
3584 flag is activated or not, and returns a boolean of its activation, or the
3585 :attr:`flag_value` if the latter is set.
3587 This method also takes care of repeated options (i.e. options with
3588 :attr:`multiple` set to ``True``).
3590 :meta private:
3591 """
3592 rv = self.resolve_envvar_value(ctx)
3594 # Absent environment variable or an empty string is interpreted as unset.
3595 if rv is None:
3596 return None
3598 # Non-boolean flags are more liberal in what they accept. But a flag being a
3599 # flag, its envvar value still needs to be analyzed to determine if the flag is
3600 # activated or not.
3601 if self.is_flag and not self.is_bool_flag:
3602 # An exact match against ``flag_value`` (a non-bool flag always has one
3603 # explicitly set) returns it directly. Otherwise the value is analyzed as a
3604 # boolean: a truthy reading activates the flag and the function receives
3605 # ``flag_value``; a falsy reading produces ``False``; an unrecognized
3606 # reading falls through as ``None``. Folding the substitution here means
3607 # :meth:`consume_value` no longer has to repeat it in a source-checked
3608 # branch.
3609 if rv == self.flag_value:
3610 return self.flag_value
3611 parsed = types.BoolParamType.str_to_bool(rv)
3612 if parsed is None:
3613 return None
3614 return self.flag_value if parsed else False
3616 # Split the envvar value if it is allowed to be repeated.
3617 value_depth = (self.nargs != 1) + bool(self.multiple)
3618 if value_depth > 0:
3619 multi_rv = self.type.split_envvar_value(rv)
3620 if self.multiple and self.nargs != 1:
3621 multi_rv = batch(multi_rv, self.nargs) # type: ignore[assignment]
3623 return multi_rv
3625 return rv
3627 def consume_value(
3628 self, ctx: Context, opts: cabc.Mapping[str, Parameter]
3629 ) -> tuple[t.Any, ParameterSource]:
3630 """For :class:`Option`, the value can be collected from an interactive prompt
3631 if the option is a flag that needs a value (and the :attr:`prompt` property is
3632 set).
3634 Additionally, this method handles flag option that are activated without a
3635 value, in which case the :attr:`flag_value` is returned.
3637 :meta private:
3638 """
3639 value, source = super().consume_value(ctx, opts)
3641 # The parser emits a sentinel when a flag is allowed to be used without a value.
3642 # Resolve it to a prompt or to the activation value depending on the option's
3643 # configuration.
3644 if value is FLAG_NEEDS_VALUE:
3645 # If the option allows for a prompt, start an interaction with the user.
3646 if self.prompt is not None and not ctx.resilient_parsing:
3647 value = self.prompt_for_value(ctx)
3648 source = ParameterSource.PROMPT
3649 # Else the flag takes its activation value (resolves UNSET).
3650 else:
3651 value = self.flag_activation_value
3652 source = ParameterSource.COMMANDLINE
3654 # Re-interpret a multiple option that the parser sent through as a list still
3655 # containing the FLAG_NEEDS_VALUE sentinel, replacing each occurrence with the
3656 # activation value.
3657 elif (
3658 self.multiple
3659 and value is not UNSET
3660 and isinstance(value, cabc.Iterable)
3661 and source < ParameterSource.DEFAULT_MAP
3662 and any(v is FLAG_NEEDS_VALUE for v in value)
3663 ):
3664 value = [
3665 self.flag_activation_value if v is FLAG_NEEDS_VALUE else v
3666 for v in value
3667 ]
3668 source = ParameterSource.COMMANDLINE
3670 # The value wasn't set, or used the param's default, prompt for one to the user
3671 # if prompting is enabled.
3672 elif (
3673 (value is UNSET or source >= ParameterSource.DEFAULT_MAP)
3674 and self.prompt is not None
3675 and (self.required or self.prompt_required)
3676 and not ctx.resilient_parsing
3677 ):
3678 value = self.prompt_for_value(ctx)
3679 source = ParameterSource.PROMPT
3681 return value, source
3683 def process_value(self, ctx: Context, value: t.Any) -> t.Any:
3684 # process_value has to be overridden on Options in order to capture
3685 # `value == UNSET` cases before `type_cast_value()` gets called.
3686 if self.is_flag and not self.required and self.is_bool_flag and value is UNSET:
3687 value = False
3689 if self.callback is not None:
3690 value = self.callback(ctx, self, value)
3692 return value
3694 # in the normal case, rely on Parameter.process_value
3695 return super().process_value(ctx, value)
3698class Argument(Parameter):
3699 """Arguments are positional parameters to a command. They generally
3700 provide fewer features than options but can have infinite ``nargs``
3701 and are required by default.
3703 All parameters are passed onwards to the constructor of :class:`Parameter`.
3705 :param help: the help string.
3707 .. versionchanged:: 8.5.0
3708 Added the ``help`` parameter.
3709 """
3711 param_type_name = "argument"
3713 def __init__(
3714 self,
3715 param_decls: cabc.Sequence[str],
3716 required: bool | None = None,
3717 help: str | None = None,
3718 **attrs: t.Any,
3719 ) -> None:
3720 # Auto-detect the requirement status of the argument if not explicitly set.
3721 if required is None:
3722 # The argument gets automatically required if it has no explicit default
3723 # value set and is setup to match at least one value.
3724 if attrs.get("default", UNSET) is UNSET:
3725 required = attrs.get("nargs", 1) > 0
3726 # If the argument has a default value, it is not required.
3727 else:
3728 required = False
3730 if "multiple" in attrs:
3731 raise TypeError("__init__() got an unexpected keyword argument 'multiple'.")
3733 super().__init__(param_decls, required=required, help=help, **attrs)
3735 @property
3736 def human_readable_name(self) -> str:
3737 if self.metavar is not None:
3738 return self.metavar
3739 return self.name.upper()
3741 def make_metavar(self, ctx: Context) -> str:
3742 if self.metavar is not None:
3743 return self.metavar
3744 var = self.type.get_metavar(param=self, ctx=ctx)
3745 if not var:
3746 var = self.name.upper()
3747 # Types like ``Choice`` and ``DateTime`` already surround their metavar
3748 # with square brackets to enumerate the allowed values. Reuse those
3749 # outer brackets as the optional-argument indicator instead of wrapping
3750 # the metavar in a second pair, which would produce ``[[a|b|c]]``.
3751 already_bracketed = var.startswith("[") and var.endswith("]")
3752 if self.deprecated:
3753 var += "!"
3754 if not self.required and not already_bracketed:
3755 var = f"[{var}]"
3756 if self.nargs != 1:
3757 var += "..."
3758 return var
3760 def _parse_decls(
3761 self, decls: cabc.Sequence[str], expose_value: bool
3762 ) -> tuple[str, list[str], list[str]]:
3763 if not decls:
3764 if not expose_value:
3765 return "", [], []
3766 raise TypeError("Argument is marked as exposed, but does not have a name.")
3767 if len(decls) == 1:
3768 name = arg = decls[0]
3769 name = name.replace("-", "_").lower()
3770 else:
3771 raise TypeError(
3772 _(
3773 "Arguments take exactly one parameter declaration, got"
3774 " {length}: {decls}."
3775 ).format(length=len(decls), decls=decls)
3776 )
3777 return name, [arg], []
3779 def get_usage_pieces(self, ctx: Context) -> list[str]:
3780 return [self.make_metavar(ctx)]
3782 def get_help_record(self, ctx: Context) -> tuple[str, str]:
3783 """Returns the argument's help row: its metavar and its help text.
3785 Unlike :meth:`Option.get_help_record`, this never returns ``None``. An
3786 argument cannot be hidden, so an undocumented one still gets a row, with
3787 an empty description.
3789 .. versionchanged:: 8.5.1
3790 Always returns a tuple. It used to return ``None`` when ``help`` was
3791 not set.
3792 """
3793 return self.make_metavar(ctx), self.help or ""
3795 def get_error_hint(self, ctx: Context | None) -> str:
3796 if ctx is not None:
3797 return f"'{self.make_metavar(ctx)}'"
3798 return f"'{self.human_readable_name}'"
3800 def add_to_parser(self, parser: _OptionParser, ctx: Context) -> None:
3801 parser.add_argument(dest=self.name, nargs=self.nargs, obj=self)
3804def __getattr__(name: str) -> object:
3805 import warnings
3807 if name == "BaseCommand":
3808 warnings.warn(
3809 "'BaseCommand' is deprecated and will be removed in Click 9.0. Use"
3810 " 'Command' instead.",
3811 DeprecationWarning,
3812 stacklevel=2,
3813 )
3814 return _BaseCommand
3816 if name == "MultiCommand":
3817 warnings.warn(
3818 "'MultiCommand' is deprecated and will be removed in Click 9.0. Use"
3819 " 'Group' instead.",
3820 DeprecationWarning,
3821 stacklevel=2,
3822 )
3823 return _MultiCommand
3825 raise AttributeError(name)