Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/click/core.py: 29%
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.IntEnum):
144 """This is an :class:`~enum.IntEnum` 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 Members are ordered from most explicit to least explicit source.
151 This allows comparison to check if a value was explicitly provided:
153 .. code-block:: python
155 source = ctx.get_parameter_source("port")
156 if source < click.ParameterSource.DEFAULT_MAP:
157 ... # value was explicitly set
159 .. versionchanged:: 8.3.3
160 Use :class:`~enum.IntEnum` and reorder members from most to
161 least explicit. Supports comparison operators.
163 .. versionchanged:: 8.0
164 Use :class:`~enum.Enum` and drop the ``validate`` method.
166 .. versionchanged:: 8.0
167 Added the ``PROMPT`` value.
168 """
170 PROMPT = enum.auto()
171 """Used a prompt to confirm a default or provide a value."""
172 COMMANDLINE = enum.auto()
173 """The value was provided by the command line args."""
174 ENVIRONMENT = enum.auto()
175 """The value was provided with an environment variable."""
176 DEFAULT_MAP = enum.auto()
177 """Used a default provided by :attr:`Context.default_map`."""
178 DEFAULT = enum.auto()
179 """Used the default specified by the parameter."""
182class Context:
183 """The context is a special internal object that holds state relevant
184 for the script execution at every single level. It's normally invisible
185 to commands unless they opt-in to getting access to it.
187 The context is useful as it can pass internal objects around and can
188 control special execution features such as reading data from
189 environment variables.
191 A context can be used as context manager in which case it will call
192 :meth:`close` on teardown.
194 :param command: the command class for this context.
195 :param parent: the parent context.
196 :param info_name: the info name for this invocation. Generally this
197 is the most descriptive name for the script or
198 command. For the toplevel script it is usually
199 the name of the script, for commands below it it's
200 the name of the script.
201 :param obj: an arbitrary object of user data.
202 :param auto_envvar_prefix: the prefix to use for automatic environment
203 variables. If this is `None` then reading
204 from environment variables is disabled. This
205 does not affect manually set environment
206 variables which are always read.
207 :param default_map: a dictionary (like object) with default values
208 for parameters.
209 :param terminal_width: the width of the terminal. The default is
210 inherit from parent context. If no context
211 defines the terminal width then auto
212 detection will be applied.
213 :param max_content_width: the maximum width for content rendered by
214 Click (this currently only affects help
215 pages). This defaults to 80 characters if
216 not overridden. In other words: even if the
217 terminal is larger than that, Click will not
218 format things wider than 80 characters by
219 default. In addition to that, formatters might
220 add some safety mapping on the right.
221 :param resilient_parsing: if this flag is enabled then Click will
222 parse without any interactivity or callback
223 invocation. Default values will also be
224 ignored. This is useful for implementing
225 things such as completion support.
226 :param allow_extra_args: if this is set to `True` then extra arguments
227 at the end will not raise an error and will be
228 kept on the context. The default is to inherit
229 from the command.
230 :param allow_interspersed_args: if this is set to `False` then options
231 and arguments cannot be mixed. The
232 default is to inherit from the command.
233 :param ignore_unknown_options: instructs click to ignore options it does
234 not know and keeps them for later
235 processing.
236 :param help_option_names: optionally a list of strings that define how
237 the default help parameter is named. The
238 default is ``['--help']``.
239 :param token_normalize_func: an optional function that is used to
240 normalize tokens (options, choices,
241 etc.). This for instance can be used to
242 implement case insensitive behavior.
243 :param color: controls if the terminal supports ANSI colors or not. The
244 default is autodetection. This is only needed if ANSI
245 codes are used in texts that Click prints which is by
246 default not the case. This for instance would affect
247 help output.
248 :param show_default: Show the default value for commands. If this
249 value is not set, it defaults to the value from the parent
250 context. ``Command.show_default`` overrides this default for the
251 specific command.
253 .. versionchanged:: 8.2
254 The ``protected_args`` attribute is deprecated and will be removed in
255 Click 9.0. ``args`` will contain remaining unparsed tokens.
257 .. versionchanged:: 8.1
258 The ``show_default`` parameter is overridden by
259 ``Command.show_default``, instead of the other way around.
261 .. versionchanged:: 8.0
262 The ``show_default`` parameter defaults to the value from the
263 parent context.
265 .. versionchanged:: 7.1
266 Added the ``show_default`` parameter.
268 .. versionchanged:: 4.0
269 Added the ``color``, ``ignore_unknown_options``, and
270 ``max_content_width`` parameters.
272 .. versionchanged:: 3.0
273 Added the ``allow_extra_args`` and ``allow_interspersed_args``
274 parameters.
276 .. versionchanged:: 2.0
277 Added the ``resilient_parsing``, ``help_option_names``, and
278 ``token_normalize_func`` parameters.
279 """
281 #: The formatter class to create with :meth:`make_formatter`.
282 #:
283 #: .. versionadded:: 8.0
284 formatter_class: type[HelpFormatter] = HelpFormatter
286 def __init__(
287 self,
288 command: Command,
289 parent: Context | None = None,
290 info_name: str | None = None,
291 obj: t.Any | None = None,
292 auto_envvar_prefix: str | None = None,
293 default_map: cabc.MutableMapping[str, t.Any] | None = None,
294 terminal_width: int | None = None,
295 max_content_width: int | None = None,
296 resilient_parsing: bool = False,
297 allow_extra_args: bool | None = None,
298 allow_interspersed_args: bool | None = None,
299 ignore_unknown_options: bool | None = None,
300 help_option_names: list[str] | None = None,
301 token_normalize_func: t.Callable[[str], str] | None = None,
302 color: bool | None = None,
303 show_default: bool | None = None,
304 ) -> None:
305 #: the parent context or `None` if none exists.
306 self.parent = parent
307 #: the :class:`Command` for this context.
308 self.command = command
309 #: the descriptive information name
310 self.info_name = info_name
311 #: Map of parameter names to their parsed values. Parameters
312 #: with ``expose_value=False`` are not stored.
313 self.params: dict[str, t.Any] = {}
314 #: the leftover arguments.
315 self.args: list[str] = []
316 #: protected arguments. These are arguments that are prepended
317 #: to `args` when certain parsing scenarios are encountered but
318 #: must be never propagated to another arguments. This is used
319 #: to implement nested parsing.
320 self._protected_args: list[str] = []
321 #: the collected prefixes of the command's options.
322 self._opt_prefixes: set[str] = set(parent._opt_prefixes) if parent else set()
324 if obj is None and parent is not None:
325 obj = parent.obj
327 #: the user object stored.
328 self.obj: t.Any = obj
329 self._meta: dict[str, t.Any] = getattr(parent, "meta", {})
331 #: A dictionary (-like object) with defaults for parameters.
332 if (
333 default_map is None
334 and info_name is not None
335 and parent is not None
336 and parent.default_map is not None
337 ):
338 default_map = parent.default_map.get(info_name)
340 self.default_map: cabc.MutableMapping[str, t.Any] | None = default_map
342 #: This flag indicates if a subcommand is going to be executed. A
343 #: group callback can use this information to figure out if it's
344 #: being executed directly or because the execution flow passes
345 #: onwards to a subcommand. By default it's None, but it can be
346 #: the name of the subcommand to execute.
347 #:
348 #: If chaining is enabled this will be set to ``'*'`` in case
349 #: any commands are executed. It is however not possible to
350 #: figure out which ones. If you require this knowledge you
351 #: should use a :func:`result_callback`.
352 self.invoked_subcommand: str | None = None
354 if terminal_width is None and parent is not None:
355 terminal_width = parent.terminal_width
357 #: The width of the terminal (None is autodetection).
358 self.terminal_width: int | None = terminal_width
360 if max_content_width is None and parent is not None:
361 max_content_width = parent.max_content_width
363 #: The maximum width of formatted content (None implies a sensible
364 #: default which is 80 for most things).
365 self.max_content_width: int | None = max_content_width
367 if allow_extra_args is None:
368 allow_extra_args = command.allow_extra_args
370 #: Indicates if the context allows extra args or if it should
371 #: fail on parsing.
372 #:
373 #: .. versionadded:: 3.0
374 self.allow_extra_args = allow_extra_args
376 if allow_interspersed_args is None:
377 allow_interspersed_args = command.allow_interspersed_args
379 #: Indicates if the context allows mixing of arguments and
380 #: options or not.
381 #:
382 #: .. versionadded:: 3.0
383 self.allow_interspersed_args: bool = allow_interspersed_args
385 if ignore_unknown_options is None:
386 ignore_unknown_options = command.ignore_unknown_options
388 #: Instructs click to ignore options that a command does not
389 #: understand and will store it on the context for later
390 #: processing. This is primarily useful for situations where you
391 #: want to call into external programs. Generally this pattern is
392 #: strongly discouraged because it's not possibly to losslessly
393 #: forward all arguments.
394 #:
395 #: .. versionadded:: 4.0
396 self.ignore_unknown_options: bool = ignore_unknown_options
398 if help_option_names is None:
399 if parent is not None:
400 help_option_names = parent.help_option_names
401 else:
402 help_option_names = ["--help"]
404 #: The names for the help options.
405 self.help_option_names: list[str] = help_option_names
407 if token_normalize_func is None and parent is not None:
408 token_normalize_func = parent.token_normalize_func
410 #: An optional normalization function for tokens. This is
411 #: options, choices, commands etc.
412 self.token_normalize_func: t.Callable[[str], str] | None = token_normalize_func
414 #: Indicates if resilient parsing is enabled. In that case Click
415 #: will do its best to not cause any failures and default values
416 #: will be ignored. Useful for completion.
417 self.resilient_parsing: bool = resilient_parsing
419 # If there is no envvar prefix yet, but the parent has one and
420 # the command on this level has a name, we can expand the envvar
421 # prefix automatically.
422 if auto_envvar_prefix is None:
423 if (
424 parent is not None
425 and parent.auto_envvar_prefix is not None
426 and self.info_name is not None
427 ):
428 auto_envvar_prefix = (
429 f"{parent.auto_envvar_prefix}_{self.info_name.upper()}"
430 )
431 else:
432 auto_envvar_prefix = auto_envvar_prefix.upper()
434 if auto_envvar_prefix is not None:
435 auto_envvar_prefix = auto_envvar_prefix.replace("-", "_")
437 self.auto_envvar_prefix: str | None = auto_envvar_prefix
439 if color is None and parent is not None:
440 color = parent.color
442 #: Controls if styling output is wanted or not.
443 self.color: bool | None = color
445 if show_default is None and parent is not None:
446 show_default = parent.show_default
448 #: Show option default values when formatting help text.
449 self.show_default: bool | None = show_default
451 self._close_callbacks: list[t.Callable[[], t.Any]] = []
452 self._depth = 0
453 self._parameter_source: dict[str, ParameterSource] = {}
454 self._exit_stack = ExitStack()
456 @property
457 def protected_args(self) -> list[str]:
458 import warnings
460 warnings.warn(
461 "'protected_args' is deprecated and will be removed in Click 9.0."
462 " 'args' will contain remaining unparsed tokens.",
463 DeprecationWarning,
464 stacklevel=2,
465 )
466 return self._protected_args
468 def to_info_dict(self) -> dict[str, t.Any]:
469 """Gather information that could be useful for a tool generating
470 user-facing documentation. This traverses the entire CLI
471 structure.
473 .. code-block:: python
475 with Context(cli) as ctx:
476 info = ctx.to_info_dict()
478 .. versionadded:: 8.0
479 """
480 return {
481 "command": self.command.to_info_dict(self),
482 "info_name": self.info_name,
483 "allow_extra_args": self.allow_extra_args,
484 "allow_interspersed_args": self.allow_interspersed_args,
485 "ignore_unknown_options": self.ignore_unknown_options,
486 "auto_envvar_prefix": self.auto_envvar_prefix,
487 }
489 def __enter__(self) -> Context:
490 self._depth += 1
491 push_context(self)
492 return self
494 def __exit__(
495 self,
496 exc_type: type[BaseException] | None,
497 exc_value: BaseException | None,
498 tb: TracebackType | None,
499 ) -> bool | None:
500 self._depth -= 1
501 exit_result: bool | None = None
502 if self._depth == 0:
503 exit_result = self._close_with_exception_info(exc_type, exc_value, tb)
504 pop_context()
506 return exit_result
508 @contextmanager
509 def scope(self, cleanup: bool = True) -> cabc.Iterator[Context]:
510 """This helper method can be used with the context object to promote
511 it to the current thread local (see :func:`get_current_context`).
512 The default behavior of this is to invoke the cleanup functions which
513 can be disabled by setting `cleanup` to `False`. The cleanup
514 functions are typically used for things such as closing file handles.
516 If the cleanup is intended the context object can also be directly
517 used as a context manager.
519 Example usage::
521 with ctx.scope():
522 assert get_current_context() is ctx
524 This is equivalent::
526 with ctx:
527 assert get_current_context() is ctx
529 .. versionadded:: 5.0
531 :param cleanup: controls if the cleanup functions should be run or
532 not. The default is to run these functions. In
533 some situations the context only wants to be
534 temporarily pushed in which case this can be disabled.
535 Nested pushes automatically defer the cleanup.
536 """
537 if not cleanup:
538 self._depth += 1
539 try:
540 with self as rv:
541 yield rv
542 finally:
543 if not cleanup:
544 self._depth -= 1
546 @property
547 def meta(self) -> dict[str, t.Any]:
548 """This is a dictionary which is shared with all the contexts
549 that are nested. It exists so that click utilities can store some
550 state here if they need to. It is however the responsibility of
551 that code to manage this dictionary well.
553 The keys are supposed to be unique dotted strings. For instance
554 module paths are a good choice for it. What is stored in there is
555 irrelevant for the operation of click. However what is important is
556 that code that places data here adheres to the general semantics of
557 the system.
559 Example usage::
561 LANG_KEY = f'{__name__}.lang'
563 def set_language(value):
564 ctx = get_current_context()
565 ctx.meta[LANG_KEY] = value
567 def get_language():
568 return get_current_context().meta.get(LANG_KEY, 'en_US')
570 .. versionadded:: 5.0
571 """
572 return self._meta
574 def make_formatter(self) -> HelpFormatter:
575 """Creates the :class:`~click.HelpFormatter` for the help and
576 usage output.
578 To quickly customize the formatter class used without overriding
579 this method, set the :attr:`formatter_class` attribute.
581 .. versionchanged:: 8.0
582 Added the :attr:`formatter_class` attribute.
583 """
584 return self.formatter_class(
585 width=self.terminal_width, max_width=self.max_content_width
586 )
588 def with_resource(self, context_manager: AbstractContextManager[V]) -> V:
589 """Register a resource as if it were used in a ``with``
590 statement. The resource will be cleaned up when the context is
591 popped.
593 Uses :meth:`contextlib.ExitStack.enter_context`. It calls the
594 resource's ``__enter__()`` method and returns the result. When
595 the context is popped, it closes the stack, which calls the
596 resource's ``__exit__()`` method.
598 To register a cleanup function for something that isn't a
599 context manager, use :meth:`call_on_close`. Or use something
600 from :mod:`contextlib` to turn it into a context manager first.
602 .. code-block:: python
604 @click.group()
605 @click.option("--name")
606 @click.pass_context
607 def cli(ctx):
608 ctx.obj = ctx.with_resource(connect_db(name))
610 :param context_manager: The context manager to enter.
611 :return: Whatever ``context_manager.__enter__()`` returns.
613 .. versionadded:: 8.0
614 """
615 return self._exit_stack.enter_context(context_manager)
617 def call_on_close(self, f: t.Callable[..., t.Any]) -> t.Callable[..., t.Any]:
618 """Register a function to be called when the context tears down.
620 This can be used to close resources opened during the script
621 execution. Resources that support Python's context manager
622 protocol which would be used in a ``with`` statement should be
623 registered with :meth:`with_resource` instead.
625 :param f: The function to execute on teardown.
626 """
627 return self._exit_stack.callback(f)
629 def close(self) -> None:
630 """Invoke all close callbacks registered with
631 :meth:`call_on_close`, and exit all context managers entered
632 with :meth:`with_resource`.
633 """
634 self._close_with_exception_info(None, None, None)
636 def _close_with_exception_info(
637 self,
638 exc_type: type[BaseException] | None,
639 exc_value: BaseException | None,
640 tb: TracebackType | None,
641 ) -> bool | None:
642 """Unwind the exit stack by calling its :meth:`__exit__` providing the exception
643 information to allow for exception handling by the various resources registered
644 using :meth;`with_resource`
646 :return: Whatever ``exit_stack.__exit__()`` returns.
647 """
648 exit_result = self._exit_stack.__exit__(exc_type, exc_value, tb)
649 # In case the context is reused, create a new exit stack.
650 self._exit_stack = ExitStack()
652 return exit_result
654 @property
655 def command_path(self) -> str:
656 """The computed command path. This is used for the ``usage``
657 information on the help page. It's automatically created by
658 combining the info names of the chain of contexts to the root.
659 """
660 rv = ""
661 if self.info_name is not None:
662 rv = self.info_name
663 if self.parent is not None:
664 parent_command_path = [self.parent.command_path]
666 if isinstance(self.parent.command, Command):
667 for param in self.parent.command.get_params(self):
668 parent_command_path.extend(param.get_usage_pieces(self))
670 rv = f"{' '.join(parent_command_path)} {rv}"
671 return rv.lstrip()
673 def find_root(self) -> Context:
674 """Finds the outermost context."""
675 node = self
676 while node.parent is not None:
677 node = node.parent
678 return node
680 def find_object(self, object_type: type[V]) -> V | None:
681 """Finds the closest object of a given type."""
682 node: Context | None = self
684 while node is not None:
685 if isinstance(node.obj, object_type):
686 return node.obj
688 node = node.parent
690 return None
692 def ensure_object(self, object_type: type[V]) -> V:
693 """Like :meth:`find_object` but sets the innermost object to a
694 new instance of `object_type` if it does not exist.
695 """
696 rv = self.find_object(object_type)
697 if rv is None:
698 self.obj = rv = object_type()
699 return rv
701 def _default_map_has(self, name: str | None) -> bool:
702 """Check if :attr:`default_map` contains a real value for ``name``.
704 Returns ``False`` when the key is absent, the map is ``None``,
705 ``name`` is ``None``, or the stored value is the internal
706 :data:`UNSET` sentinel.
707 """
708 return (
709 name is not None
710 and self.default_map is not None
711 and name in self.default_map
712 and self.default_map[name] is not UNSET
713 )
715 @t.overload
716 def lookup_default(
717 self, name: str, call: t.Literal[True] = True
718 ) -> t.Any | None: ...
720 @t.overload
721 def lookup_default(
722 self, name: str, call: t.Literal[False] = ...
723 ) -> t.Any | t.Callable[[], t.Any] | None: ...
725 def lookup_default(self, name: str, call: bool = True) -> t.Any | None:
726 """Get the default for a parameter from :attr:`default_map`.
728 :param name: Name of the parameter.
729 :param call: If the default is a callable, call it. Disable to
730 return the callable instead.
732 .. versionchanged:: 8.0
733 Added the ``call`` parameter.
734 """
735 if not self._default_map_has(name):
736 return None
738 # Assert to make the type checker happy.
739 assert self.default_map is not None
740 value = self.default_map[name]
742 if call and callable(value):
743 return value()
745 return value
747 def fail(self, message: str) -> t.NoReturn:
748 """Aborts the execution of the program with a specific error
749 message.
751 :param message: the error message to fail with.
752 """
753 raise UsageError(message, self)
755 def abort(self) -> t.NoReturn:
756 """Aborts the script."""
757 raise Abort()
759 def exit(self, code: int = 0) -> t.NoReturn:
760 """Exits the application with a given exit code.
762 .. versionchanged:: 8.2
763 Callbacks and context managers registered with :meth:`call_on_close`
764 and :meth:`with_resource` are closed before exiting.
765 """
766 self.close()
767 raise Exit(code)
769 def get_usage(self) -> str:
770 """Helper method to get formatted usage string for the current
771 context and command.
772 """
773 return self.command.get_usage(self)
775 def get_help(self) -> str:
776 """Helper method to get formatted help page for the current
777 context and command.
778 """
779 return self.command.get_help(self)
781 def _make_sub_context(self, command: Command) -> Context:
782 """Create a new context of the same type as this context, but
783 for a new command.
785 :meta private:
786 """
787 return type(self)(command, info_name=command.name, parent=self)
789 @t.overload
790 def invoke(
791 self, callback: t.Callable[..., V], /, *args: t.Any, **kwargs: t.Any
792 ) -> V: ...
794 @t.overload
795 def invoke(self, callback: Command, /, *args: t.Any, **kwargs: t.Any) -> t.Any: ...
797 def invoke(
798 self, callback: Command | t.Callable[..., V], /, *args: t.Any, **kwargs: t.Any
799 ) -> t.Any | V:
800 """Invokes a command callback in exactly the way it expects. There
801 are two ways to invoke this method:
803 1. the first argument can be a callback and all other arguments and
804 keyword arguments are forwarded directly to the function.
805 2. the first argument is a click command object. In that case all
806 arguments are forwarded as well but proper click parameters
807 (options and click arguments) must be keyword arguments and Click
808 will fill in defaults.
810 .. versionchanged:: 8.0
811 All ``kwargs`` are tracked in :attr:`params` so they will be
812 passed if :meth:`forward` is called at multiple levels.
814 .. versionchanged:: 3.2
815 A new context is created, and missing arguments use default values.
816 """
817 if isinstance(callback, Command):
818 other_cmd = callback
820 if other_cmd.callback is None:
821 raise TypeError(
822 "The given command does not have a callback that can be invoked."
823 )
824 else:
825 callback = t.cast("t.Callable[..., V]", other_cmd.callback)
827 ctx = self._make_sub_context(other_cmd)
829 for param in other_cmd.params:
830 if param.name not in kwargs and param.expose_value:
831 default_value = param.get_default(ctx)
832 # We explicitly hide the :attr:`UNSET` value to the user, as we
833 # choose to make it an implementation detail. And because ``invoke``
834 # has been designed as part of Click public API, we return ``None``
835 # instead. Refs:
836 # https://github.com/pallets/click/issues/3066
837 # https://github.com/pallets/click/issues/3065
838 # https://github.com/pallets/click/pull/3068
839 if default_value is UNSET:
840 default_value = None
841 kwargs[param.name] = param.type_cast_value( # type: ignore
842 ctx, default_value
843 )
845 # Track all kwargs as params, so that forward() will pass
846 # them on in subsequent calls.
847 ctx.params.update(kwargs)
848 else:
849 ctx = self
851 with augment_usage_errors(self):
852 with ctx:
853 return callback(*args, **kwargs)
855 def forward(self, cmd: Command, /, *args: t.Any, **kwargs: t.Any) -> t.Any:
856 """Similar to :meth:`invoke` but fills in default keyword
857 arguments from the current context if the other command expects
858 it. This cannot invoke callbacks directly, only other commands.
860 .. versionchanged:: 8.0
861 All ``kwargs`` are tracked in :attr:`params` so they will be
862 passed if ``forward`` is called at multiple levels.
863 """
864 # Can only forward to other commands, not direct callbacks.
865 if not isinstance(cmd, Command):
866 raise TypeError("Callback is not a command.")
868 for param in self.params:
869 if param not in kwargs:
870 kwargs[param] = self.params[param]
872 return self.invoke(cmd, *args, **kwargs)
874 def set_parameter_source(self, name: str, source: ParameterSource) -> None:
875 """Set the source of a parameter. This indicates the location
876 from which the value of the parameter was obtained.
878 :param name: The name of the parameter.
879 :param source: A member of :class:`~click.core.ParameterSource`.
880 """
881 self._parameter_source[name] = source
883 def get_parameter_source(self, name: str) -> ParameterSource | None:
884 """Get the source of a parameter. This indicates the location
885 from which the value of the parameter was obtained.
887 This can be useful for determining when a user specified a value
888 on the command line that is the same as the default value. It
889 will be :attr:`~click.core.ParameterSource.DEFAULT` only if the
890 value was actually taken from the default.
892 :param name: The name of the parameter.
893 :rtype: ParameterSource
895 .. versionchanged:: 8.0
896 Returns ``None`` if the parameter was not provided from any
897 source.
898 """
899 return self._parameter_source.get(name)
902class Command:
903 """Commands are the basic building block of command line interfaces in
904 Click. A basic command handles command line parsing and might dispatch
905 more parsing to commands nested below it.
907 :param name: the name of the command to use unless a group overrides it.
908 :param context_settings: an optional dictionary with defaults that are
909 passed to the context object.
910 :param callback: the callback to invoke. This is optional.
911 :param params: the parameters to register with this command. This can
912 be either :class:`Option` or :class:`Argument` objects.
913 :param help: the help string to use for this command.
914 :param epilog: like the help string but it's printed at the end of the
915 help page after everything else.
916 :param short_help: the short help to use for this command. This is
917 shown on the command listing of the parent command.
918 :param add_help_option: by default each command registers a ``--help``
919 option. This can be disabled by this parameter.
920 :param no_args_is_help: this controls what happens if no arguments are
921 provided. This option is disabled by default.
922 If enabled this will add ``--help`` as argument
923 if no arguments are passed
924 :param hidden: hide this command from help outputs.
925 :param deprecated: If ``True`` or non-empty string, issues a message
926 indicating that the command is deprecated and highlights
927 its deprecation in --help. The message can be customized
928 by using a string as the value.
930 .. versionchanged:: 8.2
931 This is the base class for all commands, not ``BaseCommand``.
932 ``deprecated`` can be set to a string as well to customize the
933 deprecation message.
935 .. versionchanged:: 8.1
936 ``help``, ``epilog``, and ``short_help`` are stored unprocessed,
937 all formatting is done when outputting help text, not at init,
938 and is done even if not using the ``@command`` decorator.
940 .. versionchanged:: 8.0
941 Added a ``repr`` showing the command name.
943 .. versionchanged:: 7.1
944 Added the ``no_args_is_help`` parameter.
946 .. versionchanged:: 2.0
947 Added the ``context_settings`` parameter.
948 """
950 #: The context class to create with :meth:`make_context`.
951 #:
952 #: .. versionadded:: 8.0
953 context_class: type[Context] = Context
955 #: the default for the :attr:`Context.allow_extra_args` flag.
956 allow_extra_args = False
958 #: the default for the :attr:`Context.allow_interspersed_args` flag.
959 allow_interspersed_args = True
961 #: the default for the :attr:`Context.ignore_unknown_options` flag.
962 ignore_unknown_options = False
964 def __init__(
965 self,
966 name: str | None,
967 context_settings: cabc.MutableMapping[str, t.Any] | None = None,
968 callback: t.Callable[..., t.Any] | None = None,
969 params: list[Parameter] | None = None,
970 help: str | None = None,
971 epilog: str | None = None,
972 short_help: str | None = None,
973 options_metavar: str | None = "[OPTIONS]",
974 add_help_option: bool = True,
975 no_args_is_help: bool = False,
976 hidden: bool = False,
977 deprecated: bool | str = False,
978 ) -> None:
979 #: the name the command thinks it has. Upon registering a command
980 #: on a :class:`Group` the group will default the command name
981 #: with this information. You should instead use the
982 #: :class:`Context`\'s :attr:`~Context.info_name` attribute.
983 self.name = name
985 if context_settings is None:
986 context_settings = {}
988 #: an optional dictionary with defaults passed to the context.
989 self.context_settings: cabc.MutableMapping[str, t.Any] = context_settings
991 #: the callback to execute when the command fires. This might be
992 #: `None` in which case nothing happens.
993 self.callback = callback
994 #: the list of parameters for this command in the order they
995 #: should show up in the help page and execute. Eager parameters
996 #: will automatically be handled before non eager ones.
997 self.params: list[Parameter] = params or []
998 self.help = help
999 self.epilog = epilog
1000 self.options_metavar = options_metavar
1001 self.short_help = short_help
1002 self.add_help_option = add_help_option
1003 self._help_option = None
1004 self.no_args_is_help = no_args_is_help
1005 self.hidden = hidden
1006 self.deprecated = deprecated
1008 def to_info_dict(self, ctx: Context) -> dict[str, t.Any]:
1009 return {
1010 "name": self.name,
1011 "params": [param.to_info_dict() for param in self.get_params(ctx)],
1012 "help": self.help,
1013 "epilog": self.epilog,
1014 "short_help": self.short_help,
1015 "hidden": self.hidden,
1016 "deprecated": self.deprecated,
1017 }
1019 def __repr__(self) -> str:
1020 return f"<{self.__class__.__name__} {self.name}>"
1022 def get_usage(self, ctx: Context) -> str:
1023 """Formats the usage line into a string and returns it.
1025 Calls :meth:`format_usage` internally.
1026 """
1027 formatter = ctx.make_formatter()
1028 self.format_usage(ctx, formatter)
1029 return formatter.getvalue().rstrip("\n")
1031 def get_params(self, ctx: Context) -> list[Parameter]:
1032 params = self.params
1033 help_option = self.get_help_option(ctx)
1035 if help_option is not None:
1036 params = [*params, help_option]
1038 if __debug__:
1039 import warnings
1041 opts = [opt for param in params for opt in param.opts]
1042 opts_counter = Counter(opts)
1043 duplicate_opts = (opt for opt, count in opts_counter.items() if count > 1)
1045 for duplicate_opt in duplicate_opts:
1046 warnings.warn(
1047 (
1048 f"The parameter {duplicate_opt} is used more than once. "
1049 "Remove its duplicate as parameters should be unique."
1050 ),
1051 stacklevel=3,
1052 )
1054 return params
1056 def format_usage(self, ctx: Context, formatter: HelpFormatter) -> None:
1057 """Writes the usage line into the formatter.
1059 This is a low-level method called by :meth:`get_usage`.
1060 """
1061 pieces = self.collect_usage_pieces(ctx)
1062 formatter.write_usage(ctx.command_path, " ".join(pieces))
1064 def collect_usage_pieces(self, ctx: Context) -> list[str]:
1065 """Returns all the pieces that go into the usage line and returns
1066 it as a list of strings.
1067 """
1068 rv = [self.options_metavar] if self.options_metavar else []
1070 for param in self.get_params(ctx):
1071 rv.extend(param.get_usage_pieces(ctx))
1073 return rv
1075 def get_help_option_names(self, ctx: Context) -> list[str]:
1076 """Returns the names for the help option."""
1077 all_names = set(ctx.help_option_names)
1078 for param in self.params:
1079 all_names.difference_update(param.opts)
1080 all_names.difference_update(param.secondary_opts)
1081 return list(all_names)
1083 def get_help_option(self, ctx: Context) -> Option | None:
1084 """Returns the help option object.
1086 Skipped if :attr:`add_help_option` is ``False``.
1088 .. versionchanged:: 8.1.8
1089 The help option is now cached to avoid creating it multiple times.
1090 """
1091 help_option_names = self.get_help_option_names(ctx)
1093 if not help_option_names or not self.add_help_option:
1094 return None
1096 # Cache the help option object in private _help_option attribute to
1097 # avoid creating it multiple times. Not doing this will break the
1098 # callback odering by iter_params_for_processing(), which relies on
1099 # object comparison.
1100 if self._help_option is None:
1101 # Avoid circular import.
1102 from .decorators import help_option
1104 # Apply help_option decorator and pop resulting option
1105 help_option(*help_option_names)(self)
1106 self._help_option = self.params.pop() # type: ignore[assignment]
1108 return self._help_option
1110 def make_parser(self, ctx: Context) -> _OptionParser:
1111 """Creates the underlying option parser for this command."""
1112 parser = _OptionParser(ctx)
1113 for param in self.get_params(ctx):
1114 param.add_to_parser(parser, ctx)
1115 return parser
1117 def get_help(self, ctx: Context) -> str:
1118 """Formats the help into a string and returns it.
1120 Calls :meth:`format_help` internally.
1121 """
1122 formatter = ctx.make_formatter()
1123 self.format_help(ctx, formatter)
1124 return formatter.getvalue().rstrip("\n")
1126 def get_short_help_str(self, limit: int = 45) -> str:
1127 """Gets short help for the command or makes it by shortening the
1128 long help string.
1129 """
1130 if self.short_help:
1131 text = inspect.cleandoc(self.short_help)
1132 elif self.help:
1133 text = make_default_short_help(self.help, limit)
1134 else:
1135 text = ""
1137 if self.deprecated:
1138 deprecated_message = (
1139 f"(DEPRECATED: {self.deprecated})"
1140 if isinstance(self.deprecated, str)
1141 else "(DEPRECATED)"
1142 )
1143 text = _("{text} {deprecated_message}").format(
1144 text=text, deprecated_message=deprecated_message
1145 )
1147 return text.strip()
1149 def format_help(self, ctx: Context, formatter: HelpFormatter) -> None:
1150 """Writes the help into the formatter if it exists.
1152 This is a low-level method called by :meth:`get_help`.
1154 This calls the following methods:
1156 - :meth:`format_usage`
1157 - :meth:`format_help_text`
1158 - :meth:`format_options`
1159 - :meth:`format_epilog`
1160 """
1161 self.format_usage(ctx, formatter)
1162 self.format_help_text(ctx, formatter)
1163 self.format_options(ctx, formatter)
1164 self.format_epilog(ctx, formatter)
1166 def format_help_text(self, ctx: Context, formatter: HelpFormatter) -> None:
1167 """Writes the help text to the formatter if it exists."""
1168 if self.help is not None:
1169 # truncate the help text to the first form feed
1170 text = inspect.cleandoc(self.help).partition("\f")[0]
1171 else:
1172 text = ""
1174 if self.deprecated:
1175 deprecated_message = (
1176 f"(DEPRECATED: {self.deprecated})"
1177 if isinstance(self.deprecated, str)
1178 else "(DEPRECATED)"
1179 )
1180 text = _("{text} {deprecated_message}").format(
1181 text=text, deprecated_message=deprecated_message
1182 )
1184 if text:
1185 formatter.write_paragraph()
1187 with formatter.indentation():
1188 formatter.write_text(text)
1190 def format_options(self, ctx: Context, formatter: HelpFormatter) -> None:
1191 """Writes all the options into the formatter if they exist."""
1192 opts = []
1193 for param in self.get_params(ctx):
1194 rv = param.get_help_record(ctx)
1195 if rv is not None:
1196 opts.append(rv)
1198 if opts:
1199 with formatter.section(_("Options")):
1200 formatter.write_dl(opts)
1202 def format_epilog(self, ctx: Context, formatter: HelpFormatter) -> None:
1203 """Writes the epilog into the formatter if it exists."""
1204 if self.epilog:
1205 epilog = inspect.cleandoc(self.epilog)
1206 formatter.write_paragraph()
1208 with formatter.indentation():
1209 formatter.write_text(epilog)
1211 def make_context(
1212 self,
1213 info_name: str | None,
1214 args: list[str],
1215 parent: Context | None = None,
1216 **extra: t.Any,
1217 ) -> Context:
1218 """This function when given an info name and arguments will kick
1219 off the parsing and create a new :class:`Context`. It does not
1220 invoke the actual command callback though.
1222 To quickly customize the context class used without overriding
1223 this method, set the :attr:`context_class` attribute.
1225 :param info_name: the info name for this invocation. Generally this
1226 is the most descriptive name for the script or
1227 command. For the toplevel script it's usually
1228 the name of the script, for commands below it's
1229 the name of the command.
1230 :param args: the arguments to parse as list of strings.
1231 :param parent: the parent context if available.
1232 :param extra: extra keyword arguments forwarded to the context
1233 constructor.
1235 .. versionchanged:: 8.0
1236 Added the :attr:`context_class` attribute.
1237 """
1238 for key, value in self.context_settings.items():
1239 if key not in extra:
1240 extra[key] = value
1242 ctx = self.context_class(self, info_name=info_name, parent=parent, **extra)
1244 with ctx.scope(cleanup=False):
1245 self.parse_args(ctx, args)
1246 return ctx
1248 def parse_args(self, ctx: Context, args: list[str]) -> list[str]:
1249 if not args and self.no_args_is_help and not ctx.resilient_parsing:
1250 raise NoArgsIsHelpError(ctx)
1252 parser = self.make_parser(ctx)
1253 opts, args, param_order = parser.parse_args(args=args)
1255 for param in iter_params_for_processing(param_order, self.get_params(ctx)):
1256 _, args = param.handle_parse_result(ctx, opts, args)
1258 # We now have all parameters' values into `ctx.params`, but the data may contain
1259 # the `UNSET` sentinel.
1260 # Convert `UNSET` to `None` to ensure that the user doesn't see `UNSET`.
1261 #
1262 # Waiting until after the initial parse to convert allows us to treat `UNSET`
1263 # more like a missing value when multiple params use the same name.
1264 # Refs:
1265 # https://github.com/pallets/click/issues/3071
1266 # https://github.com/pallets/click/pull/3079
1267 for name, value in ctx.params.items():
1268 if value is UNSET:
1269 ctx.params[name] = None
1271 if args and not ctx.allow_extra_args and not ctx.resilient_parsing:
1272 ctx.fail(
1273 ngettext(
1274 "Got unexpected extra argument ({args})",
1275 "Got unexpected extra arguments ({args})",
1276 len(args),
1277 ).format(args=" ".join(map(str, args)))
1278 )
1280 ctx.args = args
1281 ctx._opt_prefixes.update(parser._opt_prefixes)
1282 return args
1284 def invoke(self, ctx: Context) -> t.Any:
1285 """Given a context, this invokes the attached callback (if it exists)
1286 in the right way.
1287 """
1288 if self.deprecated:
1289 extra_message = (
1290 f" {self.deprecated}" if isinstance(self.deprecated, str) else ""
1291 )
1292 message = _(
1293 "DeprecationWarning: The command {name!r} is deprecated.{extra_message}"
1294 ).format(name=self.name, extra_message=extra_message)
1295 echo(style(message, fg="red"), err=True)
1297 if self.callback is not None:
1298 return ctx.invoke(self.callback, **ctx.params)
1300 def shell_complete(self, ctx: Context, incomplete: str) -> list[CompletionItem]:
1301 """Return a list of completions for the incomplete value. Looks
1302 at the names of options and chained multi-commands.
1304 Any command could be part of a chained multi-command, so sibling
1305 commands are valid at any point during command completion.
1307 :param ctx: Invocation context for this command.
1308 :param incomplete: Value being completed. May be empty.
1310 .. versionadded:: 8.0
1311 """
1312 from click.shell_completion import CompletionItem
1314 results: list[CompletionItem] = []
1316 if incomplete and not incomplete[0].isalnum():
1317 for param in self.get_params(ctx):
1318 if (
1319 not isinstance(param, Option)
1320 or param.hidden
1321 or (
1322 not param.multiple
1323 and ctx.get_parameter_source(param.name) # type: ignore
1324 is ParameterSource.COMMANDLINE
1325 )
1326 ):
1327 continue
1329 results.extend(
1330 CompletionItem(name, help=param.help)
1331 for name in [*param.opts, *param.secondary_opts]
1332 if name.startswith(incomplete)
1333 )
1335 while ctx.parent is not None:
1336 ctx = ctx.parent
1338 if isinstance(ctx.command, Group) and ctx.command.chain:
1339 results.extend(
1340 CompletionItem(name, help=command.get_short_help_str())
1341 for name, command in _complete_visible_commands(ctx, incomplete)
1342 if name not in ctx._protected_args
1343 )
1345 return results
1347 @t.overload
1348 def main(
1349 self,
1350 args: cabc.Sequence[str] | None = None,
1351 prog_name: str | None = None,
1352 complete_var: str | None = None,
1353 standalone_mode: t.Literal[True] = True,
1354 **extra: t.Any,
1355 ) -> t.NoReturn: ...
1357 @t.overload
1358 def main(
1359 self,
1360 args: cabc.Sequence[str] | None = None,
1361 prog_name: str | None = None,
1362 complete_var: str | None = None,
1363 standalone_mode: bool = ...,
1364 **extra: t.Any,
1365 ) -> t.Any: ...
1367 def main(
1368 self,
1369 args: cabc.Sequence[str] | None = None,
1370 prog_name: str | None = None,
1371 complete_var: str | None = None,
1372 standalone_mode: bool = True,
1373 windows_expand_args: bool = True,
1374 **extra: t.Any,
1375 ) -> t.Any:
1376 """This is the way to invoke a script with all the bells and
1377 whistles as a command line application. This will always terminate
1378 the application after a call. If this is not wanted, ``SystemExit``
1379 needs to be caught.
1381 This method is also available by directly calling the instance of
1382 a :class:`Command`.
1384 :param args: the arguments that should be used for parsing. If not
1385 provided, ``sys.argv[1:]`` is used.
1386 :param prog_name: the program name that should be used. By default
1387 the program name is constructed by taking the file
1388 name from ``sys.argv[0]``.
1389 :param complete_var: the environment variable that controls the
1390 bash completion support. The default is
1391 ``"_<prog_name>_COMPLETE"`` with prog_name in
1392 uppercase.
1393 :param standalone_mode: the default behavior is to invoke the script
1394 in standalone mode. Click will then
1395 handle exceptions and convert them into
1396 error messages and the function will never
1397 return but shut down the interpreter. If
1398 this is set to `False` they will be
1399 propagated to the caller and the return
1400 value of this function is the return value
1401 of :meth:`invoke`.
1402 :param windows_expand_args: Expand glob patterns, user dir, and
1403 env vars in command line args on Windows.
1404 :param extra: extra keyword arguments are forwarded to the context
1405 constructor. See :class:`Context` for more information.
1407 .. versionchanged:: 8.0.1
1408 Added the ``windows_expand_args`` parameter to allow
1409 disabling command line arg expansion on Windows.
1411 .. versionchanged:: 8.0
1412 When taking arguments from ``sys.argv`` on Windows, glob
1413 patterns, user dir, and env vars are expanded.
1415 .. versionchanged:: 3.0
1416 Added the ``standalone_mode`` parameter.
1417 """
1418 if args is None:
1419 args = sys.argv[1:]
1421 if os.name == "nt" and windows_expand_args:
1422 args = _expand_args(args)
1423 else:
1424 args = list(args)
1426 if prog_name is None:
1427 prog_name = _detect_program_name()
1429 # Process shell completion requests and exit early.
1430 self._main_shell_completion(extra, prog_name, complete_var)
1432 try:
1433 try:
1434 with self.make_context(prog_name, args, **extra) as ctx:
1435 rv = self.invoke(ctx)
1436 if not standalone_mode:
1437 return rv
1438 # it's not safe to `ctx.exit(rv)` here!
1439 # note that `rv` may actually contain data like "1" which
1440 # has obvious effects
1441 # more subtle case: `rv=[None, None]` can come out of
1442 # chained commands which all returned `None` -- so it's not
1443 # even always obvious that `rv` indicates success/failure
1444 # by its truthiness/falsiness
1445 ctx.exit()
1446 except (EOFError, KeyboardInterrupt) as e:
1447 echo(file=sys.stderr)
1448 raise Abort() from e
1449 except ClickException as e:
1450 if not standalone_mode:
1451 raise
1452 e.show()
1453 sys.exit(e.exit_code)
1454 except OSError as e:
1455 if e.errno == errno.EPIPE:
1456 sys.stdout = t.cast(t.TextIO, PacifyFlushWrapper(sys.stdout))
1457 sys.stderr = t.cast(t.TextIO, PacifyFlushWrapper(sys.stderr))
1458 sys.exit(1)
1459 else:
1460 raise
1461 except Exit as e:
1462 if standalone_mode:
1463 sys.exit(e.exit_code)
1464 else:
1465 # in non-standalone mode, return the exit code
1466 # note that this is only reached if `self.invoke` above raises
1467 # an Exit explicitly -- thus bypassing the check there which
1468 # would return its result
1469 # the results of non-standalone execution may therefore be
1470 # somewhat ambiguous: if there are codepaths which lead to
1471 # `ctx.exit(1)` and to `return 1`, the caller won't be able to
1472 # tell the difference between the two
1473 return e.exit_code
1474 except Abort:
1475 if not standalone_mode:
1476 raise
1477 echo(_("Aborted!"), file=sys.stderr)
1478 sys.exit(1)
1480 def _main_shell_completion(
1481 self,
1482 ctx_args: cabc.MutableMapping[str, t.Any],
1483 prog_name: str,
1484 complete_var: str | None = None,
1485 ) -> None:
1486 """Check if the shell is asking for tab completion, process
1487 that, then exit early. Called from :meth:`main` before the
1488 program is invoked.
1490 :param prog_name: Name of the executable in the shell.
1491 :param complete_var: Name of the environment variable that holds
1492 the completion instruction. Defaults to
1493 ``_{PROG_NAME}_COMPLETE``.
1495 .. versionchanged:: 8.2.0
1496 Dots (``.``) in ``prog_name`` are replaced with underscores (``_``).
1497 """
1498 if complete_var is None:
1499 complete_name = prog_name.replace("-", "_").replace(".", "_")
1500 complete_var = f"_{complete_name}_COMPLETE".upper()
1502 instruction = os.environ.get(complete_var)
1504 if not instruction:
1505 return
1507 from .shell_completion import shell_complete
1509 rv = shell_complete(self, ctx_args, prog_name, complete_var, instruction)
1510 sys.exit(rv)
1512 def __call__(self, *args: t.Any, **kwargs: t.Any) -> t.Any:
1513 """Alias for :meth:`main`."""
1514 return self.main(*args, **kwargs)
1517class _FakeSubclassCheck(type):
1518 def __subclasscheck__(cls, subclass: type) -> bool:
1519 return issubclass(subclass, cls.__bases__[0])
1521 def __instancecheck__(cls, instance: t.Any) -> bool:
1522 return isinstance(instance, cls.__bases__[0])
1525class _BaseCommand(Command, metaclass=_FakeSubclassCheck):
1526 """
1527 .. deprecated:: 8.2
1528 Will be removed in Click 9.0. Use ``Command`` instead.
1529 """
1532class Group(Command):
1533 """A group is a command that nests other commands (or more groups).
1535 :param name: The name of the group command.
1536 :param commands: Map names to :class:`Command` objects. Can be a list, which
1537 will use :attr:`Command.name` as the keys.
1538 :param invoke_without_command: Invoke the group's callback even if a
1539 subcommand is not given.
1540 :param no_args_is_help: If no arguments are given, show the group's help and
1541 exit. Defaults to the opposite of ``invoke_without_command``.
1542 :param subcommand_metavar: How to represent the subcommand argument in help.
1543 The default will represent whether ``chain`` is set or not.
1544 :param chain: Allow passing more than one subcommand argument. After parsing
1545 a command's arguments, if any arguments remain another command will be
1546 matched, and so on.
1547 :param result_callback: A function to call after the group's and
1548 subcommand's callbacks. The value returned by the subcommand is passed.
1549 If ``chain`` is enabled, the value will be a list of values returned by
1550 all the commands. If ``invoke_without_command`` is enabled, the value
1551 will be the value returned by the group's callback, or an empty list if
1552 ``chain`` is enabled.
1553 :param kwargs: Other arguments passed to :class:`Command`.
1555 .. versionchanged:: 8.0
1556 The ``commands`` argument can be a list of command objects.
1558 .. versionchanged:: 8.2
1559 Merged with and replaces the ``MultiCommand`` base class.
1560 """
1562 allow_extra_args = True
1563 allow_interspersed_args = False
1565 #: If set, this is used by the group's :meth:`command` decorator
1566 #: as the default :class:`Command` class. This is useful to make all
1567 #: subcommands use a custom command class.
1568 #:
1569 #: .. versionadded:: 8.0
1570 command_class: type[Command] | None = None
1572 #: If set, this is used by the group's :meth:`group` decorator
1573 #: as the default :class:`Group` class. This is useful to make all
1574 #: subgroups use a custom group class.
1575 #:
1576 #: If set to the special value :class:`type` (literally
1577 #: ``group_class = type``), this group's class will be used as the
1578 #: default class. This makes a custom group class continue to make
1579 #: custom groups.
1580 #:
1581 #: .. versionadded:: 8.0
1582 group_class: type[Group] | type[type] | None = None
1583 # Literal[type] isn't valid, so use Type[type]
1585 def __init__(
1586 self,
1587 name: str | None = None,
1588 commands: cabc.MutableMapping[str, Command]
1589 | cabc.Sequence[Command]
1590 | None = None,
1591 invoke_without_command: bool = False,
1592 no_args_is_help: bool | None = None,
1593 subcommand_metavar: str | None = None,
1594 chain: bool = False,
1595 result_callback: t.Callable[..., t.Any] | None = None,
1596 **kwargs: t.Any,
1597 ) -> None:
1598 super().__init__(name, **kwargs)
1600 if commands is None:
1601 commands = {}
1602 elif isinstance(commands, abc.Sequence):
1603 commands = {c.name: c for c in commands if c.name is not None}
1605 #: The registered subcommands by their exported names.
1606 self.commands: cabc.MutableMapping[str, Command] = commands
1608 if no_args_is_help is None:
1609 no_args_is_help = not invoke_without_command
1611 self.no_args_is_help = no_args_is_help
1612 self.invoke_without_command = invoke_without_command
1614 if subcommand_metavar is None:
1615 if chain:
1616 subcommand_metavar = "COMMAND1 [ARGS]... [COMMAND2 [ARGS]...]..."
1617 else:
1618 subcommand_metavar = "COMMAND [ARGS]..."
1620 self.subcommand_metavar = subcommand_metavar
1621 self.chain = chain
1622 # The result callback that is stored. This can be set or
1623 # overridden with the :func:`result_callback` decorator.
1624 self._result_callback = result_callback
1626 if self.chain:
1627 for param in self.params:
1628 if isinstance(param, Argument) and not param.required:
1629 raise RuntimeError(
1630 "A group in chain mode cannot have optional arguments."
1631 )
1633 def to_info_dict(self, ctx: Context) -> dict[str, t.Any]:
1634 info_dict = super().to_info_dict(ctx)
1635 commands = {}
1637 for name in self.list_commands(ctx):
1638 command = self.get_command(ctx, name)
1640 if command is None:
1641 continue
1643 sub_ctx = ctx._make_sub_context(command)
1645 with sub_ctx.scope(cleanup=False):
1646 commands[name] = command.to_info_dict(sub_ctx)
1648 info_dict.update(commands=commands, chain=self.chain)
1649 return info_dict
1651 def add_command(self, cmd: Command, name: str | None = None) -> None:
1652 """Registers another :class:`Command` with this group. If the name
1653 is not provided, the name of the command is used.
1654 """
1655 name = name or cmd.name
1656 if name is None:
1657 raise TypeError("Command has no name.")
1658 _check_nested_chain(self, name, cmd, register=True)
1659 self.commands[name] = cmd
1661 @t.overload
1662 def command(self, __func: t.Callable[..., t.Any]) -> Command: ...
1664 @t.overload
1665 def command(
1666 self, *args: t.Any, **kwargs: t.Any
1667 ) -> t.Callable[[t.Callable[..., t.Any]], Command]: ...
1669 def command(
1670 self, *args: t.Any, **kwargs: t.Any
1671 ) -> t.Callable[[t.Callable[..., t.Any]], Command] | Command:
1672 """A shortcut decorator for declaring and attaching a command to
1673 the group. This takes the same arguments as :func:`command` and
1674 immediately registers the created command with this group by
1675 calling :meth:`add_command`.
1677 To customize the command class used, set the
1678 :attr:`command_class` attribute.
1680 .. versionchanged:: 8.1
1681 This decorator can be applied without parentheses.
1683 .. versionchanged:: 8.0
1684 Added the :attr:`command_class` attribute.
1685 """
1686 from .decorators import command
1688 func: t.Callable[..., t.Any] | None = None
1690 if args and callable(args[0]):
1691 assert len(args) == 1 and not kwargs, (
1692 "Use 'command(**kwargs)(callable)' to provide arguments."
1693 )
1694 (func,) = args
1695 args = ()
1697 if self.command_class and kwargs.get("cls") is None:
1698 kwargs["cls"] = self.command_class
1700 def decorator(f: t.Callable[..., t.Any]) -> Command:
1701 cmd: Command = command(*args, **kwargs)(f)
1702 self.add_command(cmd)
1703 return cmd
1705 if func is not None:
1706 return decorator(func)
1708 return decorator
1710 @t.overload
1711 def group(self, __func: t.Callable[..., t.Any]) -> Group: ...
1713 @t.overload
1714 def group(
1715 self, *args: t.Any, **kwargs: t.Any
1716 ) -> t.Callable[[t.Callable[..., t.Any]], Group]: ...
1718 def group(
1719 self, *args: t.Any, **kwargs: t.Any
1720 ) -> t.Callable[[t.Callable[..., t.Any]], Group] | Group:
1721 """A shortcut decorator for declaring and attaching a group to
1722 the group. This takes the same arguments as :func:`group` and
1723 immediately registers the created group with this group by
1724 calling :meth:`add_command`.
1726 To customize the group class used, set the :attr:`group_class`
1727 attribute.
1729 .. versionchanged:: 8.1
1730 This decorator can be applied without parentheses.
1732 .. versionchanged:: 8.0
1733 Added the :attr:`group_class` attribute.
1734 """
1735 from .decorators import group
1737 func: t.Callable[..., t.Any] | None = None
1739 if args and callable(args[0]):
1740 assert len(args) == 1 and not kwargs, (
1741 "Use 'group(**kwargs)(callable)' to provide arguments."
1742 )
1743 (func,) = args
1744 args = ()
1746 if self.group_class is not None and kwargs.get("cls") is None:
1747 if self.group_class is type:
1748 kwargs["cls"] = type(self)
1749 else:
1750 kwargs["cls"] = self.group_class
1752 def decorator(f: t.Callable[..., t.Any]) -> Group:
1753 cmd: Group = group(*args, **kwargs)(f)
1754 self.add_command(cmd)
1755 return cmd
1757 if func is not None:
1758 return decorator(func)
1760 return decorator
1762 def result_callback(self, replace: bool = False) -> t.Callable[[F], F]:
1763 """Adds a result callback to the command. By default if a
1764 result callback is already registered this will chain them but
1765 this can be disabled with the `replace` parameter. The result
1766 callback is invoked with the return value of the subcommand
1767 (or the list of return values from all subcommands if chaining
1768 is enabled) as well as the parameters as they would be passed
1769 to the main callback.
1771 Example::
1773 @click.group()
1774 @click.option('-i', '--input', default=23)
1775 def cli(input):
1776 return 42
1778 @cli.result_callback()
1779 def process_result(result, input):
1780 return result + input
1782 :param replace: if set to `True` an already existing result
1783 callback will be removed.
1785 .. versionchanged:: 8.0
1786 Renamed from ``resultcallback``.
1788 .. versionadded:: 3.0
1789 """
1791 def decorator(f: F) -> F:
1792 old_callback = self._result_callback
1794 if old_callback is None or replace:
1795 self._result_callback = f
1796 return f
1798 def function(value: t.Any, /, *args: t.Any, **kwargs: t.Any) -> t.Any:
1799 inner = old_callback(value, *args, **kwargs)
1800 return f(inner, *args, **kwargs)
1802 self._result_callback = rv = update_wrapper(t.cast(F, function), f)
1803 return rv # type: ignore[return-value]
1805 return decorator
1807 def get_command(self, ctx: Context, cmd_name: str) -> Command | None:
1808 """Given a context and a command name, this returns a :class:`Command`
1809 object if it exists or returns ``None``.
1810 """
1811 return self.commands.get(cmd_name)
1813 def list_commands(self, ctx: Context) -> list[str]:
1814 """Returns a list of subcommand names in the order they should appear."""
1815 return sorted(self.commands)
1817 def collect_usage_pieces(self, ctx: Context) -> list[str]:
1818 rv = super().collect_usage_pieces(ctx)
1819 rv.append(self.subcommand_metavar)
1820 return rv
1822 def format_options(self, ctx: Context, formatter: HelpFormatter) -> None:
1823 super().format_options(ctx, formatter)
1824 self.format_commands(ctx, formatter)
1826 def format_commands(self, ctx: Context, formatter: HelpFormatter) -> None:
1827 """Extra format methods for multi methods that adds all the commands
1828 after the options.
1829 """
1830 commands = []
1831 for subcommand in self.list_commands(ctx):
1832 cmd = self.get_command(ctx, subcommand)
1833 # What is this, the tool lied about a command. Ignore it
1834 if cmd is None:
1835 continue
1836 if cmd.hidden:
1837 continue
1839 commands.append((subcommand, cmd))
1841 # allow for 3 times the default spacing
1842 if len(commands):
1843 limit = formatter.width - 6 - max(len(cmd[0]) for cmd in commands)
1845 rows = []
1846 for subcommand, cmd in commands:
1847 help = cmd.get_short_help_str(limit)
1848 rows.append((subcommand, help))
1850 if rows:
1851 with formatter.section(_("Commands")):
1852 formatter.write_dl(rows)
1854 def parse_args(self, ctx: Context, args: list[str]) -> list[str]:
1855 if not args and self.no_args_is_help and not ctx.resilient_parsing:
1856 raise NoArgsIsHelpError(ctx)
1858 rest = super().parse_args(ctx, args)
1860 if self.chain:
1861 ctx._protected_args = rest
1862 ctx.args = []
1863 elif rest:
1864 ctx._protected_args, ctx.args = rest[:1], rest[1:]
1866 return ctx.args
1868 def invoke(self, ctx: Context) -> t.Any:
1869 def _process_result(value: t.Any) -> t.Any:
1870 if self._result_callback is not None:
1871 value = ctx.invoke(self._result_callback, value, **ctx.params)
1872 return value
1874 if not ctx._protected_args:
1875 if self.invoke_without_command:
1876 # No subcommand was invoked, so the result callback is
1877 # invoked with the group return value for regular
1878 # groups, or an empty list for chained groups.
1879 with ctx:
1880 rv = super().invoke(ctx)
1881 return _process_result([] if self.chain else rv)
1882 ctx.fail(_("Missing command."))
1884 # Fetch args back out
1885 args = [*ctx._protected_args, *ctx.args]
1886 ctx.args = []
1887 ctx._protected_args = []
1889 # If we're not in chain mode, we only allow the invocation of a
1890 # single command but we also inform the current context about the
1891 # name of the command to invoke.
1892 if not self.chain:
1893 # Make sure the context is entered so we do not clean up
1894 # resources until the result processor has worked.
1895 with ctx:
1896 cmd_name, cmd, args = self.resolve_command(ctx, args)
1897 assert cmd is not None
1898 ctx.invoked_subcommand = cmd_name
1899 super().invoke(ctx)
1900 sub_ctx = cmd.make_context(cmd_name, args, parent=ctx)
1901 with sub_ctx:
1902 return _process_result(sub_ctx.command.invoke(sub_ctx))
1904 # In chain mode we create the contexts step by step, but after the
1905 # base command has been invoked. Because at that point we do not
1906 # know the subcommands yet, the invoked subcommand attribute is
1907 # set to ``*`` to inform the command that subcommands are executed
1908 # but nothing else.
1909 with ctx:
1910 ctx.invoked_subcommand = "*" if args else None
1911 super().invoke(ctx)
1913 # Otherwise we make every single context and invoke them in a
1914 # chain. In that case the return value to the result processor
1915 # is the list of all invoked subcommand's results.
1916 contexts = []
1917 while args:
1918 cmd_name, cmd, args = self.resolve_command(ctx, args)
1919 assert cmd is not None
1920 sub_ctx = cmd.make_context(
1921 cmd_name,
1922 args,
1923 parent=ctx,
1924 allow_extra_args=True,
1925 allow_interspersed_args=False,
1926 )
1927 contexts.append(sub_ctx)
1928 args, sub_ctx.args = sub_ctx.args, []
1930 rv = []
1931 for sub_ctx in contexts:
1932 with sub_ctx:
1933 rv.append(sub_ctx.command.invoke(sub_ctx))
1934 return _process_result(rv)
1936 def resolve_command(
1937 self, ctx: Context, args: list[str]
1938 ) -> tuple[str | None, Command | None, list[str]]:
1939 cmd_name = make_str(args[0])
1940 original_cmd_name = cmd_name
1942 # Get the command
1943 cmd = self.get_command(ctx, cmd_name)
1945 # If we can't find the command but there is a normalization
1946 # function available, we try with that one.
1947 if cmd is None and ctx.token_normalize_func is not None:
1948 cmd_name = ctx.token_normalize_func(cmd_name)
1949 cmd = self.get_command(ctx, cmd_name)
1951 # If we don't find the command we want to show an error message
1952 # to the user that it was not provided. However, there is
1953 # something else we should do: if the first argument looks like
1954 # an option we want to kick off parsing again for arguments to
1955 # resolve things like --help which now should go to the main
1956 # place.
1957 if cmd is None and not ctx.resilient_parsing:
1958 if _split_opt(cmd_name)[0]:
1959 self.parse_args(ctx, args)
1960 ctx.fail(_("No such command {name!r}.").format(name=original_cmd_name))
1961 return cmd_name if cmd else None, cmd, args[1:]
1963 def shell_complete(self, ctx: Context, incomplete: str) -> list[CompletionItem]:
1964 """Return a list of completions for the incomplete value. Looks
1965 at the names of options, subcommands, and chained
1966 multi-commands.
1968 :param ctx: Invocation context for this command.
1969 :param incomplete: Value being completed. May be empty.
1971 .. versionadded:: 8.0
1972 """
1973 from click.shell_completion import CompletionItem
1975 results = [
1976 CompletionItem(name, help=command.get_short_help_str())
1977 for name, command in _complete_visible_commands(ctx, incomplete)
1978 ]
1979 results.extend(super().shell_complete(ctx, incomplete))
1980 return results
1983class _MultiCommand(Group, metaclass=_FakeSubclassCheck):
1984 """
1985 .. deprecated:: 8.2
1986 Will be removed in Click 9.0. Use ``Group`` instead.
1987 """
1990class CommandCollection(Group):
1991 """A :class:`Group` that looks up subcommands on other groups. If a command
1992 is not found on this group, each registered source is checked in order.
1993 Parameters on a source are not added to this group, and a source's callback
1994 is not invoked when invoking its commands. In other words, this "flattens"
1995 commands in many groups into this one group.
1997 :param name: The name of the group command.
1998 :param sources: A list of :class:`Group` objects to look up commands from.
1999 :param kwargs: Other arguments passed to :class:`Group`.
2001 .. versionchanged:: 8.2
2002 This is a subclass of ``Group``. Commands are looked up first on this
2003 group, then each of its sources.
2004 """
2006 def __init__(
2007 self,
2008 name: str | None = None,
2009 sources: list[Group] | None = None,
2010 **kwargs: t.Any,
2011 ) -> None:
2012 super().__init__(name, **kwargs)
2013 #: The list of registered groups.
2014 self.sources: list[Group] = sources or []
2016 def add_source(self, group: Group) -> None:
2017 """Add a group as a source of commands."""
2018 self.sources.append(group)
2020 def get_command(self, ctx: Context, cmd_name: str) -> Command | None:
2021 rv = super().get_command(ctx, cmd_name)
2023 if rv is not None:
2024 return rv
2026 for source in self.sources:
2027 rv = source.get_command(ctx, cmd_name)
2029 if rv is not None:
2030 if self.chain:
2031 _check_nested_chain(self, cmd_name, rv)
2033 return rv
2035 return None
2037 def list_commands(self, ctx: Context) -> list[str]:
2038 rv: set[str] = set(super().list_commands(ctx))
2040 for source in self.sources:
2041 rv.update(source.list_commands(ctx))
2043 return sorted(rv)
2046def _check_iter(value: t.Any) -> cabc.Iterator[t.Any]:
2047 """Check if the value is iterable but not a string. Raises a type
2048 error, or return an iterator over the value.
2049 """
2050 if isinstance(value, str):
2051 raise TypeError
2053 return iter(value)
2056class Parameter:
2057 r"""A parameter to a command comes in two versions: they are either
2058 :class:`Option`\s or :class:`Argument`\s. Other subclasses are currently
2059 not supported by design as some of the internals for parsing are
2060 intentionally not finalized.
2062 Some settings are supported by both options and arguments.
2064 :param param_decls: the parameter declarations for this option or
2065 argument. This is a list of flags or argument
2066 names.
2067 :param type: the type that should be used. Either a :class:`ParamType`
2068 or a Python type. The latter is converted into the former
2069 automatically if supported.
2070 :param required: controls if this is optional or not.
2071 :param default: the default value if omitted. This can also be a callable,
2072 in which case it's invoked when the default is needed
2073 without any arguments.
2074 :param callback: A function to further process or validate the value
2075 after type conversion. It is called as ``f(ctx, param, value)``
2076 and must return the value. It is called for all sources,
2077 including prompts.
2078 :param nargs: the number of arguments to match. If not ``1`` the return
2079 value is a tuple instead of single value. The default for
2080 nargs is ``1`` (except if the type is a tuple, then it's
2081 the arity of the tuple). If ``nargs=-1``, all remaining
2082 parameters are collected.
2083 :param metavar: how the value is represented in the help page.
2084 :param expose_value: if this is `True` then the value is passed onwards
2085 to the command callback and stored on the context,
2086 otherwise it's skipped.
2087 :param is_eager: eager values are processed before non eager ones. This
2088 should not be set for arguments or it will inverse the
2089 order of processing.
2090 :param envvar: environment variable(s) that are used to provide a default value for
2091 this parameter. This can be a string or a sequence of strings. If a sequence is
2092 given, only the first non-empty environment variable is used for the parameter.
2093 :param shell_complete: A function that returns custom shell
2094 completions. Used instead of the param's type completion if
2095 given. Takes ``ctx, param, incomplete`` and must return a list
2096 of :class:`~click.shell_completion.CompletionItem` or a list of
2097 strings.
2098 :param deprecated: If ``True`` or non-empty string, issues a message
2099 indicating that the argument is deprecated and highlights
2100 its deprecation in --help. The message can be customized
2101 by using a string as the value. A deprecated parameter
2102 cannot be required, a ValueError will be raised otherwise.
2104 .. versionchanged:: 8.2.0
2105 Introduction of ``deprecated``.
2107 .. versionchanged:: 8.2
2108 Adding duplicate parameter names to a :class:`~click.core.Command` will
2109 result in a ``UserWarning`` being shown.
2111 .. versionchanged:: 8.2
2112 Adding duplicate parameter names to a :class:`~click.core.Command` will
2113 result in a ``UserWarning`` being shown.
2115 .. versionchanged:: 8.0
2116 ``process_value`` validates required parameters and bounded
2117 ``nargs``, and invokes the parameter callback before returning
2118 the value. This allows the callback to validate prompts.
2119 ``full_process_value`` is removed.
2121 .. versionchanged:: 8.0
2122 ``autocompletion`` is renamed to ``shell_complete`` and has new
2123 semantics described above. The old name is deprecated and will
2124 be removed in 8.1, until then it will be wrapped to match the
2125 new requirements.
2127 .. versionchanged:: 8.0
2128 For ``multiple=True, nargs>1``, the default must be a list of
2129 tuples.
2131 .. versionchanged:: 8.0
2132 Setting a default is no longer required for ``nargs>1``, it will
2133 default to ``None``. ``multiple=True`` or ``nargs=-1`` will
2134 default to ``()``.
2136 .. versionchanged:: 7.1
2137 Empty environment variables are ignored rather than taking the
2138 empty string value. This makes it possible for scripts to clear
2139 variables if they can't unset them.
2141 .. versionchanged:: 2.0
2142 Changed signature for parameter callback to also be passed the
2143 parameter. The old callback format will still work, but it will
2144 raise a warning to give you a chance to migrate the code easier.
2145 """
2147 param_type_name = "parameter"
2149 def __init__(
2150 self,
2151 param_decls: cabc.Sequence[str] | None = None,
2152 type: types.ParamType | t.Any | None = None,
2153 required: bool = False,
2154 # XXX The default historically embed two concepts:
2155 # - the declaration of a Parameter object carrying the default (handy to
2156 # arbitrage the default value of coupled Parameters sharing the same
2157 # self.name, like flag options),
2158 # - and the actual value of the default.
2159 # It is confusing and is the source of many issues discussed in:
2160 # https://github.com/pallets/click/pull/3030
2161 # In the future, we might think of splitting it in two, not unlike
2162 # Option.is_flag and Option.flag_value: we could have something like
2163 # Parameter.is_default and Parameter.default_value.
2164 default: t.Any | t.Callable[[], t.Any] | None = UNSET,
2165 callback: t.Callable[[Context, Parameter, t.Any], t.Any] | None = None,
2166 nargs: int | None = None,
2167 multiple: bool = False,
2168 metavar: str | None = None,
2169 expose_value: bool = True,
2170 is_eager: bool = False,
2171 envvar: str | cabc.Sequence[str] | None = None,
2172 shell_complete: t.Callable[
2173 [Context, Parameter, str], list[CompletionItem] | list[str]
2174 ]
2175 | None = None,
2176 deprecated: bool | str = False,
2177 ) -> None:
2178 self.name: str | None
2179 self.opts: list[str]
2180 self.secondary_opts: list[str]
2181 self.name, self.opts, self.secondary_opts = self._parse_decls(
2182 param_decls or (), expose_value
2183 )
2184 self.type: types.ParamType = types.convert_type(type, default)
2186 # Default nargs to what the type tells us if we have that
2187 # information available.
2188 if nargs is None:
2189 if self.type.is_composite:
2190 nargs = self.type.arity
2191 else:
2192 nargs = 1
2194 self.required = required
2195 self.callback = callback
2196 self.nargs = nargs
2197 self.multiple = multiple
2198 self.expose_value = expose_value
2199 self.default: t.Any | t.Callable[[], t.Any] | None = default
2200 self.is_eager = is_eager
2201 self.metavar = metavar
2202 self.envvar = envvar
2203 self._custom_shell_complete = shell_complete
2204 self.deprecated = deprecated
2206 if __debug__:
2207 if self.type.is_composite and nargs != self.type.arity:
2208 raise ValueError(
2209 f"'nargs' must be {self.type.arity} (or None) for"
2210 f" type {self.type!r}, but it was {nargs}."
2211 )
2213 if required and deprecated:
2214 raise ValueError(
2215 f"The {self.param_type_name} '{self.human_readable_name}' "
2216 "is deprecated and still required. A deprecated "
2217 f"{self.param_type_name} cannot be required."
2218 )
2220 def to_info_dict(self) -> dict[str, t.Any]:
2221 """Gather information that could be useful for a tool generating
2222 user-facing documentation.
2224 Use :meth:`click.Context.to_info_dict` to traverse the entire
2225 CLI structure.
2227 .. versionchanged:: 8.3.0
2228 Returns ``None`` for the :attr:`default` if it was not set.
2230 .. versionadded:: 8.0
2231 """
2232 return {
2233 "name": self.name,
2234 "param_type_name": self.param_type_name,
2235 "opts": self.opts,
2236 "secondary_opts": self.secondary_opts,
2237 "type": self.type.to_info_dict(),
2238 "required": self.required,
2239 "nargs": self.nargs,
2240 "multiple": self.multiple,
2241 # We explicitly hide the :attr:`UNSET` value to the user, as we choose to
2242 # make it an implementation detail. And because ``to_info_dict`` has been
2243 # designed for documentation purposes, we return ``None`` instead.
2244 "default": self.default if self.default is not UNSET else None,
2245 "envvar": self.envvar,
2246 }
2248 def __repr__(self) -> str:
2249 return f"<{self.__class__.__name__} {self.name}>"
2251 def _parse_decls(
2252 self, decls: cabc.Sequence[str], expose_value: bool
2253 ) -> tuple[str | None, list[str], list[str]]:
2254 raise NotImplementedError()
2256 @property
2257 def human_readable_name(self) -> str:
2258 """Returns the human readable name of this parameter. This is the
2259 same as the name for options, but the metavar for arguments.
2260 """
2261 return self.name # type: ignore
2263 def make_metavar(self, ctx: Context) -> str:
2264 if self.metavar is not None:
2265 return self.metavar
2267 metavar = self.type.get_metavar(param=self, ctx=ctx)
2269 if metavar is None:
2270 metavar = self.type.name.upper()
2272 if self.nargs != 1:
2273 metavar += "..."
2275 return metavar
2277 @t.overload
2278 def get_default(
2279 self, ctx: Context, call: t.Literal[True] = True
2280 ) -> t.Any | None: ...
2282 @t.overload
2283 def get_default(
2284 self, ctx: Context, call: bool = ...
2285 ) -> t.Any | t.Callable[[], t.Any] | None: ...
2287 def get_default(
2288 self, ctx: Context, call: bool = True
2289 ) -> t.Any | t.Callable[[], t.Any] | None:
2290 """Get the default for the parameter. Tries
2291 :meth:`Context.lookup_default` first, then the local default.
2293 :param ctx: Current context.
2294 :param call: If the default is a callable, call it. Disable to
2295 return the callable instead.
2297 .. versionchanged:: 8.0.2
2298 Type casting is no longer performed when getting a default.
2300 .. versionchanged:: 8.0.1
2301 Type casting can fail in resilient parsing mode. Invalid
2302 defaults will not prevent showing help text.
2304 .. versionchanged:: 8.0
2305 Looks at ``ctx.default_map`` first.
2307 .. versionchanged:: 8.0
2308 Added the ``call`` parameter.
2309 """
2310 name = self.name
2311 value = ctx.lookup_default(name, call=False) if name is not None else None
2313 if value is None and not ctx._default_map_has(name):
2314 value = self.default
2316 if call and callable(value):
2317 value = value()
2319 return value
2321 def add_to_parser(self, parser: _OptionParser, ctx: Context) -> None:
2322 raise NotImplementedError()
2324 def consume_value(
2325 self, ctx: Context, opts: cabc.Mapping[str, t.Any]
2326 ) -> tuple[t.Any, ParameterSource]:
2327 """Returns the parameter value produced by the parser.
2329 If the parser did not produce a value from user input, the value is either
2330 sourced from the environment variable, the default map, or the parameter's
2331 default value. In that order of precedence.
2333 If no value is found, an internal sentinel value is returned.
2335 :meta private:
2336 """
2337 # Collect from the parse the value passed by the user to the CLI.
2338 value = opts.get(self.name, UNSET) # type: ignore
2339 # If the value is set, it means it was sourced from the command line by the
2340 # parser, otherwise it left unset by default.
2341 source = (
2342 ParameterSource.COMMANDLINE
2343 if value is not UNSET
2344 else ParameterSource.DEFAULT
2345 )
2347 if value is UNSET:
2348 envvar_value = self.value_from_envvar(ctx)
2349 if envvar_value is not None:
2350 value = envvar_value
2351 source = ParameterSource.ENVIRONMENT
2353 if value is UNSET:
2354 default_map_value = ctx.lookup_default(self.name) # type: ignore[arg-type]
2355 if default_map_value is not None or ctx._default_map_has(self.name):
2356 value = default_map_value
2357 source = ParameterSource.DEFAULT_MAP
2359 if value is UNSET:
2360 default_value = self.get_default(ctx)
2361 if default_value is not UNSET:
2362 value = default_value
2363 source = ParameterSource.DEFAULT
2365 return value, source
2367 def type_cast_value(self, ctx: Context, value: t.Any) -> t.Any:
2368 """Convert and validate a value against the parameter's
2369 :attr:`type`, :attr:`multiple`, and :attr:`nargs`.
2370 """
2371 if value is None:
2372 if self.multiple or self.nargs == -1:
2373 return ()
2374 else:
2375 return value
2377 def check_iter(value: t.Any) -> cabc.Iterator[t.Any]:
2378 try:
2379 return _check_iter(value)
2380 except TypeError:
2381 # This should only happen when passing in args manually,
2382 # the parser should construct an iterable when parsing
2383 # the command line.
2384 raise BadParameter(
2385 _("Value must be an iterable."), ctx=ctx, param=self
2386 ) from None
2388 # Define the conversion function based on nargs and type.
2390 if self.nargs == 1 or self.type.is_composite:
2392 def convert(value: t.Any) -> t.Any:
2393 return self.type(value, param=self, ctx=ctx)
2395 elif self.nargs == -1:
2397 def convert(value: t.Any) -> t.Any: # tuple[t.Any, ...]
2398 return tuple(self.type(x, self, ctx) for x in check_iter(value))
2400 else: # nargs > 1
2402 def convert(value: t.Any) -> t.Any: # tuple[t.Any, ...]
2403 value = tuple(check_iter(value))
2405 if len(value) != self.nargs:
2406 raise BadParameter(
2407 ngettext(
2408 "Takes {nargs} values but 1 was given.",
2409 "Takes {nargs} values but {len} were given.",
2410 len(value),
2411 ).format(nargs=self.nargs, len=len(value)),
2412 ctx=ctx,
2413 param=self,
2414 )
2416 return tuple(self.type(x, self, ctx) for x in value)
2418 if self.multiple:
2419 return tuple(convert(x) for x in check_iter(value))
2421 return convert(value)
2423 def value_is_missing(self, value: t.Any) -> bool:
2424 """A value is considered missing if:
2426 - it is :attr:`UNSET`,
2427 - or if it is an empty sequence while the parameter is suppose to have
2428 non-single value (i.e. :attr:`nargs` is not ``1`` or :attr:`multiple` is
2429 set).
2431 :meta private:
2432 """
2433 if value is UNSET:
2434 return True
2436 if (self.nargs != 1 or self.multiple) and value == ():
2437 return True
2439 return False
2441 def process_value(self, ctx: Context, value: t.Any) -> t.Any:
2442 """Process the value of this parameter:
2444 1. Type cast the value using :meth:`type_cast_value`.
2445 2. Check if the value is missing (see: :meth:`value_is_missing`), and raise
2446 :exc:`MissingParameter` if it is required.
2447 3. If a :attr:`callback` is set, call it to have the value replaced by the
2448 result of the callback. If the value was not set, the callback receive
2449 ``None``. This keep the legacy behavior as it was before the introduction of
2450 the :attr:`UNSET` sentinel.
2452 :meta private:
2453 """
2454 # shelter `type_cast_value` from ever seeing an `UNSET` value by handling the
2455 # cases in which `UNSET` gets special treatment explicitly at this layer
2456 #
2457 # Refs:
2458 # https://github.com/pallets/click/issues/3069
2459 if value is UNSET:
2460 if self.multiple or self.nargs == -1:
2461 value = ()
2462 else:
2463 value = self.type_cast_value(ctx, value)
2465 if self.required and self.value_is_missing(value):
2466 raise MissingParameter(ctx=ctx, param=self)
2468 if self.callback is not None:
2469 # Legacy case: UNSET is not exposed directly to the callback, but converted
2470 # to None.
2471 if value is UNSET:
2472 value = None
2474 # Search for parameters with UNSET values in the context.
2475 unset_keys = {k: None for k, v in ctx.params.items() if v is UNSET}
2476 # No UNSET values, call the callback as usual.
2477 if not unset_keys:
2478 value = self.callback(ctx, self, value)
2480 # Legacy case: provide a temporarily manipulated context to the callback
2481 # to hide UNSET values as None.
2482 #
2483 # Refs:
2484 # https://github.com/pallets/click/issues/3136
2485 # https://github.com/pallets/click/pull/3137
2486 else:
2487 # Add another layer to the context stack to clearly hint that the
2488 # context is temporarily modified.
2489 with ctx:
2490 # Update the context parameters to replace UNSET with None.
2491 ctx.params.update(unset_keys)
2492 # Feed these fake context parameters to the callback.
2493 value = self.callback(ctx, self, value)
2494 # Restore the UNSET values in the context parameters.
2495 ctx.params.update(
2496 {
2497 k: UNSET
2498 for k in unset_keys
2499 # Only restore keys that are present and still None, in case
2500 # the callback modified other parameters.
2501 if k in ctx.params and ctx.params[k] is None
2502 }
2503 )
2505 return value
2507 def resolve_envvar_value(self, ctx: Context) -> str | None:
2508 """Returns the value found in the environment variable(s) attached to this
2509 parameter.
2511 Environment variables values are `always returned as strings
2512 <https://docs.python.org/3/library/os.html#os.environ>`_.
2514 This method returns ``None`` if:
2516 - the :attr:`envvar` property is not set on the :class:`Parameter`,
2517 - the environment variable is not found in the environment,
2518 - the variable is found in the environment but its value is empty (i.e. the
2519 environment variable is present but has an empty string).
2521 If :attr:`envvar` is setup with multiple environment variables,
2522 then only the first non-empty value is returned.
2524 .. caution::
2526 The raw value extracted from the environment is not normalized and is
2527 returned as-is. Any normalization or reconciliation is performed later by
2528 the :class:`Parameter`'s :attr:`type`.
2530 :meta private:
2531 """
2532 if not self.envvar:
2533 return None
2535 if isinstance(self.envvar, str):
2536 rv = os.environ.get(self.envvar)
2538 if rv:
2539 return rv
2540 else:
2541 for envvar in self.envvar:
2542 rv = os.environ.get(envvar)
2544 # Return the first non-empty value of the list of environment variables.
2545 if rv:
2546 return rv
2547 # Else, absence of value is interpreted as an environment variable that
2548 # is not set, so proceed to the next one.
2550 return None
2552 def value_from_envvar(self, ctx: Context) -> str | cabc.Sequence[str] | None:
2553 """Process the raw environment variable string for this parameter.
2555 Returns the string as-is or splits it into a sequence of strings if the
2556 parameter is expecting multiple values (i.e. its :attr:`nargs` property is set
2557 to a value other than ``1``).
2559 :meta private:
2560 """
2561 rv = self.resolve_envvar_value(ctx)
2563 if rv is not None and self.nargs != 1:
2564 return self.type.split_envvar_value(rv)
2566 return rv
2568 def handle_parse_result(
2569 self, ctx: Context, opts: cabc.Mapping[str, t.Any], args: list[str]
2570 ) -> tuple[t.Any, list[str]]:
2571 """Process the value produced by the parser from user input.
2573 Always process the value through the Parameter's :attr:`type`, wherever it
2574 comes from.
2576 If the parameter is deprecated, this method warn the user about it. But only if
2577 the value has been explicitly set by the user (and as such, is not coming from
2578 a default).
2580 :meta private:
2581 """
2582 with augment_usage_errors(ctx, param=self):
2583 value, source = self.consume_value(ctx, opts)
2585 ctx.set_parameter_source(self.name, source) # type: ignore
2587 # Display a deprecation warning if necessary.
2588 if (
2589 self.deprecated
2590 and value is not UNSET
2591 and source < ParameterSource.DEFAULT_MAP
2592 ):
2593 extra_message = (
2594 f" {self.deprecated}" if isinstance(self.deprecated, str) else ""
2595 )
2596 message = _(
2597 "DeprecationWarning: The {param_type} {name!r} is deprecated."
2598 "{extra_message}"
2599 ).format(
2600 param_type=self.param_type_name,
2601 name=self.human_readable_name,
2602 extra_message=extra_message,
2603 )
2604 echo(style(message, fg="red"), err=True)
2606 # Process the value through the parameter's type.
2607 try:
2608 value = self.process_value(ctx, value)
2609 except Exception:
2610 if not ctx.resilient_parsing:
2611 raise
2612 # In resilient parsing mode, we do not want to fail the command if the
2613 # value is incompatible with the parameter type, so we reset the value
2614 # to UNSET, which will be interpreted as a missing value.
2615 value = UNSET
2617 # Add parameter's value to the context.
2618 if (
2619 self.expose_value
2620 # We skip adding the value if it was previously set by another parameter
2621 # targeting the same variable name. This prevents parameters competing for
2622 # the same name to override each other.
2623 and (self.name not in ctx.params or ctx.params[self.name] is UNSET)
2624 ):
2625 # Click is logically enforcing that the name is None if the parameter is
2626 # not to be exposed. We still assert it here to please the type checker.
2627 assert self.name is not None, (
2628 f"{self!r} parameter's name should not be None when exposing value."
2629 )
2630 ctx.params[self.name] = value
2632 return value, args
2634 def get_help_record(self, ctx: Context) -> tuple[str, str] | None:
2635 pass
2637 def get_usage_pieces(self, ctx: Context) -> list[str]:
2638 return []
2640 def get_error_hint(self, ctx: Context) -> str:
2641 """Get a stringified version of the param for use in error messages to
2642 indicate which param caused the error.
2643 """
2644 hint_list = self.opts or [self.human_readable_name]
2645 return " / ".join(f"'{x}'" for x in hint_list)
2647 def shell_complete(self, ctx: Context, incomplete: str) -> list[CompletionItem]:
2648 """Return a list of completions for the incomplete value. If a
2649 ``shell_complete`` function was given during init, it is used.
2650 Otherwise, the :attr:`type`
2651 :meth:`~click.types.ParamType.shell_complete` function is used.
2653 :param ctx: Invocation context for this command.
2654 :param incomplete: Value being completed. May be empty.
2656 .. versionadded:: 8.0
2657 """
2658 if self._custom_shell_complete is not None:
2659 results = self._custom_shell_complete(ctx, self, incomplete)
2661 if results and isinstance(results[0], str):
2662 from click.shell_completion import CompletionItem
2664 results = [CompletionItem(c) for c in results]
2666 return t.cast("list[CompletionItem]", results)
2668 return self.type.shell_complete(ctx, self, incomplete)
2671class Option(Parameter):
2672 """Options are usually optional values on the command line and
2673 have some extra features that arguments don't have.
2675 All other parameters are passed onwards to the parameter constructor.
2677 :param show_default: Show the default value for this option in its
2678 help text. Values are not shown by default, unless
2679 :attr:`Context.show_default` is ``True``. If this value is a
2680 string, it shows that string in parentheses instead of the
2681 actual value. This is particularly useful for dynamic options.
2682 For single option boolean flags, the default remains hidden if
2683 its value is ``False``.
2684 :param show_envvar: Controls if an environment variable should be
2685 shown on the help page and error messages.
2686 Normally, environment variables are not shown.
2687 :param prompt: If set to ``True`` or a non empty string then the
2688 user will be prompted for input. If set to ``True`` the prompt
2689 will be the option name capitalized. A deprecated option cannot be
2690 prompted.
2691 :param confirmation_prompt: Prompt a second time to confirm the
2692 value if it was prompted for. Can be set to a string instead of
2693 ``True`` to customize the message.
2694 :param prompt_required: If set to ``False``, the user will be
2695 prompted for input only when the option was specified as a flag
2696 without a value.
2697 :param hide_input: If this is ``True`` then the input on the prompt
2698 will be hidden from the user. This is useful for password input.
2699 :param is_flag: forces this option to act as a flag. The default is
2700 auto detection.
2701 :param flag_value: which value should be used for this flag if it's
2702 enabled. This is set to a boolean automatically if
2703 the option string contains a slash to mark two options.
2704 :param multiple: if this is set to `True` then the argument is accepted
2705 multiple times and recorded. This is similar to ``nargs``
2706 in how it works but supports arbitrary number of
2707 arguments.
2708 :param count: this flag makes an option increment an integer.
2709 :param allow_from_autoenv: if this is enabled then the value of this
2710 parameter will be pulled from an environment
2711 variable in case a prefix is defined on the
2712 context.
2713 :param help: the help string.
2714 :param hidden: hide this option from help outputs.
2715 :param attrs: Other command arguments described in :class:`Parameter`.
2717 .. versionchanged:: 8.2
2718 ``envvar`` used with ``flag_value`` will always use the ``flag_value``,
2719 previously it would use the value of the environment variable.
2721 .. versionchanged:: 8.1
2722 Help text indentation is cleaned here instead of only in the
2723 ``@option`` decorator.
2725 .. versionchanged:: 8.1
2726 The ``show_default`` parameter overrides
2727 ``Context.show_default``.
2729 .. versionchanged:: 8.1
2730 The default of a single option boolean flag is not shown if the
2731 default value is ``False``.
2733 .. versionchanged:: 8.0.1
2734 ``type`` is detected from ``flag_value`` if given.
2735 """
2737 param_type_name = "option"
2739 def __init__(
2740 self,
2741 param_decls: cabc.Sequence[str] | None = None,
2742 show_default: bool | str | None = None,
2743 prompt: bool | str = False,
2744 confirmation_prompt: bool | str = False,
2745 prompt_required: bool = True,
2746 hide_input: bool = False,
2747 is_flag: bool | None = None,
2748 flag_value: t.Any = UNSET,
2749 multiple: bool = False,
2750 count: bool = False,
2751 allow_from_autoenv: bool = True,
2752 type: types.ParamType | t.Any | None = None,
2753 help: str | None = None,
2754 hidden: bool = False,
2755 show_choices: bool = True,
2756 show_envvar: bool = False,
2757 deprecated: bool | str = False,
2758 **attrs: t.Any,
2759 ) -> None:
2760 if help:
2761 help = inspect.cleandoc(help)
2763 super().__init__(
2764 param_decls, type=type, multiple=multiple, deprecated=deprecated, **attrs
2765 )
2767 if prompt is True:
2768 if self.name is None:
2769 raise TypeError("'name' is required with 'prompt=True'.")
2771 prompt_text: str | None = self.name.replace("_", " ").capitalize()
2772 elif prompt is False:
2773 prompt_text = None
2774 else:
2775 prompt_text = prompt
2777 if deprecated:
2778 deprecated_message = (
2779 f"(DEPRECATED: {deprecated})"
2780 if isinstance(deprecated, str)
2781 else "(DEPRECATED)"
2782 )
2783 help = help + deprecated_message if help is not None else deprecated_message
2785 self.prompt = prompt_text
2786 self.confirmation_prompt = confirmation_prompt
2787 self.prompt_required = prompt_required
2788 self.hide_input = hide_input
2789 self.hidden = hidden
2791 # The _flag_needs_value property tells the parser that this option is a flag
2792 # that cannot be used standalone and needs a value. With this information, the
2793 # parser can determine whether to consider the next user-provided argument in
2794 # the CLI as a value for this flag or as a new option.
2795 # If prompt is enabled but not required, then it opens the possibility for the
2796 # option to gets its value from the user.
2797 self._flag_needs_value = self.prompt is not None and not self.prompt_required
2799 # Auto-detect if this is a flag or not.
2800 if is_flag is None:
2801 # Implicitly a flag because flag_value was set.
2802 if flag_value is not UNSET:
2803 is_flag = True
2804 # Not a flag, but when used as a flag it shows a prompt.
2805 elif self._flag_needs_value:
2806 is_flag = False
2807 # Implicitly a flag because secondary options names were given.
2808 elif self.secondary_opts:
2809 is_flag = True
2811 # The option is explicitly not a flag, but to determine whether or not it needs
2812 # value, we need to check if `flag_value` or `default` was set. Either one is
2813 # sufficient.
2814 # Ref: https://github.com/pallets/click/issues/3084
2815 elif is_flag is False and not self._flag_needs_value:
2816 self._flag_needs_value = flag_value is not UNSET or self.default is UNSET
2818 if is_flag:
2819 # Set missing default for flags if not explicitly required or prompted.
2820 if self.default is UNSET and not self.required and not self.prompt:
2821 if multiple:
2822 self.default = ()
2824 # Auto-detect the type of the flag based on the flag_value.
2825 if type is None:
2826 # A flag without a flag_value is a boolean flag.
2827 if flag_value is UNSET:
2828 self.type: types.ParamType = types.BoolParamType()
2829 # If the flag value is a boolean, use BoolParamType.
2830 elif isinstance(flag_value, bool):
2831 self.type = types.BoolParamType()
2832 # Otherwise, guess the type from the flag value.
2833 else:
2834 self.type = types.convert_type(None, flag_value)
2836 self.is_flag: bool = bool(is_flag)
2837 self.is_bool_flag: bool = bool(
2838 is_flag and isinstance(self.type, types.BoolParamType)
2839 )
2840 self.flag_value: t.Any = flag_value
2842 # Set boolean flag default to False if unset and not required.
2843 if self.is_bool_flag:
2844 if self.default is UNSET and not self.required:
2845 self.default = False
2847 # The alignement of default to the flag_value is resolved lazily in
2848 # get_default() to prevent callable flag_values (like classes) from
2849 # being instantiated. Refs:
2850 # https://github.com/pallets/click/issues/3121
2851 # https://github.com/pallets/click/issues/3024#issuecomment-3146199461
2852 # https://github.com/pallets/click/pull/3030/commits/06847da
2854 # Set the default flag_value if it is not set.
2855 if self.flag_value is UNSET:
2856 if self.is_flag:
2857 self.flag_value = True
2858 else:
2859 self.flag_value = None
2861 # Counting.
2862 self.count = count
2863 if count:
2864 if type is None:
2865 self.type = types.IntRange(min=0)
2866 if self.default is UNSET:
2867 self.default = 0
2869 self.allow_from_autoenv = allow_from_autoenv
2870 self.help = help
2871 self.show_default = show_default
2872 self.show_choices = show_choices
2873 self.show_envvar = show_envvar
2875 if __debug__:
2876 if deprecated and prompt:
2877 raise ValueError("`deprecated` options cannot use `prompt`.")
2879 if self.nargs == -1:
2880 raise TypeError("nargs=-1 is not supported for options.")
2882 if not self.is_bool_flag and self.secondary_opts:
2883 raise TypeError("Secondary flag is not valid for non-boolean flag.")
2885 if self.is_bool_flag and self.hide_input and self.prompt is not None:
2886 raise TypeError(
2887 "'prompt' with 'hide_input' is not valid for boolean flag."
2888 )
2890 if self.count:
2891 if self.multiple:
2892 raise TypeError("'count' is not valid with 'multiple'.")
2894 if self.is_flag:
2895 raise TypeError("'count' is not valid with 'is_flag'.")
2897 def to_info_dict(self) -> dict[str, t.Any]:
2898 """
2899 .. versionchanged:: 8.3.0
2900 Returns ``None`` for the :attr:`flag_value` if it was not set.
2901 """
2902 info_dict = super().to_info_dict()
2903 info_dict.update(
2904 help=self.help,
2905 prompt=self.prompt,
2906 is_flag=self.is_flag,
2907 # We explicitly hide the :attr:`UNSET` value to the user, as we choose to
2908 # make it an implementation detail. And because ``to_info_dict`` has been
2909 # designed for documentation purposes, we return ``None`` instead.
2910 flag_value=self.flag_value if self.flag_value is not UNSET else None,
2911 count=self.count,
2912 hidden=self.hidden,
2913 )
2914 return info_dict
2916 def get_default(
2917 self, ctx: Context, call: bool = True
2918 ) -> t.Any | t.Callable[[], t.Any] | None:
2919 """Return the default value for this option.
2921 For non-boolean flag options, ``default=True`` is treated as a sentinel
2922 meaning "activate this flag by default" and is resolved to
2923 :attr:`flag_value`. For example, with ``--upper/--lower`` feature
2924 switches where ``flag_value="upper"`` and ``default=True``, the default
2925 resolves to ``"upper"``.
2927 .. caution::
2928 This substitution only applies to non-boolean flags
2929 (:attr:`is_bool_flag` is ``False``). For boolean flags, ``True`` is
2930 a legitimate Python value and ``default=True`` is returned as-is.
2932 .. versionchanged:: 8.3.3
2933 ``default=True`` is no longer substituted with ``flag_value`` for
2934 boolean flags, fixing negative boolean flags like
2935 ``flag_value=False, default=True``.
2936 """
2937 value = super().get_default(ctx, call=False)
2939 # Resolve default=True to flag_value lazily (here instead of
2940 # __init__) to prevent callable flag_values (like classes) from
2941 # being instantiated by the callable check below.
2942 if value is True and self.is_flag and not self.is_bool_flag:
2943 value = self.flag_value
2944 elif call and callable(value):
2945 value = value()
2947 return value
2949 def get_error_hint(self, ctx: Context) -> str:
2950 result = super().get_error_hint(ctx)
2951 if self.show_envvar and self.envvar is not None:
2952 result += f" (env var: '{self.envvar}')"
2953 return result
2955 def _parse_decls(
2956 self, decls: cabc.Sequence[str], expose_value: bool
2957 ) -> tuple[str | None, list[str], list[str]]:
2958 opts = []
2959 secondary_opts = []
2960 name = None
2961 possible_names = []
2963 for decl in decls:
2964 if decl.isidentifier():
2965 if name is not None:
2966 raise TypeError(f"Name '{name}' defined twice")
2967 name = decl
2968 else:
2969 split_char = ";" if decl[:1] == "/" else "/"
2970 if split_char in decl:
2971 first, second = decl.split(split_char, 1)
2972 first = first.rstrip()
2973 if first:
2974 possible_names.append(_split_opt(first))
2975 opts.append(first)
2976 second = second.lstrip()
2977 if second:
2978 secondary_opts.append(second.lstrip())
2979 if first == second:
2980 raise ValueError(
2981 f"Boolean option {decl!r} cannot use the"
2982 " same flag for true/false."
2983 )
2984 else:
2985 possible_names.append(_split_opt(decl))
2986 opts.append(decl)
2988 if name is None and possible_names:
2989 possible_names.sort(key=lambda x: -len(x[0])) # group long options first
2990 name = possible_names[0][1].replace("-", "_").lower()
2991 if not name.isidentifier():
2992 name = None
2994 if name is None:
2995 if not expose_value:
2996 return None, opts, secondary_opts
2997 raise TypeError(
2998 f"Could not determine name for option with declarations {decls!r}"
2999 )
3001 if not opts and not secondary_opts:
3002 raise TypeError(
3003 f"No options defined but a name was passed ({name})."
3004 " Did you mean to declare an argument instead? Did"
3005 f" you mean to pass '--{name}'?"
3006 )
3008 return name, opts, secondary_opts
3010 def add_to_parser(self, parser: _OptionParser, ctx: Context) -> None:
3011 if self.multiple:
3012 action = "append"
3013 elif self.count:
3014 action = "count"
3015 else:
3016 action = "store"
3018 if self.is_flag:
3019 action = f"{action}_const"
3021 if self.is_bool_flag and self.secondary_opts:
3022 parser.add_option(
3023 obj=self, opts=self.opts, dest=self.name, action=action, const=True
3024 )
3025 parser.add_option(
3026 obj=self,
3027 opts=self.secondary_opts,
3028 dest=self.name,
3029 action=action,
3030 const=False,
3031 )
3032 else:
3033 parser.add_option(
3034 obj=self,
3035 opts=self.opts,
3036 dest=self.name,
3037 action=action,
3038 const=self.flag_value,
3039 )
3040 else:
3041 parser.add_option(
3042 obj=self,
3043 opts=self.opts,
3044 dest=self.name,
3045 action=action,
3046 nargs=self.nargs,
3047 )
3049 def get_help_record(self, ctx: Context) -> tuple[str, str] | None:
3050 if self.hidden:
3051 return None
3053 any_prefix_is_slash = False
3055 def _write_opts(opts: cabc.Sequence[str]) -> str:
3056 nonlocal any_prefix_is_slash
3058 rv, any_slashes = join_options(opts)
3060 if any_slashes:
3061 any_prefix_is_slash = True
3063 if not self.is_flag and not self.count:
3064 rv += f" {self.make_metavar(ctx=ctx)}"
3066 return rv
3068 rv = [_write_opts(self.opts)]
3070 if self.secondary_opts:
3071 rv.append(_write_opts(self.secondary_opts))
3073 help = self.help or ""
3075 extra = self.get_help_extra(ctx)
3076 extra_items = []
3077 if "envvars" in extra:
3078 extra_items.append(
3079 _("env var: {var}").format(var=", ".join(extra["envvars"]))
3080 )
3081 if "default" in extra:
3082 extra_items.append(_("default: {default}").format(default=extra["default"]))
3083 if "range" in extra:
3084 extra_items.append(extra["range"])
3085 if "required" in extra:
3086 extra_items.append(_(extra["required"]))
3088 if extra_items:
3089 extra_str = "; ".join(extra_items)
3090 help = f"{help} [{extra_str}]" if help else f"[{extra_str}]"
3092 return ("; " if any_prefix_is_slash else " / ").join(rv), help
3094 def get_help_extra(self, ctx: Context) -> types.OptionHelpExtra:
3095 extra: types.OptionHelpExtra = {}
3097 if self.show_envvar:
3098 envvar = self.envvar
3100 if envvar is None:
3101 if (
3102 self.allow_from_autoenv
3103 and ctx.auto_envvar_prefix is not None
3104 and self.name is not None
3105 ):
3106 envvar = f"{ctx.auto_envvar_prefix}_{self.name.upper()}"
3108 if envvar is not None:
3109 if isinstance(envvar, str):
3110 extra["envvars"] = (envvar,)
3111 else:
3112 extra["envvars"] = tuple(str(d) for d in envvar)
3114 # Temporarily enable resilient parsing to avoid type casting
3115 # failing for the default. Might be possible to extend this to
3116 # help formatting in general.
3117 resilient = ctx.resilient_parsing
3118 ctx.resilient_parsing = True
3120 try:
3121 default_value = self.get_default(ctx, call=False)
3122 finally:
3123 ctx.resilient_parsing = resilient
3125 show_default = False
3126 show_default_is_str = False
3128 if self.show_default is not None:
3129 if isinstance(self.show_default, str):
3130 show_default_is_str = show_default = True
3131 else:
3132 show_default = self.show_default
3133 elif ctx.show_default is not None:
3134 show_default = ctx.show_default
3136 if show_default_is_str or (
3137 show_default and (default_value not in (None, UNSET))
3138 ):
3139 if show_default_is_str:
3140 default_string = f"({self.show_default})"
3141 elif isinstance(default_value, (list, tuple)):
3142 default_string = ", ".join(str(d) for d in default_value)
3143 elif isinstance(default_value, enum.Enum):
3144 default_string = default_value.name
3145 elif inspect.isfunction(default_value):
3146 default_string = _("(dynamic)")
3147 elif self.is_bool_flag and self.secondary_opts:
3148 # For boolean flags that have distinct True/False opts,
3149 # use the opt without prefix instead of the value.
3150 default_string = _split_opt(
3151 (self.opts if default_value else self.secondary_opts)[0]
3152 )[1]
3153 elif self.is_bool_flag and not self.secondary_opts and not default_value:
3154 default_string = ""
3155 elif isinstance(default_value, str) and default_value == "":
3156 default_string = '""'
3157 else:
3158 default_string = str(default_value)
3160 if default_string:
3161 extra["default"] = default_string
3163 if (
3164 isinstance(self.type, types._NumberRangeBase)
3165 # skip count with default range type
3166 and not (self.count and self.type.min == 0 and self.type.max is None)
3167 ):
3168 range_str = self.type._describe_range()
3170 if range_str:
3171 extra["range"] = range_str
3173 if self.required:
3174 extra["required"] = "required"
3176 return extra
3178 def prompt_for_value(self, ctx: Context) -> t.Any:
3179 """This is an alternative flow that can be activated in the full
3180 value processing if a value does not exist. It will prompt the
3181 user until a valid value exists and then returns the processed
3182 value as result.
3183 """
3184 assert self.prompt is not None
3186 # Calculate the default before prompting anything to lock in the value before
3187 # attempting any user interaction.
3188 default = self.get_default(ctx)
3190 # A boolean flag can use a simplified [y/n] confirmation prompt.
3191 if self.is_bool_flag:
3192 # If we have no boolean default, we force the user to explicitly provide
3193 # one.
3194 if default in (UNSET, None):
3195 default = None
3196 # Nothing prevent you to declare an option that is simultaneously:
3197 # 1) auto-detected as a boolean flag,
3198 # 2) allowed to prompt, and
3199 # 3) still declare a non-boolean default.
3200 # This forced casting into a boolean is necessary to align any non-boolean
3201 # default to the prompt, which is going to be a [y/n]-style confirmation
3202 # because the option is still a boolean flag. That way, instead of [y/n],
3203 # we get [Y/n] or [y/N] depending on the truthy value of the default.
3204 # Refs: https://github.com/pallets/click/pull/3030#discussion_r2289180249
3205 else:
3206 default = bool(default)
3207 return confirm(self.prompt, default)
3209 # If show_default is given, provide this to `prompt` as well,
3210 # otherwise we use `prompt`'s default behavior
3211 prompt_kwargs: t.Any = {}
3212 if self.show_default is not None:
3213 prompt_kwargs["show_default"] = self.show_default
3215 return prompt(
3216 self.prompt,
3217 # Use ``None`` to inform the prompt() function to reiterate until a valid
3218 # value is provided by the user if we have no default.
3219 default=None if default is UNSET else default,
3220 type=self.type,
3221 hide_input=self.hide_input,
3222 show_choices=self.show_choices,
3223 confirmation_prompt=self.confirmation_prompt,
3224 value_proc=lambda x: self.process_value(ctx, x),
3225 **prompt_kwargs,
3226 )
3228 def resolve_envvar_value(self, ctx: Context) -> str | None:
3229 """:class:`Option` resolves its environment variable the same way as
3230 :func:`Parameter.resolve_envvar_value`, but it also supports
3231 :attr:`Context.auto_envvar_prefix`. If we could not find an environment from
3232 the :attr:`envvar` property, we fallback on :attr:`Context.auto_envvar_prefix`
3233 to build dynamiccaly the environment variable name using the
3234 :python:`{ctx.auto_envvar_prefix}_{self.name.upper()}` template.
3236 :meta private:
3237 """
3238 rv = super().resolve_envvar_value(ctx)
3240 if rv is not None:
3241 return rv
3243 if (
3244 self.allow_from_autoenv
3245 and ctx.auto_envvar_prefix is not None
3246 and self.name is not None
3247 ):
3248 envvar = f"{ctx.auto_envvar_prefix}_{self.name.upper()}"
3249 rv = os.environ.get(envvar)
3251 if rv:
3252 return rv
3254 return None
3256 def value_from_envvar(self, ctx: Context) -> t.Any:
3257 """For :class:`Option`, this method processes the raw environment variable
3258 string the same way as :func:`Parameter.value_from_envvar` does.
3260 But in the case of non-boolean flags, the value is analyzed to determine if the
3261 flag is activated or not, and returns a boolean of its activation, or the
3262 :attr:`flag_value` if the latter is set.
3264 This method also takes care of repeated options (i.e. options with
3265 :attr:`multiple` set to ``True``).
3267 :meta private:
3268 """
3269 rv = self.resolve_envvar_value(ctx)
3271 # Absent environment variable or an empty string is interpreted as unset.
3272 if rv is None:
3273 return None
3275 # Non-boolean flags are more liberal in what they accept. But a flag being a
3276 # flag, its envvar value still needs to be analyzed to determine if the flag is
3277 # activated or not.
3278 if self.is_flag and not self.is_bool_flag:
3279 # If the flag_value is set and match the envvar value, return it
3280 # directly.
3281 if self.flag_value is not UNSET and rv == self.flag_value:
3282 return self.flag_value
3283 # Analyze the envvar value as a boolean to know if the flag is
3284 # activated or not.
3285 return types.BoolParamType.str_to_bool(rv)
3287 # Split the envvar value if it is allowed to be repeated.
3288 value_depth = (self.nargs != 1) + bool(self.multiple)
3289 if value_depth > 0:
3290 multi_rv = self.type.split_envvar_value(rv)
3291 if self.multiple and self.nargs != 1:
3292 multi_rv = batch(multi_rv, self.nargs) # type: ignore[assignment]
3294 return multi_rv
3296 return rv
3298 def consume_value(
3299 self, ctx: Context, opts: cabc.Mapping[str, Parameter]
3300 ) -> tuple[t.Any, ParameterSource]:
3301 """For :class:`Option`, the value can be collected from an interactive prompt
3302 if the option is a flag that needs a value (and the :attr:`prompt` property is
3303 set).
3305 Additionally, this method handles flag option that are activated without a
3306 value, in which case the :attr:`flag_value` is returned.
3308 :meta private:
3309 """
3310 value, source = super().consume_value(ctx, opts)
3312 # The parser will emit a sentinel value if the option is allowed to as a flag
3313 # without a value.
3314 if value is FLAG_NEEDS_VALUE:
3315 # If the option allows for a prompt, we start an interaction with the user.
3316 if self.prompt is not None and not ctx.resilient_parsing:
3317 value = self.prompt_for_value(ctx)
3318 source = ParameterSource.PROMPT
3319 # Else the flag takes its flag_value as value.
3320 else:
3321 value = self.flag_value
3322 source = ParameterSource.COMMANDLINE
3324 # A flag which is activated always returns the flag value, unless the value
3325 # comes from the explicitly sets default.
3326 elif (
3327 self.is_flag
3328 and value is True
3329 and not self.is_bool_flag
3330 and source < ParameterSource.DEFAULT_MAP
3331 ):
3332 value = self.flag_value
3334 # Re-interpret a multiple option which has been sent as-is by the parser.
3335 # Here we replace each occurrence of value-less flags (marked by the
3336 # FLAG_NEEDS_VALUE sentinel) with the flag_value.
3337 elif (
3338 self.multiple
3339 and value is not UNSET
3340 and source < ParameterSource.DEFAULT_MAP
3341 and any(v is FLAG_NEEDS_VALUE for v in value)
3342 ):
3343 value = [self.flag_value if v is FLAG_NEEDS_VALUE else v for v in value]
3344 source = ParameterSource.COMMANDLINE
3346 # The value wasn't set, or used the param's default, prompt for one to the user
3347 # if prompting is enabled.
3348 elif (
3349 (value is UNSET or source >= ParameterSource.DEFAULT_MAP)
3350 and self.prompt is not None
3351 and (self.required or self.prompt_required)
3352 and not ctx.resilient_parsing
3353 ):
3354 value = self.prompt_for_value(ctx)
3355 source = ParameterSource.PROMPT
3357 return value, source
3359 def process_value(self, ctx: Context, value: t.Any) -> t.Any:
3360 # process_value has to be overridden on Options in order to capture
3361 # `value == UNSET` cases before `type_cast_value()` gets called.
3362 #
3363 # Refs:
3364 # https://github.com/pallets/click/issues/3069
3365 if self.is_flag and not self.required and self.is_bool_flag and value is UNSET:
3366 value = False
3368 if self.callback is not None:
3369 value = self.callback(ctx, self, value)
3371 return value
3373 # in the normal case, rely on Parameter.process_value
3374 return super().process_value(ctx, value)
3377class Argument(Parameter):
3378 """Arguments are positional parameters to a command. They generally
3379 provide fewer features than options but can have infinite ``nargs``
3380 and are required by default.
3382 All parameters are passed onwards to the constructor of :class:`Parameter`.
3383 """
3385 param_type_name = "argument"
3387 def __init__(
3388 self,
3389 param_decls: cabc.Sequence[str],
3390 required: bool | None = None,
3391 **attrs: t.Any,
3392 ) -> None:
3393 # Auto-detect the requirement status of the argument if not explicitly set.
3394 if required is None:
3395 # The argument gets automatically required if it has no explicit default
3396 # value set and is setup to match at least one value.
3397 if attrs.get("default", UNSET) is UNSET:
3398 required = attrs.get("nargs", 1) > 0
3399 # If the argument has a default value, it is not required.
3400 else:
3401 required = False
3403 if "multiple" in attrs:
3404 raise TypeError("__init__() got an unexpected keyword argument 'multiple'.")
3406 super().__init__(param_decls, required=required, **attrs)
3408 @property
3409 def human_readable_name(self) -> str:
3410 if self.metavar is not None:
3411 return self.metavar
3412 return self.name.upper() # type: ignore
3414 def make_metavar(self, ctx: Context) -> str:
3415 if self.metavar is not None:
3416 return self.metavar
3417 var = self.type.get_metavar(param=self, ctx=ctx)
3418 if not var:
3419 var = self.name.upper() # type: ignore
3420 if self.deprecated:
3421 var += "!"
3422 if not self.required:
3423 var = f"[{var}]"
3424 if self.nargs != 1:
3425 var += "..."
3426 return var
3428 def _parse_decls(
3429 self, decls: cabc.Sequence[str], expose_value: bool
3430 ) -> tuple[str | None, list[str], list[str]]:
3431 if not decls:
3432 if not expose_value:
3433 return None, [], []
3434 raise TypeError("Argument is marked as exposed, but does not have a name.")
3435 if len(decls) == 1:
3436 name = arg = decls[0]
3437 name = name.replace("-", "_").lower()
3438 else:
3439 raise TypeError(
3440 "Arguments take exactly one parameter declaration, got"
3441 f" {len(decls)}: {decls}."
3442 )
3443 return name, [arg], []
3445 def get_usage_pieces(self, ctx: Context) -> list[str]:
3446 return [self.make_metavar(ctx)]
3448 def get_error_hint(self, ctx: Context) -> str:
3449 return f"'{self.make_metavar(ctx)}'"
3451 def add_to_parser(self, parser: _OptionParser, ctx: Context) -> None:
3452 parser.add_argument(dest=self.name, nargs=self.nargs, obj=self)
3455def __getattr__(name: str) -> object:
3456 import warnings
3458 if name == "BaseCommand":
3459 warnings.warn(
3460 "'BaseCommand' is deprecated and will be removed in Click 9.0. Use"
3461 " 'Command' instead.",
3462 DeprecationWarning,
3463 stacklevel=2,
3464 )
3465 return _BaseCommand
3467 if name == "MultiCommand":
3468 warnings.warn(
3469 "'MultiCommand' is deprecated and will be removed in Click 9.0. Use"
3470 " 'Group' instead.",
3471 DeprecationWarning,
3472 stacklevel=2,
3473 )
3474 return _MultiCommand
3476 raise AttributeError(name)