Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/click/core.py: 32%
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1from __future__ import annotations
3import collections.abc as cabc
4import enum
5import errno
6import inspect
7import os
8import sys
9import typing as t
10from collections import abc
11from collections import Counter
12from contextlib import AbstractContextManager
13from contextlib import contextmanager
14from contextlib import ExitStack
15from functools import update_wrapper
16from gettext import gettext as _
17from gettext import ngettext
18from itertools import repeat
19from types import TracebackType
21from . import types
22from ._utils import FLAG_NEEDS_VALUE
23from ._utils import UNSET
24from .exceptions import Abort
25from .exceptions import BadParameter
26from .exceptions import ClickException
27from .exceptions import Exit
28from .exceptions import MissingParameter
29from .exceptions import NoArgsIsHelpError
30from .exceptions import UsageError
31from .formatting import HelpFormatter
32from .formatting import join_options
33from .globals import pop_context
34from .globals import push_context
35from .parser import _OptionParser
36from .parser import _split_opt
37from .termui import confirm
38from .termui import prompt
39from .termui import style
40from .utils import _detect_program_name
41from .utils import _expand_args
42from .utils import echo
43from .utils import make_default_short_help
44from .utils import make_str
45from .utils import PacifyFlushWrapper
47if t.TYPE_CHECKING:
48 from .shell_completion import CompletionItem
50F = t.TypeVar("F", bound="t.Callable[..., t.Any]")
51V = t.TypeVar("V")
54def _complete_visible_commands(
55 ctx: Context, incomplete: str
56) -> cabc.Iterator[tuple[str, Command]]:
57 """List all the subcommands of a group that start with the
58 incomplete value and aren't hidden.
60 :param ctx: Invocation context for the group.
61 :param incomplete: Value being completed. May be empty.
62 """
63 multi = t.cast(Group, ctx.command)
65 for name in multi.list_commands(ctx):
66 if name.startswith(incomplete):
67 command = multi.get_command(ctx, name)
69 if command is not None and not command.hidden:
70 yield name, command
73def _check_nested_chain(
74 base_command: Group, cmd_name: str, cmd: Command, register: bool = False
75) -> None:
76 if not base_command.chain or not isinstance(cmd, Group):
77 return
79 if register:
80 message = (
81 f"It is not possible to add the group {cmd_name!r} to another"
82 f" group {base_command.name!r} that is in chain mode."
83 )
84 else:
85 message = (
86 f"Found the group {cmd_name!r} as subcommand to another group "
87 f" {base_command.name!r} that is in chain mode. This is not supported."
88 )
90 raise RuntimeError(message)
93def batch(iterable: cabc.Iterable[V], batch_size: int) -> list[tuple[V, ...]]:
94 return list(zip(*repeat(iter(iterable), batch_size), strict=False))
97@contextmanager
98def augment_usage_errors(
99 ctx: Context, param: Parameter | None = None
100) -> cabc.Iterator[None]:
101 """Context manager that attaches extra information to exceptions."""
102 try:
103 yield
104 except BadParameter as e:
105 if e.ctx is None:
106 e.ctx = ctx
107 if param is not None and e.param is None:
108 e.param = param
109 raise
110 except UsageError as e:
111 if e.ctx is None:
112 e.ctx = ctx
113 raise
116def iter_params_for_processing(
117 invocation_order: cabc.Sequence[Parameter],
118 declaration_order: cabc.Sequence[Parameter],
119) -> list[Parameter]:
120 """Returns all declared parameters in the order they should be processed.
122 The declared parameters are re-shuffled depending on the order in which
123 they were invoked, as well as the eagerness of each parameters.
125 The invocation order takes precedence over the declaration order. I.e. the
126 order in which the user provided them to the CLI is respected.
128 This behavior and its effect on callback evaluation is detailed at:
129 https://click.palletsprojects.com/en/stable/advanced/#callback-evaluation-order
130 """
132 def sort_key(item: Parameter) -> tuple[bool, float]:
133 try:
134 idx: float = invocation_order.index(item)
135 except ValueError:
136 idx = float("inf")
138 return not item.is_eager, idx
140 return sorted(declaration_order, key=sort_key)
143class ParameterSource(enum.Enum):
144 """This is an :class:`~enum.Enum` that indicates the source of a
145 parameter's value.
147 Use :meth:`click.Context.get_parameter_source` to get the
148 source for a parameter by name.
150 .. versionchanged:: 8.0
151 Use :class:`~enum.Enum` and drop the ``validate`` method.
153 .. versionchanged:: 8.0
154 Added the ``PROMPT`` value.
155 """
157 COMMANDLINE = enum.auto()
158 """The value was provided by the command line args."""
159 ENVIRONMENT = enum.auto()
160 """The value was provided with an environment variable."""
161 DEFAULT = enum.auto()
162 """Used the default specified by the parameter."""
163 DEFAULT_MAP = enum.auto()
164 """Used a default provided by :attr:`Context.default_map`."""
165 PROMPT = enum.auto()
166 """Used a prompt to confirm a default or provide a value."""
169class Context:
170 """The context is a special internal object that holds state relevant
171 for the script execution at every single level. It's normally invisible
172 to commands unless they opt-in to getting access to it.
174 The context is useful as it can pass internal objects around and can
175 control special execution features such as reading data from
176 environment variables.
178 A context can be used as context manager in which case it will call
179 :meth:`close` on teardown.
181 :param command: the command class for this context.
182 :param parent: the parent context.
183 :param info_name: the info name for this invocation. Generally this
184 is the most descriptive name for the script or
185 command. For the toplevel script it is usually
186 the name of the script, for commands below it it's
187 the name of the script.
188 :param obj: an arbitrary object of user data.
189 :param auto_envvar_prefix: the prefix to use for automatic environment
190 variables. If this is `None` then reading
191 from environment variables is disabled. This
192 does not affect manually set environment
193 variables which are always read.
194 :param default_map: a dictionary (like object) with default values
195 for parameters.
196 :param terminal_width: the width of the terminal. The default is
197 inherit from parent context. If no context
198 defines the terminal width then auto
199 detection will be applied.
200 :param max_content_width: the maximum width for content rendered by
201 Click (this currently only affects help
202 pages). This defaults to 80 characters if
203 not overridden. In other words: even if the
204 terminal is larger than that, Click will not
205 format things wider than 80 characters by
206 default. In addition to that, formatters might
207 add some safety mapping on the right.
208 :param resilient_parsing: if this flag is enabled then Click will
209 parse without any interactivity or callback
210 invocation. Default values will also be
211 ignored. This is useful for implementing
212 things such as completion support.
213 :param allow_extra_args: if this is set to `True` then extra arguments
214 at the end will not raise an error and will be
215 kept on the context. The default is to inherit
216 from the command.
217 :param allow_interspersed_args: if this is set to `False` then options
218 and arguments cannot be mixed. The
219 default is to inherit from the command.
220 :param ignore_unknown_options: instructs click to ignore options it does
221 not know and keeps them for later
222 processing.
223 :param help_option_names: optionally a list of strings that define how
224 the default help parameter is named. The
225 default is ``['--help']``.
226 :param token_normalize_func: an optional function that is used to
227 normalize tokens (options, choices,
228 etc.). This for instance can be used to
229 implement case insensitive behavior.
230 :param color: controls if the terminal supports ANSI colors or not. The
231 default is autodetection. This is only needed if ANSI
232 codes are used in texts that Click prints which is by
233 default not the case. This for instance would affect
234 help output.
235 :param show_default: Show the default value for commands. If this
236 value is not set, it defaults to the value from the parent
237 context. ``Command.show_default`` overrides this default for the
238 specific command.
240 .. versionchanged:: 8.2
241 The ``protected_args`` attribute is deprecated and will be removed in
242 Click 9.0. ``args`` will contain remaining unparsed tokens.
244 .. versionchanged:: 8.1
245 The ``show_default`` parameter is overridden by
246 ``Command.show_default``, instead of the other way around.
248 .. versionchanged:: 8.0
249 The ``show_default`` parameter defaults to the value from the
250 parent context.
252 .. versionchanged:: 7.1
253 Added the ``show_default`` parameter.
255 .. versionchanged:: 4.0
256 Added the ``color``, ``ignore_unknown_options``, and
257 ``max_content_width`` parameters.
259 .. versionchanged:: 3.0
260 Added the ``allow_extra_args`` and ``allow_interspersed_args``
261 parameters.
263 .. versionchanged:: 2.0
264 Added the ``resilient_parsing``, ``help_option_names``, and
265 ``token_normalize_func`` parameters.
266 """
268 #: The formatter class to create with :meth:`make_formatter`.
269 #:
270 #: .. versionadded:: 8.0
271 formatter_class: type[HelpFormatter] = HelpFormatter
273 def __init__(
274 self,
275 command: Command,
276 parent: Context | None = None,
277 info_name: str | None = None,
278 obj: t.Any | None = None,
279 auto_envvar_prefix: str | None = None,
280 default_map: cabc.MutableMapping[str, t.Any] | None = None,
281 terminal_width: int | None = None,
282 max_content_width: int | None = None,
283 resilient_parsing: bool = False,
284 allow_extra_args: bool | None = None,
285 allow_interspersed_args: bool | None = None,
286 ignore_unknown_options: bool | None = None,
287 help_option_names: list[str] | None = None,
288 token_normalize_func: t.Callable[[str], str] | None = None,
289 color: bool | None = None,
290 show_default: bool | None = None,
291 ) -> None:
292 #: the parent context or `None` if none exists.
293 self.parent = parent
294 #: the :class:`Command` for this context.
295 self.command = command
296 #: the descriptive information name
297 self.info_name = info_name
298 #: Map of parameter names to their parsed values. Parameters
299 #: with ``expose_value=False`` are not stored.
300 self.params: dict[str, t.Any] = {}
301 #: the leftover arguments.
302 self.args: list[str] = []
303 #: protected arguments. These are arguments that are prepended
304 #: to `args` when certain parsing scenarios are encountered but
305 #: must be never propagated to another arguments. This is used
306 #: to implement nested parsing.
307 self._protected_args: list[str] = []
308 #: the collected prefixes of the command's options.
309 self._opt_prefixes: set[str] = set(parent._opt_prefixes) if parent else set()
311 if obj is None and parent is not None:
312 obj = parent.obj
314 #: the user object stored.
315 self.obj: t.Any = obj
316 self._meta: dict[str, t.Any] = getattr(parent, "meta", {})
318 #: A dictionary (-like object) with defaults for parameters.
319 if (
320 default_map is None
321 and info_name is not None
322 and parent is not None
323 and parent.default_map is not None
324 ):
325 default_map = parent.default_map.get(info_name)
327 self.default_map: cabc.MutableMapping[str, t.Any] | None = default_map
329 #: This flag indicates if a subcommand is going to be executed. A
330 #: group callback can use this information to figure out if it's
331 #: being executed directly or because the execution flow passes
332 #: onwards to a subcommand. By default it's None, but it can be
333 #: the name of the subcommand to execute.
334 #:
335 #: If chaining is enabled this will be set to ``'*'`` in case
336 #: any commands are executed. It is however not possible to
337 #: figure out which ones. If you require this knowledge you
338 #: should use a :func:`result_callback`.
339 self.invoked_subcommand: str | None = None
341 if terminal_width is None and parent is not None:
342 terminal_width = parent.terminal_width
344 #: The width of the terminal (None is autodetection).
345 self.terminal_width: int | None = terminal_width
347 if max_content_width is None and parent is not None:
348 max_content_width = parent.max_content_width
350 #: The maximum width of formatted content (None implies a sensible
351 #: default which is 80 for most things).
352 self.max_content_width: int | None = max_content_width
354 if allow_extra_args is None:
355 allow_extra_args = command.allow_extra_args
357 #: Indicates if the context allows extra args or if it should
358 #: fail on parsing.
359 #:
360 #: .. versionadded:: 3.0
361 self.allow_extra_args = allow_extra_args
363 if allow_interspersed_args is None:
364 allow_interspersed_args = command.allow_interspersed_args
366 #: Indicates if the context allows mixing of arguments and
367 #: options or not.
368 #:
369 #: .. versionadded:: 3.0
370 self.allow_interspersed_args: bool = allow_interspersed_args
372 if ignore_unknown_options is None:
373 ignore_unknown_options = command.ignore_unknown_options
375 #: Instructs click to ignore options that a command does not
376 #: understand and will store it on the context for later
377 #: processing. This is primarily useful for situations where you
378 #: want to call into external programs. Generally this pattern is
379 #: strongly discouraged because it's not possibly to losslessly
380 #: forward all arguments.
381 #:
382 #: .. versionadded:: 4.0
383 self.ignore_unknown_options: bool = ignore_unknown_options
385 if help_option_names is None:
386 if parent is not None:
387 help_option_names = parent.help_option_names
388 else:
389 help_option_names = ["--help"]
391 #: The names for the help options.
392 self.help_option_names: list[str] = help_option_names
394 if token_normalize_func is None and parent is not None:
395 token_normalize_func = parent.token_normalize_func
397 #: An optional normalization function for tokens. This is
398 #: options, choices, commands etc.
399 self.token_normalize_func: t.Callable[[str], str] | None = token_normalize_func
401 #: Indicates if resilient parsing is enabled. In that case Click
402 #: will do its best to not cause any failures and default values
403 #: will be ignored. Useful for completion.
404 self.resilient_parsing: bool = resilient_parsing
406 # If there is no envvar prefix yet, but the parent has one and
407 # the command on this level has a name, we can expand the envvar
408 # prefix automatically.
409 if auto_envvar_prefix is None:
410 if (
411 parent is not None
412 and parent.auto_envvar_prefix is not None
413 and self.info_name is not None
414 ):
415 auto_envvar_prefix = (
416 f"{parent.auto_envvar_prefix}_{self.info_name.upper()}"
417 )
418 else:
419 auto_envvar_prefix = auto_envvar_prefix.upper()
421 if auto_envvar_prefix is not None:
422 auto_envvar_prefix = auto_envvar_prefix.replace("-", "_")
424 self.auto_envvar_prefix: str | None = auto_envvar_prefix
426 if color is None and parent is not None:
427 color = parent.color
429 #: Controls if styling output is wanted or not.
430 self.color: bool | None = color
432 if show_default is None and parent is not None:
433 show_default = parent.show_default
435 #: Show option default values when formatting help text.
436 self.show_default: bool | None = show_default
438 self._close_callbacks: list[t.Callable[[], t.Any]] = []
439 self._depth = 0
440 self._parameter_source: dict[str, ParameterSource] = {}
441 self._exit_stack = ExitStack()
443 @property
444 def protected_args(self) -> list[str]:
445 import warnings
447 warnings.warn(
448 "'protected_args' is deprecated and will be removed in Click 9.0."
449 " 'args' will contain remaining unparsed tokens.",
450 DeprecationWarning,
451 stacklevel=2,
452 )
453 return self._protected_args
455 def to_info_dict(self) -> dict[str, t.Any]:
456 """Gather information that could be useful for a tool generating
457 user-facing documentation. This traverses the entire CLI
458 structure.
460 .. code-block:: python
462 with Context(cli) as ctx:
463 info = ctx.to_info_dict()
465 .. versionadded:: 8.0
466 """
467 return {
468 "command": self.command.to_info_dict(self),
469 "info_name": self.info_name,
470 "allow_extra_args": self.allow_extra_args,
471 "allow_interspersed_args": self.allow_interspersed_args,
472 "ignore_unknown_options": self.ignore_unknown_options,
473 "auto_envvar_prefix": self.auto_envvar_prefix,
474 }
476 def __enter__(self) -> Context:
477 self._depth += 1
478 push_context(self)
479 return self
481 def __exit__(
482 self,
483 exc_type: type[BaseException] | None,
484 exc_value: BaseException | None,
485 tb: TracebackType | None,
486 ) -> bool | None:
487 self._depth -= 1
488 exit_result: bool | None = None
489 if self._depth == 0:
490 exit_result = self._close_with_exception_info(exc_type, exc_value, tb)
491 pop_context()
493 return exit_result
495 @contextmanager
496 def scope(self, cleanup: bool = True) -> cabc.Iterator[Context]:
497 """This helper method can be used with the context object to promote
498 it to the current thread local (see :func:`get_current_context`).
499 The default behavior of this is to invoke the cleanup functions which
500 can be disabled by setting `cleanup` to `False`. The cleanup
501 functions are typically used for things such as closing file handles.
503 If the cleanup is intended the context object can also be directly
504 used as a context manager.
506 Example usage::
508 with ctx.scope():
509 assert get_current_context() is ctx
511 This is equivalent::
513 with ctx:
514 assert get_current_context() is ctx
516 .. versionadded:: 5.0
518 :param cleanup: controls if the cleanup functions should be run or
519 not. The default is to run these functions. In
520 some situations the context only wants to be
521 temporarily pushed in which case this can be disabled.
522 Nested pushes automatically defer the cleanup.
523 """
524 if not cleanup:
525 self._depth += 1
526 try:
527 with self as rv:
528 yield rv
529 finally:
530 if not cleanup:
531 self._depth -= 1
533 @property
534 def meta(self) -> dict[str, t.Any]:
535 """This is a dictionary which is shared with all the contexts
536 that are nested. It exists so that click utilities can store some
537 state here if they need to. It is however the responsibility of
538 that code to manage this dictionary well.
540 The keys are supposed to be unique dotted strings. For instance
541 module paths are a good choice for it. What is stored in there is
542 irrelevant for the operation of click. However what is important is
543 that code that places data here adheres to the general semantics of
544 the system.
546 Example usage::
548 LANG_KEY = f'{__name__}.lang'
550 def set_language(value):
551 ctx = get_current_context()
552 ctx.meta[LANG_KEY] = value
554 def get_language():
555 return get_current_context().meta.get(LANG_KEY, 'en_US')
557 .. versionadded:: 5.0
558 """
559 return self._meta
561 def make_formatter(self) -> HelpFormatter:
562 """Creates the :class:`~click.HelpFormatter` for the help and
563 usage output.
565 To quickly customize the formatter class used without overriding
566 this method, set the :attr:`formatter_class` attribute.
568 .. versionchanged:: 8.0
569 Added the :attr:`formatter_class` attribute.
570 """
571 return self.formatter_class(
572 width=self.terminal_width, max_width=self.max_content_width
573 )
575 def with_resource(self, context_manager: AbstractContextManager[V]) -> V:
576 """Register a resource as if it were used in a ``with``
577 statement. The resource will be cleaned up when the context is
578 popped.
580 Uses :meth:`contextlib.ExitStack.enter_context`. It calls the
581 resource's ``__enter__()`` method and returns the result. When
582 the context is popped, it closes the stack, which calls the
583 resource's ``__exit__()`` method.
585 To register a cleanup function for something that isn't a
586 context manager, use :meth:`call_on_close`. Or use something
587 from :mod:`contextlib` to turn it into a context manager first.
589 .. code-block:: python
591 @click.group()
592 @click.option("--name")
593 @click.pass_context
594 def cli(ctx):
595 ctx.obj = ctx.with_resource(connect_db(name))
597 :param context_manager: The context manager to enter.
598 :return: Whatever ``context_manager.__enter__()`` returns.
600 .. versionadded:: 8.0
601 """
602 return self._exit_stack.enter_context(context_manager)
604 def call_on_close(self, f: t.Callable[..., t.Any]) -> t.Callable[..., t.Any]:
605 """Register a function to be called when the context tears down.
607 This can be used to close resources opened during the script
608 execution. Resources that support Python's context manager
609 protocol which would be used in a ``with`` statement should be
610 registered with :meth:`with_resource` instead.
612 :param f: The function to execute on teardown.
613 """
614 return self._exit_stack.callback(f)
616 def close(self) -> None:
617 """Invoke all close callbacks registered with
618 :meth:`call_on_close`, and exit all context managers entered
619 with :meth:`with_resource`.
620 """
621 self._close_with_exception_info(None, None, None)
623 def _close_with_exception_info(
624 self,
625 exc_type: type[BaseException] | None,
626 exc_value: BaseException | None,
627 tb: TracebackType | None,
628 ) -> bool | None:
629 """Unwind the exit stack by calling its :meth:`__exit__` providing the exception
630 information to allow for exception handling by the various resources registered
631 using :meth;`with_resource`
633 :return: Whatever ``exit_stack.__exit__()`` returns.
634 """
635 exit_result = self._exit_stack.__exit__(exc_type, exc_value, tb)
636 # In case the context is reused, create a new exit stack.
637 self._exit_stack = ExitStack()
639 return exit_result
641 @property
642 def command_path(self) -> str:
643 """The computed command path. This is used for the ``usage``
644 information on the help page. It's automatically created by
645 combining the info names of the chain of contexts to the root.
646 """
647 rv = ""
648 if self.info_name is not None:
649 rv = self.info_name
650 if self.parent is not None:
651 parent_command_path = [self.parent.command_path]
653 if isinstance(self.parent.command, Command):
654 for param in self.parent.command.get_params(self):
655 parent_command_path.extend(param.get_usage_pieces(self))
657 rv = f"{' '.join(parent_command_path)} {rv}"
658 return rv.lstrip()
660 def find_root(self) -> Context:
661 """Finds the outermost context."""
662 node = self
663 while node.parent is not None:
664 node = node.parent
665 return node
667 def find_object(self, object_type: type[V]) -> V | None:
668 """Finds the closest object of a given type."""
669 node: Context | None = self
671 while node is not None:
672 if isinstance(node.obj, object_type):
673 return node.obj
675 node = node.parent
677 return None
679 def ensure_object(self, object_type: type[V]) -> V:
680 """Like :meth:`find_object` but sets the innermost object to a
681 new instance of `object_type` if it does not exist.
682 """
683 rv = self.find_object(object_type)
684 if rv is None:
685 self.obj = rv = object_type()
686 return rv
688 @t.overload
689 def lookup_default(
690 self, name: str, call: t.Literal[True] = True
691 ) -> t.Any | None: ...
693 @t.overload
694 def lookup_default(
695 self, name: str, call: t.Literal[False] = ...
696 ) -> t.Any | t.Callable[[], t.Any] | None: ...
698 def lookup_default(self, name: str, call: bool = True) -> t.Any | None:
699 """Get the default for a parameter from :attr:`default_map`.
701 :param name: Name of the parameter.
702 :param call: If the default is a callable, call it. Disable to
703 return the callable instead.
705 .. versionchanged:: 8.0
706 Added the ``call`` parameter.
707 """
708 if self.default_map is not None:
709 value = self.default_map.get(name, UNSET)
711 if call and callable(value):
712 return value()
714 return value
716 return UNSET
718 def fail(self, message: str) -> t.NoReturn:
719 """Aborts the execution of the program with a specific error
720 message.
722 :param message: the error message to fail with.
723 """
724 raise UsageError(message, self)
726 def abort(self) -> t.NoReturn:
727 """Aborts the script."""
728 raise Abort()
730 def exit(self, code: int = 0) -> t.NoReturn:
731 """Exits the application with a given exit code.
733 .. versionchanged:: 8.2
734 Callbacks and context managers registered with :meth:`call_on_close`
735 and :meth:`with_resource` are closed before exiting.
736 """
737 self.close()
738 raise Exit(code)
740 def get_usage(self) -> str:
741 """Helper method to get formatted usage string for the current
742 context and command.
743 """
744 return self.command.get_usage(self)
746 def get_help(self) -> str:
747 """Helper method to get formatted help page for the current
748 context and command.
749 """
750 return self.command.get_help(self)
752 def _make_sub_context(self, command: Command) -> Context:
753 """Create a new context of the same type as this context, but
754 for a new command.
756 :meta private:
757 """
758 return type(self)(command, info_name=command.name, parent=self)
760 @t.overload
761 def invoke(
762 self, callback: t.Callable[..., V], /, *args: t.Any, **kwargs: t.Any
763 ) -> V: ...
765 @t.overload
766 def invoke(self, callback: Command, /, *args: t.Any, **kwargs: t.Any) -> t.Any: ...
768 def invoke(
769 self, callback: Command | t.Callable[..., V], /, *args: t.Any, **kwargs: t.Any
770 ) -> t.Any | V:
771 """Invokes a command callback in exactly the way it expects. There
772 are two ways to invoke this method:
774 1. the first argument can be a callback and all other arguments and
775 keyword arguments are forwarded directly to the function.
776 2. the first argument is a click command object. In that case all
777 arguments are forwarded as well but proper click parameters
778 (options and click arguments) must be keyword arguments and Click
779 will fill in defaults.
781 .. versionchanged:: 8.0
782 All ``kwargs`` are tracked in :attr:`params` so they will be
783 passed if :meth:`forward` is called at multiple levels.
785 .. versionchanged:: 3.2
786 A new context is created, and missing arguments use default values.
787 """
788 if isinstance(callback, Command):
789 other_cmd = callback
791 if other_cmd.callback is None:
792 raise TypeError(
793 "The given command does not have a callback that can be invoked."
794 )
795 else:
796 callback = t.cast("t.Callable[..., V]", other_cmd.callback)
798 ctx = self._make_sub_context(other_cmd)
800 for param in other_cmd.params:
801 if param.name not in kwargs and param.expose_value:
802 default_value = param.get_default(ctx)
803 # We explicitly hide the :attr:`UNSET` value to the user, as we
804 # choose to make it an implementation detail. And because ``invoke``
805 # has been designed as part of Click public API, we return ``None``
806 # instead. Refs:
807 # https://github.com/pallets/click/issues/3066
808 # https://github.com/pallets/click/issues/3065
809 # https://github.com/pallets/click/pull/3068
810 if default_value is UNSET:
811 default_value = None
812 kwargs[param.name] = param.type_cast_value( # type: ignore
813 ctx, default_value
814 )
816 # Track all kwargs as params, so that forward() will pass
817 # them on in subsequent calls.
818 ctx.params.update(kwargs)
819 else:
820 ctx = self
822 with augment_usage_errors(self):
823 with ctx:
824 return callback(*args, **kwargs)
826 def forward(self, cmd: Command, /, *args: t.Any, **kwargs: t.Any) -> t.Any:
827 """Similar to :meth:`invoke` but fills in default keyword
828 arguments from the current context if the other command expects
829 it. This cannot invoke callbacks directly, only other commands.
831 .. versionchanged:: 8.0
832 All ``kwargs`` are tracked in :attr:`params` so they will be
833 passed if ``forward`` is called at multiple levels.
834 """
835 # Can only forward to other commands, not direct callbacks.
836 if not isinstance(cmd, Command):
837 raise TypeError("Callback is not a command.")
839 for param in self.params:
840 if param not in kwargs:
841 kwargs[param] = self.params[param]
843 return self.invoke(cmd, *args, **kwargs)
845 def set_parameter_source(self, name: str, source: ParameterSource) -> None:
846 """Set the source of a parameter. This indicates the location
847 from which the value of the parameter was obtained.
849 :param name: The name of the parameter.
850 :param source: A member of :class:`~click.core.ParameterSource`.
851 """
852 self._parameter_source[name] = source
854 def get_parameter_source(self, name: str) -> ParameterSource | None:
855 """Get the source of a parameter. This indicates the location
856 from which the value of the parameter was obtained.
858 This can be useful for determining when a user specified a value
859 on the command line that is the same as the default value. It
860 will be :attr:`~click.core.ParameterSource.DEFAULT` only if the
861 value was actually taken from the default.
863 :param name: The name of the parameter.
864 :rtype: ParameterSource
866 .. versionchanged:: 8.0
867 Returns ``None`` if the parameter was not provided from any
868 source.
869 """
870 return self._parameter_source.get(name)
873class Command:
874 """Commands are the basic building block of command line interfaces in
875 Click. A basic command handles command line parsing and might dispatch
876 more parsing to commands nested below it.
878 :param name: the name of the command to use unless a group overrides it.
879 :param context_settings: an optional dictionary with defaults that are
880 passed to the context object.
881 :param callback: the callback to invoke. This is optional.
882 :param params: the parameters to register with this command. This can
883 be either :class:`Option` or :class:`Argument` objects.
884 :param help: the help string to use for this command.
885 :param epilog: like the help string but it's printed at the end of the
886 help page after everything else.
887 :param short_help: the short help to use for this command. This is
888 shown on the command listing of the parent command.
889 :param add_help_option: by default each command registers a ``--help``
890 option. This can be disabled by this parameter.
891 :param no_args_is_help: this controls what happens if no arguments are
892 provided. This option is disabled by default.
893 If enabled this will add ``--help`` as argument
894 if no arguments are passed
895 :param hidden: hide this command from help outputs.
896 :param deprecated: If ``True`` or non-empty string, issues a message
897 indicating that the command is deprecated and highlights
898 its deprecation in --help. The message can be customized
899 by using a string as the value.
901 .. versionchanged:: 8.2
902 This is the base class for all commands, not ``BaseCommand``.
903 ``deprecated`` can be set to a string as well to customize the
904 deprecation message.
906 .. versionchanged:: 8.1
907 ``help``, ``epilog``, and ``short_help`` are stored unprocessed,
908 all formatting is done when outputting help text, not at init,
909 and is done even if not using the ``@command`` decorator.
911 .. versionchanged:: 8.0
912 Added a ``repr`` showing the command name.
914 .. versionchanged:: 7.1
915 Added the ``no_args_is_help`` parameter.
917 .. versionchanged:: 2.0
918 Added the ``context_settings`` parameter.
919 """
921 #: The context class to create with :meth:`make_context`.
922 #:
923 #: .. versionadded:: 8.0
924 context_class: type[Context] = Context
926 #: the default for the :attr:`Context.allow_extra_args` flag.
927 allow_extra_args = False
929 #: the default for the :attr:`Context.allow_interspersed_args` flag.
930 allow_interspersed_args = True
932 #: the default for the :attr:`Context.ignore_unknown_options` flag.
933 ignore_unknown_options = False
935 def __init__(
936 self,
937 name: str | None,
938 context_settings: cabc.MutableMapping[str, t.Any] | None = None,
939 callback: t.Callable[..., t.Any] | None = None,
940 params: list[Parameter] | None = None,
941 help: str | None = None,
942 epilog: str | None = None,
943 short_help: str | None = None,
944 options_metavar: str | None = "[OPTIONS]",
945 add_help_option: bool = True,
946 no_args_is_help: bool = False,
947 hidden: bool = False,
948 deprecated: bool | str = False,
949 ) -> None:
950 #: the name the command thinks it has. Upon registering a command
951 #: on a :class:`Group` the group will default the command name
952 #: with this information. You should instead use the
953 #: :class:`Context`\'s :attr:`~Context.info_name` attribute.
954 self.name = name
956 if context_settings is None:
957 context_settings = {}
959 #: an optional dictionary with defaults passed to the context.
960 self.context_settings: cabc.MutableMapping[str, t.Any] = context_settings
962 #: the callback to execute when the command fires. This might be
963 #: `None` in which case nothing happens.
964 self.callback = callback
965 #: the list of parameters for this command in the order they
966 #: should show up in the help page and execute. Eager parameters
967 #: will automatically be handled before non eager ones.
968 self.params: list[Parameter] = params or []
969 self.help = help
970 self.epilog = epilog
971 self.options_metavar = options_metavar
972 self.short_help = short_help
973 self.add_help_option = add_help_option
974 self._help_option = None
975 self.no_args_is_help = no_args_is_help
976 self.hidden = hidden
977 self.deprecated = deprecated
979 def to_info_dict(self, ctx: Context) -> dict[str, t.Any]:
980 return {
981 "name": self.name,
982 "params": [param.to_info_dict() for param in self.get_params(ctx)],
983 "help": self.help,
984 "epilog": self.epilog,
985 "short_help": self.short_help,
986 "hidden": self.hidden,
987 "deprecated": self.deprecated,
988 }
990 def __repr__(self) -> str:
991 return f"<{self.__class__.__name__} {self.name}>"
993 def get_usage(self, ctx: Context) -> str:
994 """Formats the usage line into a string and returns it.
996 Calls :meth:`format_usage` internally.
997 """
998 formatter = ctx.make_formatter()
999 self.format_usage(ctx, formatter)
1000 return formatter.getvalue().rstrip("\n")
1002 def get_params(self, ctx: Context) -> list[Parameter]:
1003 params = self.params
1004 help_option = self.get_help_option(ctx)
1006 if help_option is not None:
1007 params = [*params, help_option]
1009 if __debug__:
1010 import warnings
1012 opts = [opt for param in params for opt in param.opts]
1013 opts_counter = Counter(opts)
1014 duplicate_opts = (opt for opt, count in opts_counter.items() if count > 1)
1016 for duplicate_opt in duplicate_opts:
1017 warnings.warn(
1018 (
1019 f"The parameter {duplicate_opt} is used more than once. "
1020 "Remove its duplicate as parameters should be unique."
1021 ),
1022 stacklevel=3,
1023 )
1025 return params
1027 def format_usage(self, ctx: Context, formatter: HelpFormatter) -> None:
1028 """Writes the usage line into the formatter.
1030 This is a low-level method called by :meth:`get_usage`.
1031 """
1032 pieces = self.collect_usage_pieces(ctx)
1033 formatter.write_usage(ctx.command_path, " ".join(pieces))
1035 def collect_usage_pieces(self, ctx: Context) -> list[str]:
1036 """Returns all the pieces that go into the usage line and returns
1037 it as a list of strings.
1038 """
1039 rv = [self.options_metavar] if self.options_metavar else []
1041 for param in self.get_params(ctx):
1042 rv.extend(param.get_usage_pieces(ctx))
1044 return rv
1046 def get_help_option_names(self, ctx: Context) -> list[str]:
1047 """Returns the names for the help option."""
1048 all_names = set(ctx.help_option_names)
1049 for param in self.params:
1050 all_names.difference_update(param.opts)
1051 all_names.difference_update(param.secondary_opts)
1052 return list(all_names)
1054 def get_help_option(self, ctx: Context) -> Option | None:
1055 """Returns the help option object.
1057 Skipped if :attr:`add_help_option` is ``False``.
1059 .. versionchanged:: 8.1.8
1060 The help option is now cached to avoid creating it multiple times.
1061 """
1062 help_option_names = self.get_help_option_names(ctx)
1064 if not help_option_names or not self.add_help_option:
1065 return None
1067 # Cache the help option object in private _help_option attribute to
1068 # avoid creating it multiple times. Not doing this will break the
1069 # callback odering by iter_params_for_processing(), which relies on
1070 # object comparison.
1071 if self._help_option is None:
1072 # Avoid circular import.
1073 from .decorators import help_option
1075 # Apply help_option decorator and pop resulting option
1076 help_option(*help_option_names)(self)
1077 self._help_option = self.params.pop() # type: ignore[assignment]
1079 return self._help_option
1081 def make_parser(self, ctx: Context) -> _OptionParser:
1082 """Creates the underlying option parser for this command."""
1083 parser = _OptionParser(ctx)
1084 for param in self.get_params(ctx):
1085 param.add_to_parser(parser, ctx)
1086 return parser
1088 def get_help(self, ctx: Context) -> str:
1089 """Formats the help into a string and returns it.
1091 Calls :meth:`format_help` internally.
1092 """
1093 formatter = ctx.make_formatter()
1094 self.format_help(ctx, formatter)
1095 return formatter.getvalue().rstrip("\n")
1097 def get_short_help_str(self, limit: int = 45) -> str:
1098 """Gets short help for the command or makes it by shortening the
1099 long help string.
1100 """
1101 if self.short_help:
1102 text = inspect.cleandoc(self.short_help)
1103 elif self.help:
1104 text = make_default_short_help(self.help, limit)
1105 else:
1106 text = ""
1108 if self.deprecated:
1109 deprecated_message = (
1110 f"(DEPRECATED: {self.deprecated})"
1111 if isinstance(self.deprecated, str)
1112 else "(DEPRECATED)"
1113 )
1114 text = _("{text} {deprecated_message}").format(
1115 text=text, deprecated_message=deprecated_message
1116 )
1118 return text.strip()
1120 def format_help(self, ctx: Context, formatter: HelpFormatter) -> None:
1121 """Writes the help into the formatter if it exists.
1123 This is a low-level method called by :meth:`get_help`.
1125 This calls the following methods:
1127 - :meth:`format_usage`
1128 - :meth:`format_help_text`
1129 - :meth:`format_options`
1130 - :meth:`format_epilog`
1131 """
1132 self.format_usage(ctx, formatter)
1133 self.format_help_text(ctx, formatter)
1134 self.format_options(ctx, formatter)
1135 self.format_epilog(ctx, formatter)
1137 def format_help_text(self, ctx: Context, formatter: HelpFormatter) -> None:
1138 """Writes the help text to the formatter if it exists."""
1139 if self.help is not None:
1140 # truncate the help text to the first form feed
1141 text = inspect.cleandoc(self.help).partition("\f")[0]
1142 else:
1143 text = ""
1145 if self.deprecated:
1146 deprecated_message = (
1147 f"(DEPRECATED: {self.deprecated})"
1148 if isinstance(self.deprecated, str)
1149 else "(DEPRECATED)"
1150 )
1151 text = _("{text} {deprecated_message}").format(
1152 text=text, deprecated_message=deprecated_message
1153 )
1155 if text:
1156 formatter.write_paragraph()
1158 with formatter.indentation():
1159 formatter.write_text(text)
1161 def format_options(self, ctx: Context, formatter: HelpFormatter) -> None:
1162 """Writes all the options into the formatter if they exist."""
1163 opts = []
1164 for param in self.get_params(ctx):
1165 rv = param.get_help_record(ctx)
1166 if rv is not None:
1167 opts.append(rv)
1169 if opts:
1170 with formatter.section(_("Options")):
1171 formatter.write_dl(opts)
1173 def format_epilog(self, ctx: Context, formatter: HelpFormatter) -> None:
1174 """Writes the epilog into the formatter if it exists."""
1175 if self.epilog:
1176 epilog = inspect.cleandoc(self.epilog)
1177 formatter.write_paragraph()
1179 with formatter.indentation():
1180 formatter.write_text(epilog)
1182 def make_context(
1183 self,
1184 info_name: str | None,
1185 args: list[str],
1186 parent: Context | None = None,
1187 **extra: t.Any,
1188 ) -> Context:
1189 """This function when given an info name and arguments will kick
1190 off the parsing and create a new :class:`Context`. It does not
1191 invoke the actual command callback though.
1193 To quickly customize the context class used without overriding
1194 this method, set the :attr:`context_class` attribute.
1196 :param info_name: the info name for this invocation. Generally this
1197 is the most descriptive name for the script or
1198 command. For the toplevel script it's usually
1199 the name of the script, for commands below it's
1200 the name of the command.
1201 :param args: the arguments to parse as list of strings.
1202 :param parent: the parent context if available.
1203 :param extra: extra keyword arguments forwarded to the context
1204 constructor.
1206 .. versionchanged:: 8.0
1207 Added the :attr:`context_class` attribute.
1208 """
1209 for key, value in self.context_settings.items():
1210 if key not in extra:
1211 extra[key] = value
1213 ctx = self.context_class(self, info_name=info_name, parent=parent, **extra)
1215 with ctx.scope(cleanup=False):
1216 self.parse_args(ctx, args)
1217 return ctx
1219 def parse_args(self, ctx: Context, args: list[str]) -> list[str]:
1220 if not args and self.no_args_is_help and not ctx.resilient_parsing:
1221 raise NoArgsIsHelpError(ctx)
1223 parser = self.make_parser(ctx)
1224 opts, args, param_order = parser.parse_args(args=args)
1226 for param in iter_params_for_processing(param_order, self.get_params(ctx)):
1227 _, args = param.handle_parse_result(ctx, opts, args)
1229 # We now have all parameters' values into `ctx.params`, but the data may contain
1230 # the `UNSET` sentinel.
1231 # Convert `UNSET` to `None` to ensure that the user doesn't see `UNSET`.
1232 #
1233 # Waiting until after the initial parse to convert allows us to treat `UNSET`
1234 # more like a missing value when multiple params use the same name.
1235 # Refs:
1236 # https://github.com/pallets/click/issues/3071
1237 # https://github.com/pallets/click/pull/3079
1238 for name, value in ctx.params.items():
1239 if value is UNSET:
1240 ctx.params[name] = None
1242 if args and not ctx.allow_extra_args and not ctx.resilient_parsing:
1243 ctx.fail(
1244 ngettext(
1245 "Got unexpected extra argument ({args})",
1246 "Got unexpected extra arguments ({args})",
1247 len(args),
1248 ).format(args=" ".join(map(str, args)))
1249 )
1251 ctx.args = args
1252 ctx._opt_prefixes.update(parser._opt_prefixes)
1253 return args
1255 def invoke(self, ctx: Context) -> t.Any:
1256 """Given a context, this invokes the attached callback (if it exists)
1257 in the right way.
1258 """
1259 if self.deprecated:
1260 extra_message = (
1261 f" {self.deprecated}" if isinstance(self.deprecated, str) else ""
1262 )
1263 message = _(
1264 "DeprecationWarning: The command {name!r} is deprecated.{extra_message}"
1265 ).format(name=self.name, extra_message=extra_message)
1266 echo(style(message, fg="red"), err=True)
1268 if self.callback is not None:
1269 return ctx.invoke(self.callback, **ctx.params)
1271 def shell_complete(self, ctx: Context, incomplete: str) -> list[CompletionItem]:
1272 """Return a list of completions for the incomplete value. Looks
1273 at the names of options and chained multi-commands.
1275 Any command could be part of a chained multi-command, so sibling
1276 commands are valid at any point during command completion.
1278 :param ctx: Invocation context for this command.
1279 :param incomplete: Value being completed. May be empty.
1281 .. versionadded:: 8.0
1282 """
1283 from click.shell_completion import CompletionItem
1285 results: list[CompletionItem] = []
1287 if incomplete and not incomplete[0].isalnum():
1288 for param in self.get_params(ctx):
1289 if (
1290 not isinstance(param, Option)
1291 or param.hidden
1292 or (
1293 not param.multiple
1294 and ctx.get_parameter_source(param.name) # type: ignore
1295 is ParameterSource.COMMANDLINE
1296 )
1297 ):
1298 continue
1300 results.extend(
1301 CompletionItem(name, help=param.help)
1302 for name in [*param.opts, *param.secondary_opts]
1303 if name.startswith(incomplete)
1304 )
1306 while ctx.parent is not None:
1307 ctx = ctx.parent
1309 if isinstance(ctx.command, Group) and ctx.command.chain:
1310 results.extend(
1311 CompletionItem(name, help=command.get_short_help_str())
1312 for name, command in _complete_visible_commands(ctx, incomplete)
1313 if name not in ctx._protected_args
1314 )
1316 return results
1318 @t.overload
1319 def main(
1320 self,
1321 args: cabc.Sequence[str] | None = None,
1322 prog_name: str | None = None,
1323 complete_var: str | None = None,
1324 standalone_mode: t.Literal[True] = True,
1325 **extra: t.Any,
1326 ) -> t.NoReturn: ...
1328 @t.overload
1329 def main(
1330 self,
1331 args: cabc.Sequence[str] | None = None,
1332 prog_name: str | None = None,
1333 complete_var: str | None = None,
1334 standalone_mode: bool = ...,
1335 **extra: t.Any,
1336 ) -> t.Any: ...
1338 def main(
1339 self,
1340 args: cabc.Sequence[str] | None = None,
1341 prog_name: str | None = None,
1342 complete_var: str | None = None,
1343 standalone_mode: bool = True,
1344 windows_expand_args: bool = True,
1345 **extra: t.Any,
1346 ) -> t.Any:
1347 """This is the way to invoke a script with all the bells and
1348 whistles as a command line application. This will always terminate
1349 the application after a call. If this is not wanted, ``SystemExit``
1350 needs to be caught.
1352 This method is also available by directly calling the instance of
1353 a :class:`Command`.
1355 :param args: the arguments that should be used for parsing. If not
1356 provided, ``sys.argv[1:]`` is used.
1357 :param prog_name: the program name that should be used. By default
1358 the program name is constructed by taking the file
1359 name from ``sys.argv[0]``.
1360 :param complete_var: the environment variable that controls the
1361 bash completion support. The default is
1362 ``"_<prog_name>_COMPLETE"`` with prog_name in
1363 uppercase.
1364 :param standalone_mode: the default behavior is to invoke the script
1365 in standalone mode. Click will then
1366 handle exceptions and convert them into
1367 error messages and the function will never
1368 return but shut down the interpreter. If
1369 this is set to `False` they will be
1370 propagated to the caller and the return
1371 value of this function is the return value
1372 of :meth:`invoke`.
1373 :param windows_expand_args: Expand glob patterns, user dir, and
1374 env vars in command line args on Windows.
1375 :param extra: extra keyword arguments are forwarded to the context
1376 constructor. See :class:`Context` for more information.
1378 .. versionchanged:: 8.0.1
1379 Added the ``windows_expand_args`` parameter to allow
1380 disabling command line arg expansion on Windows.
1382 .. versionchanged:: 8.0
1383 When taking arguments from ``sys.argv`` on Windows, glob
1384 patterns, user dir, and env vars are expanded.
1386 .. versionchanged:: 3.0
1387 Added the ``standalone_mode`` parameter.
1388 """
1389 if args is None:
1390 args = sys.argv[1:]
1392 if os.name == "nt" and windows_expand_args:
1393 args = _expand_args(args)
1394 else:
1395 args = list(args)
1397 if prog_name is None:
1398 prog_name = _detect_program_name()
1400 # Process shell completion requests and exit early.
1401 self._main_shell_completion(extra, prog_name, complete_var)
1403 try:
1404 try:
1405 with self.make_context(prog_name, args, **extra) as ctx:
1406 rv = self.invoke(ctx)
1407 if not standalone_mode:
1408 return rv
1409 # it's not safe to `ctx.exit(rv)` here!
1410 # note that `rv` may actually contain data like "1" which
1411 # has obvious effects
1412 # more subtle case: `rv=[None, None]` can come out of
1413 # chained commands which all returned `None` -- so it's not
1414 # even always obvious that `rv` indicates success/failure
1415 # by its truthiness/falsiness
1416 ctx.exit()
1417 except (EOFError, KeyboardInterrupt) as e:
1418 echo(file=sys.stderr)
1419 raise Abort() from e
1420 except ClickException as e:
1421 if not standalone_mode:
1422 raise
1423 e.show()
1424 sys.exit(e.exit_code)
1425 except OSError as e:
1426 if e.errno == errno.EPIPE:
1427 sys.stdout = t.cast(t.TextIO, PacifyFlushWrapper(sys.stdout))
1428 sys.stderr = t.cast(t.TextIO, PacifyFlushWrapper(sys.stderr))
1429 sys.exit(1)
1430 else:
1431 raise
1432 except Exit as e:
1433 if standalone_mode:
1434 sys.exit(e.exit_code)
1435 else:
1436 # in non-standalone mode, return the exit code
1437 # note that this is only reached if `self.invoke` above raises
1438 # an Exit explicitly -- thus bypassing the check there which
1439 # would return its result
1440 # the results of non-standalone execution may therefore be
1441 # somewhat ambiguous: if there are codepaths which lead to
1442 # `ctx.exit(1)` and to `return 1`, the caller won't be able to
1443 # tell the difference between the two
1444 return e.exit_code
1445 except Abort:
1446 if not standalone_mode:
1447 raise
1448 echo(_("Aborted!"), file=sys.stderr)
1449 sys.exit(1)
1451 def _main_shell_completion(
1452 self,
1453 ctx_args: cabc.MutableMapping[str, t.Any],
1454 prog_name: str,
1455 complete_var: str | None = None,
1456 ) -> None:
1457 """Check if the shell is asking for tab completion, process
1458 that, then exit early. Called from :meth:`main` before the
1459 program is invoked.
1461 :param prog_name: Name of the executable in the shell.
1462 :param complete_var: Name of the environment variable that holds
1463 the completion instruction. Defaults to
1464 ``_{PROG_NAME}_COMPLETE``.
1466 .. versionchanged:: 8.2.0
1467 Dots (``.``) in ``prog_name`` are replaced with underscores (``_``).
1468 """
1469 if complete_var is None:
1470 complete_name = prog_name.replace("-", "_").replace(".", "_")
1471 complete_var = f"_{complete_name}_COMPLETE".upper()
1473 instruction = os.environ.get(complete_var)
1475 if not instruction:
1476 return
1478 from .shell_completion import shell_complete
1480 rv = shell_complete(self, ctx_args, prog_name, complete_var, instruction)
1481 sys.exit(rv)
1483 def __call__(self, *args: t.Any, **kwargs: t.Any) -> t.Any:
1484 """Alias for :meth:`main`."""
1485 return self.main(*args, **kwargs)
1488class _FakeSubclassCheck(type):
1489 def __subclasscheck__(cls, subclass: type) -> bool:
1490 return issubclass(subclass, cls.__bases__[0])
1492 def __instancecheck__(cls, instance: t.Any) -> bool:
1493 return isinstance(instance, cls.__bases__[0])
1496class _BaseCommand(Command, metaclass=_FakeSubclassCheck):
1497 """
1498 .. deprecated:: 8.2
1499 Will be removed in Click 9.0. Use ``Command`` instead.
1500 """
1503class Group(Command):
1504 """A group is a command that nests other commands (or more groups).
1506 :param name: The name of the group command.
1507 :param commands: Map names to :class:`Command` objects. Can be a list, which
1508 will use :attr:`Command.name` as the keys.
1509 :param invoke_without_command: Invoke the group's callback even if a
1510 subcommand is not given.
1511 :param no_args_is_help: If no arguments are given, show the group's help and
1512 exit. Defaults to the opposite of ``invoke_without_command``.
1513 :param subcommand_metavar: How to represent the subcommand argument in help.
1514 The default will represent whether ``chain`` is set or not.
1515 :param chain: Allow passing more than one subcommand argument. After parsing
1516 a command's arguments, if any arguments remain another command will be
1517 matched, and so on.
1518 :param result_callback: A function to call after the group's and
1519 subcommand's callbacks. The value returned by the subcommand is passed.
1520 If ``chain`` is enabled, the value will be a list of values returned by
1521 all the commands. If ``invoke_without_command`` is enabled, the value
1522 will be the value returned by the group's callback, or an empty list if
1523 ``chain`` is enabled.
1524 :param kwargs: Other arguments passed to :class:`Command`.
1526 .. versionchanged:: 8.0
1527 The ``commands`` argument can be a list of command objects.
1529 .. versionchanged:: 8.2
1530 Merged with and replaces the ``MultiCommand`` base class.
1531 """
1533 allow_extra_args = True
1534 allow_interspersed_args = False
1536 #: If set, this is used by the group's :meth:`command` decorator
1537 #: as the default :class:`Command` class. This is useful to make all
1538 #: subcommands use a custom command class.
1539 #:
1540 #: .. versionadded:: 8.0
1541 command_class: type[Command] | None = None
1543 #: If set, this is used by the group's :meth:`group` decorator
1544 #: as the default :class:`Group` class. This is useful to make all
1545 #: subgroups use a custom group class.
1546 #:
1547 #: If set to the special value :class:`type` (literally
1548 #: ``group_class = type``), this group's class will be used as the
1549 #: default class. This makes a custom group class continue to make
1550 #: custom groups.
1551 #:
1552 #: .. versionadded:: 8.0
1553 group_class: type[Group] | type[type] | None = None
1554 # Literal[type] isn't valid, so use Type[type]
1556 def __init__(
1557 self,
1558 name: str | None = None,
1559 commands: cabc.MutableMapping[str, Command]
1560 | cabc.Sequence[Command]
1561 | None = None,
1562 invoke_without_command: bool = False,
1563 no_args_is_help: bool | None = None,
1564 subcommand_metavar: str | None = None,
1565 chain: bool = False,
1566 result_callback: t.Callable[..., t.Any] | None = None,
1567 **kwargs: t.Any,
1568 ) -> None:
1569 super().__init__(name, **kwargs)
1571 if commands is None:
1572 commands = {}
1573 elif isinstance(commands, abc.Sequence):
1574 commands = {c.name: c for c in commands if c.name is not None}
1576 #: The registered subcommands by their exported names.
1577 self.commands: cabc.MutableMapping[str, Command] = commands
1579 if no_args_is_help is None:
1580 no_args_is_help = not invoke_without_command
1582 self.no_args_is_help = no_args_is_help
1583 self.invoke_without_command = invoke_without_command
1585 if subcommand_metavar is None:
1586 if chain:
1587 subcommand_metavar = "COMMAND1 [ARGS]... [COMMAND2 [ARGS]...]..."
1588 else:
1589 subcommand_metavar = "COMMAND [ARGS]..."
1591 self.subcommand_metavar = subcommand_metavar
1592 self.chain = chain
1593 # The result callback that is stored. This can be set or
1594 # overridden with the :func:`result_callback` decorator.
1595 self._result_callback = result_callback
1597 if self.chain:
1598 for param in self.params:
1599 if isinstance(param, Argument) and not param.required:
1600 raise RuntimeError(
1601 "A group in chain mode cannot have optional arguments."
1602 )
1604 def to_info_dict(self, ctx: Context) -> dict[str, t.Any]:
1605 info_dict = super().to_info_dict(ctx)
1606 commands = {}
1608 for name in self.list_commands(ctx):
1609 command = self.get_command(ctx, name)
1611 if command is None:
1612 continue
1614 sub_ctx = ctx._make_sub_context(command)
1616 with sub_ctx.scope(cleanup=False):
1617 commands[name] = command.to_info_dict(sub_ctx)
1619 info_dict.update(commands=commands, chain=self.chain)
1620 return info_dict
1622 def add_command(self, cmd: Command, name: str | None = None) -> None:
1623 """Registers another :class:`Command` with this group. If the name
1624 is not provided, the name of the command is used.
1625 """
1626 name = name or cmd.name
1627 if name is None:
1628 raise TypeError("Command has no name.")
1629 _check_nested_chain(self, name, cmd, register=True)
1630 self.commands[name] = cmd
1632 @t.overload
1633 def command(self, __func: t.Callable[..., t.Any]) -> Command: ...
1635 @t.overload
1636 def command(
1637 self, *args: t.Any, **kwargs: t.Any
1638 ) -> t.Callable[[t.Callable[..., t.Any]], Command]: ...
1640 def command(
1641 self, *args: t.Any, **kwargs: t.Any
1642 ) -> t.Callable[[t.Callable[..., t.Any]], Command] | Command:
1643 """A shortcut decorator for declaring and attaching a command to
1644 the group. This takes the same arguments as :func:`command` and
1645 immediately registers the created command with this group by
1646 calling :meth:`add_command`.
1648 To customize the command class used, set the
1649 :attr:`command_class` attribute.
1651 .. versionchanged:: 8.1
1652 This decorator can be applied without parentheses.
1654 .. versionchanged:: 8.0
1655 Added the :attr:`command_class` attribute.
1656 """
1657 from .decorators import command
1659 func: t.Callable[..., t.Any] | None = None
1661 if args and callable(args[0]):
1662 assert len(args) == 1 and not kwargs, (
1663 "Use 'command(**kwargs)(callable)' to provide arguments."
1664 )
1665 (func,) = args
1666 args = ()
1668 if self.command_class and kwargs.get("cls") is None:
1669 kwargs["cls"] = self.command_class
1671 def decorator(f: t.Callable[..., t.Any]) -> Command:
1672 cmd: Command = command(*args, **kwargs)(f)
1673 self.add_command(cmd)
1674 return cmd
1676 if func is not None:
1677 return decorator(func)
1679 return decorator
1681 @t.overload
1682 def group(self, __func: t.Callable[..., t.Any]) -> Group: ...
1684 @t.overload
1685 def group(
1686 self, *args: t.Any, **kwargs: t.Any
1687 ) -> t.Callable[[t.Callable[..., t.Any]], Group]: ...
1689 def group(
1690 self, *args: t.Any, **kwargs: t.Any
1691 ) -> t.Callable[[t.Callable[..., t.Any]], Group] | Group:
1692 """A shortcut decorator for declaring and attaching a group to
1693 the group. This takes the same arguments as :func:`group` and
1694 immediately registers the created group with this group by
1695 calling :meth:`add_command`.
1697 To customize the group class used, set the :attr:`group_class`
1698 attribute.
1700 .. versionchanged:: 8.1
1701 This decorator can be applied without parentheses.
1703 .. versionchanged:: 8.0
1704 Added the :attr:`group_class` attribute.
1705 """
1706 from .decorators import group
1708 func: t.Callable[..., t.Any] | None = None
1710 if args and callable(args[0]):
1711 assert len(args) == 1 and not kwargs, (
1712 "Use 'group(**kwargs)(callable)' to provide arguments."
1713 )
1714 (func,) = args
1715 args = ()
1717 if self.group_class is not None and kwargs.get("cls") is None:
1718 if self.group_class is type:
1719 kwargs["cls"] = type(self)
1720 else:
1721 kwargs["cls"] = self.group_class
1723 def decorator(f: t.Callable[..., t.Any]) -> Group:
1724 cmd: Group = group(*args, **kwargs)(f)
1725 self.add_command(cmd)
1726 return cmd
1728 if func is not None:
1729 return decorator(func)
1731 return decorator
1733 def result_callback(self, replace: bool = False) -> t.Callable[[F], F]:
1734 """Adds a result callback to the command. By default if a
1735 result callback is already registered this will chain them but
1736 this can be disabled with the `replace` parameter. The result
1737 callback is invoked with the return value of the subcommand
1738 (or the list of return values from all subcommands if chaining
1739 is enabled) as well as the parameters as they would be passed
1740 to the main callback.
1742 Example::
1744 @click.group()
1745 @click.option('-i', '--input', default=23)
1746 def cli(input):
1747 return 42
1749 @cli.result_callback()
1750 def process_result(result, input):
1751 return result + input
1753 :param replace: if set to `True` an already existing result
1754 callback will be removed.
1756 .. versionchanged:: 8.0
1757 Renamed from ``resultcallback``.
1759 .. versionadded:: 3.0
1760 """
1762 def decorator(f: F) -> F:
1763 old_callback = self._result_callback
1765 if old_callback is None or replace:
1766 self._result_callback = f
1767 return f
1769 def function(value: t.Any, /, *args: t.Any, **kwargs: t.Any) -> t.Any:
1770 inner = old_callback(value, *args, **kwargs)
1771 return f(inner, *args, **kwargs)
1773 self._result_callback = rv = update_wrapper(t.cast(F, function), f)
1774 return rv # type: ignore[return-value]
1776 return decorator
1778 def get_command(self, ctx: Context, cmd_name: str) -> Command | None:
1779 """Given a context and a command name, this returns a :class:`Command`
1780 object if it exists or returns ``None``.
1781 """
1782 return self.commands.get(cmd_name)
1784 def list_commands(self, ctx: Context) -> list[str]:
1785 """Returns a list of subcommand names in the order they should appear."""
1786 return sorted(self.commands)
1788 def collect_usage_pieces(self, ctx: Context) -> list[str]:
1789 rv = super().collect_usage_pieces(ctx)
1790 rv.append(self.subcommand_metavar)
1791 return rv
1793 def format_options(self, ctx: Context, formatter: HelpFormatter) -> None:
1794 super().format_options(ctx, formatter)
1795 self.format_commands(ctx, formatter)
1797 def format_commands(self, ctx: Context, formatter: HelpFormatter) -> None:
1798 """Extra format methods for multi methods that adds all the commands
1799 after the options.
1800 """
1801 commands = []
1802 for subcommand in self.list_commands(ctx):
1803 cmd = self.get_command(ctx, subcommand)
1804 # What is this, the tool lied about a command. Ignore it
1805 if cmd is None:
1806 continue
1807 if cmd.hidden:
1808 continue
1810 commands.append((subcommand, cmd))
1812 # allow for 3 times the default spacing
1813 if len(commands):
1814 limit = formatter.width - 6 - max(len(cmd[0]) for cmd in commands)
1816 rows = []
1817 for subcommand, cmd in commands:
1818 help = cmd.get_short_help_str(limit)
1819 rows.append((subcommand, help))
1821 if rows:
1822 with formatter.section(_("Commands")):
1823 formatter.write_dl(rows)
1825 def parse_args(self, ctx: Context, args: list[str]) -> list[str]:
1826 if not args and self.no_args_is_help and not ctx.resilient_parsing:
1827 raise NoArgsIsHelpError(ctx)
1829 rest = super().parse_args(ctx, args)
1831 if self.chain:
1832 ctx._protected_args = rest
1833 ctx.args = []
1834 elif rest:
1835 ctx._protected_args, ctx.args = rest[:1], rest[1:]
1837 return ctx.args
1839 def invoke(self, ctx: Context) -> t.Any:
1840 def _process_result(value: t.Any) -> t.Any:
1841 if self._result_callback is not None:
1842 value = ctx.invoke(self._result_callback, value, **ctx.params)
1843 return value
1845 if not ctx._protected_args:
1846 if self.invoke_without_command:
1847 # No subcommand was invoked, so the result callback is
1848 # invoked with the group return value for regular
1849 # groups, or an empty list for chained groups.
1850 with ctx:
1851 rv = super().invoke(ctx)
1852 return _process_result([] if self.chain else rv)
1853 ctx.fail(_("Missing command."))
1855 # Fetch args back out
1856 args = [*ctx._protected_args, *ctx.args]
1857 ctx.args = []
1858 ctx._protected_args = []
1860 # If we're not in chain mode, we only allow the invocation of a
1861 # single command but we also inform the current context about the
1862 # name of the command to invoke.
1863 if not self.chain:
1864 # Make sure the context is entered so we do not clean up
1865 # resources until the result processor has worked.
1866 with ctx:
1867 cmd_name, cmd, args = self.resolve_command(ctx, args)
1868 assert cmd is not None
1869 ctx.invoked_subcommand = cmd_name
1870 super().invoke(ctx)
1871 sub_ctx = cmd.make_context(cmd_name, args, parent=ctx)
1872 with sub_ctx:
1873 return _process_result(sub_ctx.command.invoke(sub_ctx))
1875 # In chain mode we create the contexts step by step, but after the
1876 # base command has been invoked. Because at that point we do not
1877 # know the subcommands yet, the invoked subcommand attribute is
1878 # set to ``*`` to inform the command that subcommands are executed
1879 # but nothing else.
1880 with ctx:
1881 ctx.invoked_subcommand = "*" if args else None
1882 super().invoke(ctx)
1884 # Otherwise we make every single context and invoke them in a
1885 # chain. In that case the return value to the result processor
1886 # is the list of all invoked subcommand's results.
1887 contexts = []
1888 while args:
1889 cmd_name, cmd, args = self.resolve_command(ctx, args)
1890 assert cmd is not None
1891 sub_ctx = cmd.make_context(
1892 cmd_name,
1893 args,
1894 parent=ctx,
1895 allow_extra_args=True,
1896 allow_interspersed_args=False,
1897 )
1898 contexts.append(sub_ctx)
1899 args, sub_ctx.args = sub_ctx.args, []
1901 rv = []
1902 for sub_ctx in contexts:
1903 with sub_ctx:
1904 rv.append(sub_ctx.command.invoke(sub_ctx))
1905 return _process_result(rv)
1907 def resolve_command(
1908 self, ctx: Context, args: list[str]
1909 ) -> tuple[str | None, Command | None, list[str]]:
1910 cmd_name = make_str(args[0])
1911 original_cmd_name = cmd_name
1913 # Get the command
1914 cmd = self.get_command(ctx, cmd_name)
1916 # If we can't find the command but there is a normalization
1917 # function available, we try with that one.
1918 if cmd is None and ctx.token_normalize_func is not None:
1919 cmd_name = ctx.token_normalize_func(cmd_name)
1920 cmd = self.get_command(ctx, cmd_name)
1922 # If we don't find the command we want to show an error message
1923 # to the user that it was not provided. However, there is
1924 # something else we should do: if the first argument looks like
1925 # an option we want to kick off parsing again for arguments to
1926 # resolve things like --help which now should go to the main
1927 # place.
1928 if cmd is None and not ctx.resilient_parsing:
1929 if _split_opt(cmd_name)[0]:
1930 self.parse_args(ctx, args)
1931 ctx.fail(_("No such command {name!r}.").format(name=original_cmd_name))
1932 return cmd_name if cmd else None, cmd, args[1:]
1934 def shell_complete(self, ctx: Context, incomplete: str) -> list[CompletionItem]:
1935 """Return a list of completions for the incomplete value. Looks
1936 at the names of options, subcommands, and chained
1937 multi-commands.
1939 :param ctx: Invocation context for this command.
1940 :param incomplete: Value being completed. May be empty.
1942 .. versionadded:: 8.0
1943 """
1944 from click.shell_completion import CompletionItem
1946 results = [
1947 CompletionItem(name, help=command.get_short_help_str())
1948 for name, command in _complete_visible_commands(ctx, incomplete)
1949 ]
1950 results.extend(super().shell_complete(ctx, incomplete))
1951 return results
1954class _MultiCommand(Group, metaclass=_FakeSubclassCheck):
1955 """
1956 .. deprecated:: 8.2
1957 Will be removed in Click 9.0. Use ``Group`` instead.
1958 """
1961class CommandCollection(Group):
1962 """A :class:`Group` that looks up subcommands on other groups. If a command
1963 is not found on this group, each registered source is checked in order.
1964 Parameters on a source are not added to this group, and a source's callback
1965 is not invoked when invoking its commands. In other words, this "flattens"
1966 commands in many groups into this one group.
1968 :param name: The name of the group command.
1969 :param sources: A list of :class:`Group` objects to look up commands from.
1970 :param kwargs: Other arguments passed to :class:`Group`.
1972 .. versionchanged:: 8.2
1973 This is a subclass of ``Group``. Commands are looked up first on this
1974 group, then each of its sources.
1975 """
1977 def __init__(
1978 self,
1979 name: str | None = None,
1980 sources: list[Group] | None = None,
1981 **kwargs: t.Any,
1982 ) -> None:
1983 super().__init__(name, **kwargs)
1984 #: The list of registered groups.
1985 self.sources: list[Group] = sources or []
1987 def add_source(self, group: Group) -> None:
1988 """Add a group as a source of commands."""
1989 self.sources.append(group)
1991 def get_command(self, ctx: Context, cmd_name: str) -> Command | None:
1992 rv = super().get_command(ctx, cmd_name)
1994 if rv is not None:
1995 return rv
1997 for source in self.sources:
1998 rv = source.get_command(ctx, cmd_name)
2000 if rv is not None:
2001 if self.chain:
2002 _check_nested_chain(self, cmd_name, rv)
2004 return rv
2006 return None
2008 def list_commands(self, ctx: Context) -> list[str]:
2009 rv: set[str] = set(super().list_commands(ctx))
2011 for source in self.sources:
2012 rv.update(source.list_commands(ctx))
2014 return sorted(rv)
2017def _check_iter(value: t.Any) -> cabc.Iterator[t.Any]:
2018 """Check if the value is iterable but not a string. Raises a type
2019 error, or return an iterator over the value.
2020 """
2021 if isinstance(value, str):
2022 raise TypeError
2024 return iter(value)
2027class Parameter:
2028 r"""A parameter to a command comes in two versions: they are either
2029 :class:`Option`\s or :class:`Argument`\s. Other subclasses are currently
2030 not supported by design as some of the internals for parsing are
2031 intentionally not finalized.
2033 Some settings are supported by both options and arguments.
2035 :param param_decls: the parameter declarations for this option or
2036 argument. This is a list of flags or argument
2037 names.
2038 :param type: the type that should be used. Either a :class:`ParamType`
2039 or a Python type. The latter is converted into the former
2040 automatically if supported.
2041 :param required: controls if this is optional or not.
2042 :param default: the default value if omitted. This can also be a callable,
2043 in which case it's invoked when the default is needed
2044 without any arguments.
2045 :param callback: A function to further process or validate the value
2046 after type conversion. It is called as ``f(ctx, param, value)``
2047 and must return the value. It is called for all sources,
2048 including prompts.
2049 :param nargs: the number of arguments to match. If not ``1`` the return
2050 value is a tuple instead of single value. The default for
2051 nargs is ``1`` (except if the type is a tuple, then it's
2052 the arity of the tuple). If ``nargs=-1``, all remaining
2053 parameters are collected.
2054 :param metavar: how the value is represented in the help page.
2055 :param expose_value: if this is `True` then the value is passed onwards
2056 to the command callback and stored on the context,
2057 otherwise it's skipped.
2058 :param is_eager: eager values are processed before non eager ones. This
2059 should not be set for arguments or it will inverse the
2060 order of processing.
2061 :param envvar: environment variable(s) that are used to provide a default value for
2062 this parameter. This can be a string or a sequence of strings. If a sequence is
2063 given, only the first non-empty environment variable is used for the parameter.
2064 :param shell_complete: A function that returns custom shell
2065 completions. Used instead of the param's type completion if
2066 given. Takes ``ctx, param, incomplete`` and must return a list
2067 of :class:`~click.shell_completion.CompletionItem` or a list of
2068 strings.
2069 :param deprecated: If ``True`` or non-empty string, issues a message
2070 indicating that the argument is deprecated and highlights
2071 its deprecation in --help. The message can be customized
2072 by using a string as the value. A deprecated parameter
2073 cannot be required, a ValueError will be raised otherwise.
2075 .. versionchanged:: 8.2.0
2076 Introduction of ``deprecated``.
2078 .. versionchanged:: 8.2
2079 Adding duplicate parameter names to a :class:`~click.core.Command` will
2080 result in a ``UserWarning`` being shown.
2082 .. versionchanged:: 8.2
2083 Adding duplicate parameter names to a :class:`~click.core.Command` will
2084 result in a ``UserWarning`` being shown.
2086 .. versionchanged:: 8.0
2087 ``process_value`` validates required parameters and bounded
2088 ``nargs``, and invokes the parameter callback before returning
2089 the value. This allows the callback to validate prompts.
2090 ``full_process_value`` is removed.
2092 .. versionchanged:: 8.0
2093 ``autocompletion`` is renamed to ``shell_complete`` and has new
2094 semantics described above. The old name is deprecated and will
2095 be removed in 8.1, until then it will be wrapped to match the
2096 new requirements.
2098 .. versionchanged:: 8.0
2099 For ``multiple=True, nargs>1``, the default must be a list of
2100 tuples.
2102 .. versionchanged:: 8.0
2103 Setting a default is no longer required for ``nargs>1``, it will
2104 default to ``None``. ``multiple=True`` or ``nargs=-1`` will
2105 default to ``()``.
2107 .. versionchanged:: 7.1
2108 Empty environment variables are ignored rather than taking the
2109 empty string value. This makes it possible for scripts to clear
2110 variables if they can't unset them.
2112 .. versionchanged:: 2.0
2113 Changed signature for parameter callback to also be passed the
2114 parameter. The old callback format will still work, but it will
2115 raise a warning to give you a chance to migrate the code easier.
2116 """
2118 param_type_name = "parameter"
2120 def __init__(
2121 self,
2122 param_decls: cabc.Sequence[str] | None = None,
2123 type: types.ParamType | t.Any | None = None,
2124 required: bool = False,
2125 # XXX The default historically embed two concepts:
2126 # - the declaration of a Parameter object carrying the default (handy to
2127 # arbitrage the default value of coupled Parameters sharing the same
2128 # self.name, like flag options),
2129 # - and the actual value of the default.
2130 # It is confusing and is the source of many issues discussed in:
2131 # https://github.com/pallets/click/pull/3030
2132 # In the future, we might think of splitting it in two, not unlike
2133 # Option.is_flag and Option.flag_value: we could have something like
2134 # Parameter.is_default and Parameter.default_value.
2135 default: t.Any | t.Callable[[], t.Any] | None = UNSET,
2136 callback: t.Callable[[Context, Parameter, t.Any], t.Any] | None = None,
2137 nargs: int | None = None,
2138 multiple: bool = False,
2139 metavar: str | None = None,
2140 expose_value: bool = True,
2141 is_eager: bool = False,
2142 envvar: str | cabc.Sequence[str] | None = None,
2143 shell_complete: t.Callable[
2144 [Context, Parameter, str], list[CompletionItem] | list[str]
2145 ]
2146 | None = None,
2147 deprecated: bool | str = False,
2148 ) -> None:
2149 self.name: str | None
2150 self.opts: list[str]
2151 self.secondary_opts: list[str]
2152 self.name, self.opts, self.secondary_opts = self._parse_decls(
2153 param_decls or (), expose_value
2154 )
2155 self.type: types.ParamType = types.convert_type(type, default)
2157 # Default nargs to what the type tells us if we have that
2158 # information available.
2159 if nargs is None:
2160 if self.type.is_composite:
2161 nargs = self.type.arity
2162 else:
2163 nargs = 1
2165 self.required = required
2166 self.callback = callback
2167 self.nargs = nargs
2168 self.multiple = multiple
2169 self.expose_value = expose_value
2170 self.default = default
2171 self.is_eager = is_eager
2172 self.metavar = metavar
2173 self.envvar = envvar
2174 self._custom_shell_complete = shell_complete
2175 self.deprecated = deprecated
2177 if __debug__:
2178 if self.type.is_composite and nargs != self.type.arity:
2179 raise ValueError(
2180 f"'nargs' must be {self.type.arity} (or None) for"
2181 f" type {self.type!r}, but it was {nargs}."
2182 )
2184 if required and deprecated:
2185 raise ValueError(
2186 f"The {self.param_type_name} '{self.human_readable_name}' "
2187 "is deprecated and still required. A deprecated "
2188 f"{self.param_type_name} cannot be required."
2189 )
2191 def to_info_dict(self) -> dict[str, t.Any]:
2192 """Gather information that could be useful for a tool generating
2193 user-facing documentation.
2195 Use :meth:`click.Context.to_info_dict` to traverse the entire
2196 CLI structure.
2198 .. versionchanged:: 8.3.0
2199 Returns ``None`` for the :attr:`default` if it was not set.
2201 .. versionadded:: 8.0
2202 """
2203 return {
2204 "name": self.name,
2205 "param_type_name": self.param_type_name,
2206 "opts": self.opts,
2207 "secondary_opts": self.secondary_opts,
2208 "type": self.type.to_info_dict(),
2209 "required": self.required,
2210 "nargs": self.nargs,
2211 "multiple": self.multiple,
2212 # We explicitly hide the :attr:`UNSET` value to the user, as we choose to
2213 # make it an implementation detail. And because ``to_info_dict`` has been
2214 # designed for documentation purposes, we return ``None`` instead.
2215 "default": self.default if self.default is not UNSET else None,
2216 "envvar": self.envvar,
2217 }
2219 def __repr__(self) -> str:
2220 return f"<{self.__class__.__name__} {self.name}>"
2222 def _parse_decls(
2223 self, decls: cabc.Sequence[str], expose_value: bool
2224 ) -> tuple[str | None, list[str], list[str]]:
2225 raise NotImplementedError()
2227 @property
2228 def human_readable_name(self) -> str:
2229 """Returns the human readable name of this parameter. This is the
2230 same as the name for options, but the metavar for arguments.
2231 """
2232 return self.name # type: ignore
2234 def make_metavar(self, ctx: Context) -> str:
2235 if self.metavar is not None:
2236 return self.metavar
2238 metavar = self.type.get_metavar(param=self, ctx=ctx)
2240 if metavar is None:
2241 metavar = self.type.name.upper()
2243 if self.nargs != 1:
2244 metavar += "..."
2246 return metavar
2248 @t.overload
2249 def get_default(
2250 self, ctx: Context, call: t.Literal[True] = True
2251 ) -> t.Any | None: ...
2253 @t.overload
2254 def get_default(
2255 self, ctx: Context, call: bool = ...
2256 ) -> t.Any | t.Callable[[], t.Any] | None: ...
2258 def get_default(
2259 self, ctx: Context, call: bool = True
2260 ) -> t.Any | t.Callable[[], t.Any] | None:
2261 """Get the default for the parameter. Tries
2262 :meth:`Context.lookup_default` first, then the local default.
2264 :param ctx: Current context.
2265 :param call: If the default is a callable, call it. Disable to
2266 return the callable instead.
2268 .. versionchanged:: 8.0.2
2269 Type casting is no longer performed when getting a default.
2271 .. versionchanged:: 8.0.1
2272 Type casting can fail in resilient parsing mode. Invalid
2273 defaults will not prevent showing help text.
2275 .. versionchanged:: 8.0
2276 Looks at ``ctx.default_map`` first.
2278 .. versionchanged:: 8.0
2279 Added the ``call`` parameter.
2280 """
2281 value = ctx.lookup_default(self.name, call=False) # type: ignore
2283 if value is UNSET:
2284 value = self.default
2286 if call and callable(value):
2287 value = value()
2289 return value
2291 def add_to_parser(self, parser: _OptionParser, ctx: Context) -> None:
2292 raise NotImplementedError()
2294 def consume_value(
2295 self, ctx: Context, opts: cabc.Mapping[str, t.Any]
2296 ) -> tuple[t.Any, ParameterSource]:
2297 """Returns the parameter value produced by the parser.
2299 If the parser did not produce a value from user input, the value is either
2300 sourced from the environment variable, the default map, or the parameter's
2301 default value. In that order of precedence.
2303 If no value is found, an internal sentinel value is returned.
2305 :meta private:
2306 """
2307 # Collect from the parse the value passed by the user to the CLI.
2308 value = opts.get(self.name, UNSET) # type: ignore
2309 # If the value is set, it means it was sourced from the command line by the
2310 # parser, otherwise it left unset by default.
2311 source = (
2312 ParameterSource.COMMANDLINE
2313 if value is not UNSET
2314 else ParameterSource.DEFAULT
2315 )
2317 if value is UNSET:
2318 envvar_value = self.value_from_envvar(ctx)
2319 if envvar_value is not None:
2320 value = envvar_value
2321 source = ParameterSource.ENVIRONMENT
2323 if value is UNSET:
2324 default_map_value = ctx.lookup_default(self.name) # type: ignore
2325 if default_map_value is not UNSET:
2326 value = default_map_value
2327 source = ParameterSource.DEFAULT_MAP
2329 if value is UNSET:
2330 default_value = self.get_default(ctx)
2331 if default_value is not UNSET:
2332 value = default_value
2333 source = ParameterSource.DEFAULT
2335 return value, source
2337 def type_cast_value(self, ctx: Context, value: t.Any) -> t.Any:
2338 """Convert and validate a value against the parameter's
2339 :attr:`type`, :attr:`multiple`, and :attr:`nargs`.
2340 """
2341 if value is None:
2342 if self.multiple or self.nargs == -1:
2343 return ()
2344 else:
2345 return value
2347 def check_iter(value: t.Any) -> cabc.Iterator[t.Any]:
2348 try:
2349 return _check_iter(value)
2350 except TypeError:
2351 # This should only happen when passing in args manually,
2352 # the parser should construct an iterable when parsing
2353 # the command line.
2354 raise BadParameter(
2355 _("Value must be an iterable."), ctx=ctx, param=self
2356 ) from None
2358 # Define the conversion function based on nargs and type.
2360 if self.nargs == 1 or self.type.is_composite:
2362 def convert(value: t.Any) -> t.Any:
2363 return self.type(value, param=self, ctx=ctx)
2365 elif self.nargs == -1:
2367 def convert(value: t.Any) -> t.Any: # tuple[t.Any, ...]
2368 return tuple(self.type(x, self, ctx) for x in check_iter(value))
2370 else: # nargs > 1
2372 def convert(value: t.Any) -> t.Any: # tuple[t.Any, ...]
2373 value = tuple(check_iter(value))
2375 if len(value) != self.nargs:
2376 raise BadParameter(
2377 ngettext(
2378 "Takes {nargs} values but 1 was given.",
2379 "Takes {nargs} values but {len} were given.",
2380 len(value),
2381 ).format(nargs=self.nargs, len=len(value)),
2382 ctx=ctx,
2383 param=self,
2384 )
2386 return tuple(self.type(x, self, ctx) for x in value)
2388 if self.multiple:
2389 return tuple(convert(x) for x in check_iter(value))
2391 return convert(value)
2393 def value_is_missing(self, value: t.Any) -> bool:
2394 """A value is considered missing if:
2396 - it is :attr:`UNSET`,
2397 - or if it is an empty sequence while the parameter is suppose to have
2398 non-single value (i.e. :attr:`nargs` is not ``1`` or :attr:`multiple` is
2399 set).
2401 :meta private:
2402 """
2403 if value is UNSET:
2404 return True
2406 if (self.nargs != 1 or self.multiple) and value == ():
2407 return True
2409 return False
2411 def process_value(self, ctx: Context, value: t.Any) -> t.Any:
2412 """Process the value of this parameter:
2414 1. Type cast the value using :meth:`type_cast_value`.
2415 2. Check if the value is missing (see: :meth:`value_is_missing`), and raise
2416 :exc:`MissingParameter` if it is required.
2417 3. If a :attr:`callback` is set, call it to have the value replaced by the
2418 result of the callback. If the value was not set, the callback receive
2419 ``None``. This keep the legacy behavior as it was before the introduction of
2420 the :attr:`UNSET` sentinel.
2422 :meta private:
2423 """
2424 # shelter `type_cast_value` from ever seeing an `UNSET` value by handling the
2425 # cases in which `UNSET` gets special treatment explicitly at this layer
2426 #
2427 # Refs:
2428 # https://github.com/pallets/click/issues/3069
2429 if value is UNSET:
2430 if self.multiple or self.nargs == -1:
2431 value = ()
2432 else:
2433 value = self.type_cast_value(ctx, value)
2435 if self.required and self.value_is_missing(value):
2436 raise MissingParameter(ctx=ctx, param=self)
2438 if self.callback is not None:
2439 # Legacy case: UNSET is not exposed directly to the callback, but converted
2440 # to None.
2441 if value is UNSET:
2442 value = None
2443 value = self.callback(ctx, self, value)
2445 return value
2447 def resolve_envvar_value(self, ctx: Context) -> str | None:
2448 """Returns the value found in the environment variable(s) attached to this
2449 parameter.
2451 Environment variables values are `always returned as strings
2452 <https://docs.python.org/3/library/os.html#os.environ>`_.
2454 This method returns ``None`` if:
2456 - the :attr:`envvar` property is not set on the :class:`Parameter`,
2457 - the environment variable is not found in the environment,
2458 - the variable is found in the environment but its value is empty (i.e. the
2459 environment variable is present but has an empty string).
2461 If :attr:`envvar` is setup with multiple environment variables,
2462 then only the first non-empty value is returned.
2464 .. caution::
2466 The raw value extracted from the environment is not normalized and is
2467 returned as-is. Any normalization or reconciliation is performed later by
2468 the :class:`Parameter`'s :attr:`type`.
2470 :meta private:
2471 """
2472 if not self.envvar:
2473 return None
2475 if isinstance(self.envvar, str):
2476 rv = os.environ.get(self.envvar)
2478 if rv:
2479 return rv
2480 else:
2481 for envvar in self.envvar:
2482 rv = os.environ.get(envvar)
2484 # Return the first non-empty value of the list of environment variables.
2485 if rv:
2486 return rv
2487 # Else, absence of value is interpreted as an environment variable that
2488 # is not set, so proceed to the next one.
2490 return None
2492 def value_from_envvar(self, ctx: Context) -> str | cabc.Sequence[str] | None:
2493 """Process the raw environment variable string for this parameter.
2495 Returns the string as-is or splits it into a sequence of strings if the
2496 parameter is expecting multiple values (i.e. its :attr:`nargs` property is set
2497 to a value other than ``1``).
2499 :meta private:
2500 """
2501 rv = self.resolve_envvar_value(ctx)
2503 if rv is not None and self.nargs != 1:
2504 return self.type.split_envvar_value(rv)
2506 return rv
2508 def handle_parse_result(
2509 self, ctx: Context, opts: cabc.Mapping[str, t.Any], args: list[str]
2510 ) -> tuple[t.Any, list[str]]:
2511 """Process the value produced by the parser from user input.
2513 Always process the value through the Parameter's :attr:`type`, wherever it
2514 comes from.
2516 If the parameter is deprecated, this method warn the user about it. But only if
2517 the value has been explicitly set by the user (and as such, is not coming from
2518 a default).
2520 :meta private:
2521 """
2522 with augment_usage_errors(ctx, param=self):
2523 value, source = self.consume_value(ctx, opts)
2525 ctx.set_parameter_source(self.name, source) # type: ignore
2527 # Display a deprecation warning if necessary.
2528 if (
2529 self.deprecated
2530 and value is not UNSET
2531 and source not in (ParameterSource.DEFAULT, ParameterSource.DEFAULT_MAP)
2532 ):
2533 extra_message = (
2534 f" {self.deprecated}" if isinstance(self.deprecated, str) else ""
2535 )
2536 message = _(
2537 "DeprecationWarning: The {param_type} {name!r} is deprecated."
2538 "{extra_message}"
2539 ).format(
2540 param_type=self.param_type_name,
2541 name=self.human_readable_name,
2542 extra_message=extra_message,
2543 )
2544 echo(style(message, fg="red"), err=True)
2546 # Process the value through the parameter's type.
2547 try:
2548 value = self.process_value(ctx, value)
2549 except Exception:
2550 if not ctx.resilient_parsing:
2551 raise
2552 # In resilient parsing mode, we do not want to fail the command if the
2553 # value is incompatible with the parameter type, so we reset the value
2554 # to UNSET, which will be interpreted as a missing value.
2555 value = UNSET
2557 # Add parameter's value to the context.
2558 if (
2559 self.expose_value
2560 # We skip adding the value if it was previously set by another parameter
2561 # targeting the same variable name. This prevents parameters competing for
2562 # the same name to override each other.
2563 and (self.name not in ctx.params or ctx.params[self.name] is UNSET)
2564 ):
2565 # Click is logically enforcing that the name is None if the parameter is
2566 # not to be exposed. We still assert it here to please the type checker.
2567 assert self.name is not None, (
2568 f"{self!r} parameter's name should not be None when exposing value."
2569 )
2570 ctx.params[self.name] = value
2572 return value, args
2574 def get_help_record(self, ctx: Context) -> tuple[str, str] | None:
2575 pass
2577 def get_usage_pieces(self, ctx: Context) -> list[str]:
2578 return []
2580 def get_error_hint(self, ctx: Context) -> str:
2581 """Get a stringified version of the param for use in error messages to
2582 indicate which param caused the error.
2583 """
2584 hint_list = self.opts or [self.human_readable_name]
2585 return " / ".join(f"'{x}'" for x in hint_list)
2587 def shell_complete(self, ctx: Context, incomplete: str) -> list[CompletionItem]:
2588 """Return a list of completions for the incomplete value. If a
2589 ``shell_complete`` function was given during init, it is used.
2590 Otherwise, the :attr:`type`
2591 :meth:`~click.types.ParamType.shell_complete` function is used.
2593 :param ctx: Invocation context for this command.
2594 :param incomplete: Value being completed. May be empty.
2596 .. versionadded:: 8.0
2597 """
2598 if self._custom_shell_complete is not None:
2599 results = self._custom_shell_complete(ctx, self, incomplete)
2601 if results and isinstance(results[0], str):
2602 from click.shell_completion import CompletionItem
2604 results = [CompletionItem(c) for c in results]
2606 return t.cast("list[CompletionItem]", results)
2608 return self.type.shell_complete(ctx, self, incomplete)
2611class Option(Parameter):
2612 """Options are usually optional values on the command line and
2613 have some extra features that arguments don't have.
2615 All other parameters are passed onwards to the parameter constructor.
2617 :param show_default: Show the default value for this option in its
2618 help text. Values are not shown by default, unless
2619 :attr:`Context.show_default` is ``True``. If this value is a
2620 string, it shows that string in parentheses instead of the
2621 actual value. This is particularly useful for dynamic options.
2622 For single option boolean flags, the default remains hidden if
2623 its value is ``False``.
2624 :param show_envvar: Controls if an environment variable should be
2625 shown on the help page and error messages.
2626 Normally, environment variables are not shown.
2627 :param prompt: If set to ``True`` or a non empty string then the
2628 user will be prompted for input. If set to ``True`` the prompt
2629 will be the option name capitalized. A deprecated option cannot be
2630 prompted.
2631 :param confirmation_prompt: Prompt a second time to confirm the
2632 value if it was prompted for. Can be set to a string instead of
2633 ``True`` to customize the message.
2634 :param prompt_required: If set to ``False``, the user will be
2635 prompted for input only when the option was specified as a flag
2636 without a value.
2637 :param hide_input: If this is ``True`` then the input on the prompt
2638 will be hidden from the user. This is useful for password input.
2639 :param is_flag: forces this option to act as a flag. The default is
2640 auto detection.
2641 :param flag_value: which value should be used for this flag if it's
2642 enabled. This is set to a boolean automatically if
2643 the option string contains a slash to mark two options.
2644 :param multiple: if this is set to `True` then the argument is accepted
2645 multiple times and recorded. This is similar to ``nargs``
2646 in how it works but supports arbitrary number of
2647 arguments.
2648 :param count: this flag makes an option increment an integer.
2649 :param allow_from_autoenv: if this is enabled then the value of this
2650 parameter will be pulled from an environment
2651 variable in case a prefix is defined on the
2652 context.
2653 :param help: the help string.
2654 :param hidden: hide this option from help outputs.
2655 :param attrs: Other command arguments described in :class:`Parameter`.
2657 .. versionchanged:: 8.2
2658 ``envvar`` used with ``flag_value`` will always use the ``flag_value``,
2659 previously it would use the value of the environment variable.
2661 .. versionchanged:: 8.1
2662 Help text indentation is cleaned here instead of only in the
2663 ``@option`` decorator.
2665 .. versionchanged:: 8.1
2666 The ``show_default`` parameter overrides
2667 ``Context.show_default``.
2669 .. versionchanged:: 8.1
2670 The default of a single option boolean flag is not shown if the
2671 default value is ``False``.
2673 .. versionchanged:: 8.0.1
2674 ``type`` is detected from ``flag_value`` if given.
2675 """
2677 param_type_name = "option"
2679 def __init__(
2680 self,
2681 param_decls: cabc.Sequence[str] | None = None,
2682 show_default: bool | str | None = None,
2683 prompt: bool | str = False,
2684 confirmation_prompt: bool | str = False,
2685 prompt_required: bool = True,
2686 hide_input: bool = False,
2687 is_flag: bool | None = None,
2688 flag_value: t.Any = UNSET,
2689 multiple: bool = False,
2690 count: bool = False,
2691 allow_from_autoenv: bool = True,
2692 type: types.ParamType | t.Any | None = None,
2693 help: str | None = None,
2694 hidden: bool = False,
2695 show_choices: bool = True,
2696 show_envvar: bool = False,
2697 deprecated: bool | str = False,
2698 **attrs: t.Any,
2699 ) -> None:
2700 if help:
2701 help = inspect.cleandoc(help)
2703 super().__init__(
2704 param_decls, type=type, multiple=multiple, deprecated=deprecated, **attrs
2705 )
2707 if prompt is True:
2708 if self.name is None:
2709 raise TypeError("'name' is required with 'prompt=True'.")
2711 prompt_text: str | None = self.name.replace("_", " ").capitalize()
2712 elif prompt is False:
2713 prompt_text = None
2714 else:
2715 prompt_text = prompt
2717 if deprecated:
2718 deprecated_message = (
2719 f"(DEPRECATED: {deprecated})"
2720 if isinstance(deprecated, str)
2721 else "(DEPRECATED)"
2722 )
2723 help = help + deprecated_message if help is not None else deprecated_message
2725 self.prompt = prompt_text
2726 self.confirmation_prompt = confirmation_prompt
2727 self.prompt_required = prompt_required
2728 self.hide_input = hide_input
2729 self.hidden = hidden
2731 # The _flag_needs_value property tells the parser that this option is a flag
2732 # that cannot be used standalone and needs a value. With this information, the
2733 # parser can determine whether to consider the next user-provided argument in
2734 # the CLI as a value for this flag or as a new option.
2735 # If prompt is enabled but not required, then it opens the possibility for the
2736 # option to gets its value from the user.
2737 self._flag_needs_value = self.prompt is not None and not self.prompt_required
2739 # Auto-detect if this is a flag or not.
2740 if is_flag is None:
2741 # Implicitly a flag because flag_value was set.
2742 if flag_value is not UNSET:
2743 is_flag = True
2744 # Not a flag, but when used as a flag it shows a prompt.
2745 elif self._flag_needs_value:
2746 is_flag = False
2747 # Implicitly a flag because secondary options names were given.
2748 elif self.secondary_opts:
2749 is_flag = True
2750 # The option is explicitly not a flag. But we do not know yet if it needs a
2751 # value or not. So we look at the default value to determine it.
2752 elif is_flag is False and not self._flag_needs_value:
2753 self._flag_needs_value = self.default is UNSET
2755 if is_flag:
2756 # Set missing default for flags if not explicitly required or prompted.
2757 if self.default is UNSET and not self.required and not self.prompt:
2758 if multiple:
2759 self.default = ()
2761 # Auto-detect the type of the flag based on the flag_value.
2762 if type is None:
2763 # A flag without a flag_value is a boolean flag.
2764 if flag_value is UNSET:
2765 self.type = types.BoolParamType()
2766 # If the flag value is a boolean, use BoolParamType.
2767 elif isinstance(flag_value, bool):
2768 self.type = types.BoolParamType()
2769 # Otherwise, guess the type from the flag value.
2770 else:
2771 self.type = types.convert_type(None, flag_value)
2773 self.is_flag: bool = bool(is_flag)
2774 self.is_bool_flag: bool = bool(
2775 is_flag and isinstance(self.type, types.BoolParamType)
2776 )
2777 self.flag_value: t.Any = flag_value
2779 # Set boolean flag default to False if unset and not required.
2780 if self.is_bool_flag:
2781 if self.default is UNSET and not self.required:
2782 self.default = False
2784 # Support the special case of aligning the default value with the flag_value
2785 # for flags whose default is explicitly set to True. Note that as long as we
2786 # have this condition, there is no way a flag can have a default set to True,
2787 # and a flag_value set to something else. Refs:
2788 # https://github.com/pallets/click/issues/3024#issuecomment-3146199461
2789 # https://github.com/pallets/click/pull/3030/commits/06847da
2790 if self.default is True and self.flag_value is not UNSET:
2791 self.default = self.flag_value
2793 # Set the default flag_value if it is not set.
2794 if self.flag_value is UNSET:
2795 if self.is_flag:
2796 self.flag_value = True
2797 else:
2798 self.flag_value = None
2800 # Counting.
2801 self.count = count
2802 if count:
2803 if type is None:
2804 self.type = types.IntRange(min=0)
2805 if self.default is UNSET:
2806 self.default = 0
2808 self.allow_from_autoenv = allow_from_autoenv
2809 self.help = help
2810 self.show_default = show_default
2811 self.show_choices = show_choices
2812 self.show_envvar = show_envvar
2814 if __debug__:
2815 if deprecated and prompt:
2816 raise ValueError("`deprecated` options cannot use `prompt`.")
2818 if self.nargs == -1:
2819 raise TypeError("nargs=-1 is not supported for options.")
2821 if not self.is_bool_flag and self.secondary_opts:
2822 raise TypeError("Secondary flag is not valid for non-boolean flag.")
2824 if self.is_bool_flag and self.hide_input and self.prompt is not None:
2825 raise TypeError(
2826 "'prompt' with 'hide_input' is not valid for boolean flag."
2827 )
2829 if self.count:
2830 if self.multiple:
2831 raise TypeError("'count' is not valid with 'multiple'.")
2833 if self.is_flag:
2834 raise TypeError("'count' is not valid with 'is_flag'.")
2836 def to_info_dict(self) -> dict[str, t.Any]:
2837 """
2838 .. versionchanged:: 8.3.0
2839 Returns ``None`` for the :attr:`flag_value` if it was not set.
2840 """
2841 info_dict = super().to_info_dict()
2842 info_dict.update(
2843 help=self.help,
2844 prompt=self.prompt,
2845 is_flag=self.is_flag,
2846 # We explicitly hide the :attr:`UNSET` value to the user, as we choose to
2847 # make it an implementation detail. And because ``to_info_dict`` has been
2848 # designed for documentation purposes, we return ``None`` instead.
2849 flag_value=self.flag_value if self.flag_value is not UNSET else None,
2850 count=self.count,
2851 hidden=self.hidden,
2852 )
2853 return info_dict
2855 def get_error_hint(self, ctx: Context) -> str:
2856 result = super().get_error_hint(ctx)
2857 if self.show_envvar and self.envvar is not None:
2858 result += f" (env var: '{self.envvar}')"
2859 return result
2861 def _parse_decls(
2862 self, decls: cabc.Sequence[str], expose_value: bool
2863 ) -> tuple[str | None, list[str], list[str]]:
2864 opts = []
2865 secondary_opts = []
2866 name = None
2867 possible_names = []
2869 for decl in decls:
2870 if decl.isidentifier():
2871 if name is not None:
2872 raise TypeError(f"Name '{name}' defined twice")
2873 name = decl
2874 else:
2875 split_char = ";" if decl[:1] == "/" else "/"
2876 if split_char in decl:
2877 first, second = decl.split(split_char, 1)
2878 first = first.rstrip()
2879 if first:
2880 possible_names.append(_split_opt(first))
2881 opts.append(first)
2882 second = second.lstrip()
2883 if second:
2884 secondary_opts.append(second.lstrip())
2885 if first == second:
2886 raise ValueError(
2887 f"Boolean option {decl!r} cannot use the"
2888 " same flag for true/false."
2889 )
2890 else:
2891 possible_names.append(_split_opt(decl))
2892 opts.append(decl)
2894 if name is None and possible_names:
2895 possible_names.sort(key=lambda x: -len(x[0])) # group long options first
2896 name = possible_names[0][1].replace("-", "_").lower()
2897 if not name.isidentifier():
2898 name = None
2900 if name is None:
2901 if not expose_value:
2902 return None, opts, secondary_opts
2903 raise TypeError(
2904 f"Could not determine name for option with declarations {decls!r}"
2905 )
2907 if not opts and not secondary_opts:
2908 raise TypeError(
2909 f"No options defined but a name was passed ({name})."
2910 " Did you mean to declare an argument instead? Did"
2911 f" you mean to pass '--{name}'?"
2912 )
2914 return name, opts, secondary_opts
2916 def add_to_parser(self, parser: _OptionParser, ctx: Context) -> None:
2917 if self.multiple:
2918 action = "append"
2919 elif self.count:
2920 action = "count"
2921 else:
2922 action = "store"
2924 if self.is_flag:
2925 action = f"{action}_const"
2927 if self.is_bool_flag and self.secondary_opts:
2928 parser.add_option(
2929 obj=self, opts=self.opts, dest=self.name, action=action, const=True
2930 )
2931 parser.add_option(
2932 obj=self,
2933 opts=self.secondary_opts,
2934 dest=self.name,
2935 action=action,
2936 const=False,
2937 )
2938 else:
2939 parser.add_option(
2940 obj=self,
2941 opts=self.opts,
2942 dest=self.name,
2943 action=action,
2944 const=self.flag_value,
2945 )
2946 else:
2947 parser.add_option(
2948 obj=self,
2949 opts=self.opts,
2950 dest=self.name,
2951 action=action,
2952 nargs=self.nargs,
2953 )
2955 def get_help_record(self, ctx: Context) -> tuple[str, str] | None:
2956 if self.hidden:
2957 return None
2959 any_prefix_is_slash = False
2961 def _write_opts(opts: cabc.Sequence[str]) -> str:
2962 nonlocal any_prefix_is_slash
2964 rv, any_slashes = join_options(opts)
2966 if any_slashes:
2967 any_prefix_is_slash = True
2969 if not self.is_flag and not self.count:
2970 rv += f" {self.make_metavar(ctx=ctx)}"
2972 return rv
2974 rv = [_write_opts(self.opts)]
2976 if self.secondary_opts:
2977 rv.append(_write_opts(self.secondary_opts))
2979 help = self.help or ""
2981 extra = self.get_help_extra(ctx)
2982 extra_items = []
2983 if "envvars" in extra:
2984 extra_items.append(
2985 _("env var: {var}").format(var=", ".join(extra["envvars"]))
2986 )
2987 if "default" in extra:
2988 extra_items.append(_("default: {default}").format(default=extra["default"]))
2989 if "range" in extra:
2990 extra_items.append(extra["range"])
2991 if "required" in extra:
2992 extra_items.append(_(extra["required"]))
2994 if extra_items:
2995 extra_str = "; ".join(extra_items)
2996 help = f"{help} [{extra_str}]" if help else f"[{extra_str}]"
2998 return ("; " if any_prefix_is_slash else " / ").join(rv), help
3000 def get_help_extra(self, ctx: Context) -> types.OptionHelpExtra:
3001 extra: types.OptionHelpExtra = {}
3003 if self.show_envvar:
3004 envvar = self.envvar
3006 if envvar is None:
3007 if (
3008 self.allow_from_autoenv
3009 and ctx.auto_envvar_prefix is not None
3010 and self.name is not None
3011 ):
3012 envvar = f"{ctx.auto_envvar_prefix}_{self.name.upper()}"
3014 if envvar is not None:
3015 if isinstance(envvar, str):
3016 extra["envvars"] = (envvar,)
3017 else:
3018 extra["envvars"] = tuple(str(d) for d in envvar)
3020 # Temporarily enable resilient parsing to avoid type casting
3021 # failing for the default. Might be possible to extend this to
3022 # help formatting in general.
3023 resilient = ctx.resilient_parsing
3024 ctx.resilient_parsing = True
3026 try:
3027 default_value = self.get_default(ctx, call=False)
3028 finally:
3029 ctx.resilient_parsing = resilient
3031 show_default = False
3032 show_default_is_str = False
3034 if self.show_default is not None:
3035 if isinstance(self.show_default, str):
3036 show_default_is_str = show_default = True
3037 else:
3038 show_default = self.show_default
3039 elif ctx.show_default is not None:
3040 show_default = ctx.show_default
3042 if show_default_is_str or (
3043 show_default and (default_value not in (None, UNSET))
3044 ):
3045 if show_default_is_str:
3046 default_string = f"({self.show_default})"
3047 elif isinstance(default_value, (list, tuple)):
3048 default_string = ", ".join(str(d) for d in default_value)
3049 elif isinstance(default_value, enum.Enum):
3050 default_string = default_value.name
3051 elif inspect.isfunction(default_value):
3052 default_string = _("(dynamic)")
3053 elif self.is_bool_flag and self.secondary_opts:
3054 # For boolean flags that have distinct True/False opts,
3055 # use the opt without prefix instead of the value.
3056 default_string = _split_opt(
3057 (self.opts if default_value else self.secondary_opts)[0]
3058 )[1]
3059 elif self.is_bool_flag and not self.secondary_opts and not default_value:
3060 default_string = ""
3061 elif default_value == "":
3062 default_string = '""'
3063 else:
3064 default_string = str(default_value)
3066 if default_string:
3067 extra["default"] = default_string
3069 if (
3070 isinstance(self.type, types._NumberRangeBase)
3071 # skip count with default range type
3072 and not (self.count and self.type.min == 0 and self.type.max is None)
3073 ):
3074 range_str = self.type._describe_range()
3076 if range_str:
3077 extra["range"] = range_str
3079 if self.required:
3080 extra["required"] = "required"
3082 return extra
3084 def prompt_for_value(self, ctx: Context) -> t.Any:
3085 """This is an alternative flow that can be activated in the full
3086 value processing if a value does not exist. It will prompt the
3087 user until a valid value exists and then returns the processed
3088 value as result.
3089 """
3090 assert self.prompt is not None
3092 # Calculate the default before prompting anything to lock in the value before
3093 # attempting any user interaction.
3094 default = self.get_default(ctx)
3096 # A boolean flag can use a simplified [y/n] confirmation prompt.
3097 if self.is_bool_flag:
3098 # If we have no boolean default, we force the user to explicitly provide
3099 # one.
3100 if default in (UNSET, None):
3101 default = None
3102 # Nothing prevent you to declare an option that is simultaneously:
3103 # 1) auto-detected as a boolean flag,
3104 # 2) allowed to prompt, and
3105 # 3) still declare a non-boolean default.
3106 # This forced casting into a boolean is necessary to align any non-boolean
3107 # default to the prompt, which is going to be a [y/n]-style confirmation
3108 # because the option is still a boolean flag. That way, instead of [y/n],
3109 # we get [Y/n] or [y/N] depending on the truthy value of the default.
3110 # Refs: https://github.com/pallets/click/pull/3030#discussion_r2289180249
3111 else:
3112 default = bool(default)
3113 return confirm(self.prompt, default)
3115 # If show_default is set to True/False, provide this to `prompt` as well. For
3116 # non-bool values of `show_default`, we use `prompt`'s default behavior
3117 prompt_kwargs: t.Any = {}
3118 if isinstance(self.show_default, bool):
3119 prompt_kwargs["show_default"] = self.show_default
3121 return prompt(
3122 self.prompt,
3123 # Use ``None`` to inform the prompt() function to reiterate until a valid
3124 # value is provided by the user if we have no default.
3125 default=None if default is UNSET else default,
3126 type=self.type,
3127 hide_input=self.hide_input,
3128 show_choices=self.show_choices,
3129 confirmation_prompt=self.confirmation_prompt,
3130 value_proc=lambda x: self.process_value(ctx, x),
3131 **prompt_kwargs,
3132 )
3134 def resolve_envvar_value(self, ctx: Context) -> str | None:
3135 """:class:`Option` resolves its environment variable the same way as
3136 :func:`Parameter.resolve_envvar_value`, but it also supports
3137 :attr:`Context.auto_envvar_prefix`. If we could not find an environment from
3138 the :attr:`envvar` property, we fallback on :attr:`Context.auto_envvar_prefix`
3139 to build dynamiccaly the environment variable name using the
3140 :python:`{ctx.auto_envvar_prefix}_{self.name.upper()}` template.
3142 :meta private:
3143 """
3144 rv = super().resolve_envvar_value(ctx)
3146 if rv is not None:
3147 return rv
3149 if (
3150 self.allow_from_autoenv
3151 and ctx.auto_envvar_prefix is not None
3152 and self.name is not None
3153 ):
3154 envvar = f"{ctx.auto_envvar_prefix}_{self.name.upper()}"
3155 rv = os.environ.get(envvar)
3157 if rv:
3158 return rv
3160 return None
3162 def value_from_envvar(self, ctx: Context) -> t.Any:
3163 """For :class:`Option`, this method processes the raw environment variable
3164 string the same way as :func:`Parameter.value_from_envvar` does.
3166 But in the case of non-boolean flags, the value is analyzed to determine if the
3167 flag is activated or not, and returns a boolean of its activation, or the
3168 :attr:`flag_value` if the latter is set.
3170 This method also takes care of repeated options (i.e. options with
3171 :attr:`multiple` set to ``True``).
3173 :meta private:
3174 """
3175 rv = self.resolve_envvar_value(ctx)
3177 # Absent environment variable or an empty string is interpreted as unset.
3178 if rv is None:
3179 return None
3181 # Non-boolean flags are more liberal in what they accept. But a flag being a
3182 # flag, its envvar value still needs to be analyzed to determine if the flag is
3183 # activated or not.
3184 if self.is_flag and not self.is_bool_flag:
3185 # If the flag_value is set and match the envvar value, return it
3186 # directly.
3187 if self.flag_value is not UNSET and rv == self.flag_value:
3188 return self.flag_value
3189 # Analyze the envvar value as a boolean to know if the flag is
3190 # activated or not.
3191 return types.BoolParamType.str_to_bool(rv)
3193 # Split the envvar value if it is allowed to be repeated.
3194 value_depth = (self.nargs != 1) + bool(self.multiple)
3195 if value_depth > 0:
3196 multi_rv = self.type.split_envvar_value(rv)
3197 if self.multiple and self.nargs != 1:
3198 multi_rv = batch(multi_rv, self.nargs) # type: ignore[assignment]
3200 return multi_rv
3202 return rv
3204 def consume_value(
3205 self, ctx: Context, opts: cabc.Mapping[str, Parameter]
3206 ) -> tuple[t.Any, ParameterSource]:
3207 """For :class:`Option`, the value can be collected from an interactive prompt
3208 if the option is a flag that needs a value (and the :attr:`prompt` property is
3209 set).
3211 Additionally, this method handles flag option that are activated without a
3212 value, in which case the :attr:`flag_value` is returned.
3214 :meta private:
3215 """
3216 value, source = super().consume_value(ctx, opts)
3218 # The parser will emit a sentinel value if the option is allowed to as a flag
3219 # without a value.
3220 if value is FLAG_NEEDS_VALUE:
3221 # If the option allows for a prompt, we start an interaction with the user.
3222 if self.prompt is not None and not ctx.resilient_parsing:
3223 value = self.prompt_for_value(ctx)
3224 source = ParameterSource.PROMPT
3225 # Else the flag takes its flag_value as value.
3226 else:
3227 value = self.flag_value
3228 source = ParameterSource.COMMANDLINE
3230 # A flag which is activated always returns the flag value, unless the value
3231 # comes from the explicitly sets default.
3232 elif (
3233 self.is_flag
3234 and value is True
3235 and not self.is_bool_flag
3236 and source not in (ParameterSource.DEFAULT, ParameterSource.DEFAULT_MAP)
3237 ):
3238 value = self.flag_value
3240 # Re-interpret a multiple option which has been sent as-is by the parser.
3241 # Here we replace each occurrence of value-less flags (marked by the
3242 # FLAG_NEEDS_VALUE sentinel) with the flag_value.
3243 elif (
3244 self.multiple
3245 and value is not UNSET
3246 and source not in (ParameterSource.DEFAULT, ParameterSource.DEFAULT_MAP)
3247 and any(v is FLAG_NEEDS_VALUE for v in value)
3248 ):
3249 value = [self.flag_value if v is FLAG_NEEDS_VALUE else v for v in value]
3250 source = ParameterSource.COMMANDLINE
3252 # The value wasn't set, or used the param's default, prompt for one to the user
3253 # if prompting is enabled.
3254 elif (
3255 (
3256 value is UNSET
3257 or source in (ParameterSource.DEFAULT, ParameterSource.DEFAULT_MAP)
3258 )
3259 and self.prompt is not None
3260 and (self.required or self.prompt_required)
3261 and not ctx.resilient_parsing
3262 ):
3263 value = self.prompt_for_value(ctx)
3264 source = ParameterSource.PROMPT
3266 return value, source
3268 def process_value(self, ctx: Context, value: t.Any) -> t.Any:
3269 # process_value has to be overridden on Options in order to capture
3270 # `value == UNSET` cases before `type_cast_value()` gets called.
3271 #
3272 # Refs:
3273 # https://github.com/pallets/click/issues/3069
3274 if self.is_flag and not self.required and self.is_bool_flag and value is UNSET:
3275 value = False
3277 if self.callback is not None:
3278 value = self.callback(ctx, self, value)
3280 return value
3282 # in the normal case, rely on Parameter.process_value
3283 return super().process_value(ctx, value)
3286class Argument(Parameter):
3287 """Arguments are positional parameters to a command. They generally
3288 provide fewer features than options but can have infinite ``nargs``
3289 and are required by default.
3291 All parameters are passed onwards to the constructor of :class:`Parameter`.
3292 """
3294 param_type_name = "argument"
3296 def __init__(
3297 self,
3298 param_decls: cabc.Sequence[str],
3299 required: bool | None = None,
3300 **attrs: t.Any,
3301 ) -> None:
3302 # Auto-detect the requirement status of the argument if not explicitly set.
3303 if required is None:
3304 # The argument gets automatically required if it has no explicit default
3305 # value set and is setup to match at least one value.
3306 if attrs.get("default", UNSET) is UNSET:
3307 required = attrs.get("nargs", 1) > 0
3308 # If the argument has a default value, it is not required.
3309 else:
3310 required = False
3312 if "multiple" in attrs:
3313 raise TypeError("__init__() got an unexpected keyword argument 'multiple'.")
3315 super().__init__(param_decls, required=required, **attrs)
3317 @property
3318 def human_readable_name(self) -> str:
3319 if self.metavar is not None:
3320 return self.metavar
3321 return self.name.upper() # type: ignore
3323 def make_metavar(self, ctx: Context) -> str:
3324 if self.metavar is not None:
3325 return self.metavar
3326 var = self.type.get_metavar(param=self, ctx=ctx)
3327 if not var:
3328 var = self.name.upper() # type: ignore
3329 if self.deprecated:
3330 var += "!"
3331 if not self.required:
3332 var = f"[{var}]"
3333 if self.nargs != 1:
3334 var += "..."
3335 return var
3337 def _parse_decls(
3338 self, decls: cabc.Sequence[str], expose_value: bool
3339 ) -> tuple[str | None, list[str], list[str]]:
3340 if not decls:
3341 if not expose_value:
3342 return None, [], []
3343 raise TypeError("Argument is marked as exposed, but does not have a name.")
3344 if len(decls) == 1:
3345 name = arg = decls[0]
3346 name = name.replace("-", "_").lower()
3347 else:
3348 raise TypeError(
3349 "Arguments take exactly one parameter declaration, got"
3350 f" {len(decls)}: {decls}."
3351 )
3352 return name, [arg], []
3354 def get_usage_pieces(self, ctx: Context) -> list[str]:
3355 return [self.make_metavar(ctx)]
3357 def get_error_hint(self, ctx: Context) -> str:
3358 return f"'{self.make_metavar(ctx)}'"
3360 def add_to_parser(self, parser: _OptionParser, ctx: Context) -> None:
3361 parser.add_argument(dest=self.name, nargs=self.nargs, obj=self)
3364def __getattr__(name: str) -> object:
3365 import warnings
3367 if name == "BaseCommand":
3368 warnings.warn(
3369 "'BaseCommand' is deprecated and will be removed in Click 9.0. Use"
3370 " 'Command' instead.",
3371 DeprecationWarning,
3372 stacklevel=2,
3373 )
3374 return _BaseCommand
3376 if name == "MultiCommand":
3377 warnings.warn(
3378 "'MultiCommand' is deprecated and will be removed in Click 9.0. Use"
3379 " 'Group' instead.",
3380 DeprecationWarning,
3381 stacklevel=2,
3382 )
3383 return _MultiCommand
3385 raise AttributeError(name)