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