Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/click/core.py: 33%
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 contextlib import AbstractContextManager
12from contextlib import contextmanager
13from contextlib import ExitStack
14from functools import update_wrapper
15from gettext import gettext as _
16from gettext import ngettext
17from itertools import repeat
18from types import TracebackType
20from . import types
21from .exceptions import Abort
22from .exceptions import BadParameter
23from .exceptions import ClickException
24from .exceptions import Exit
25from .exceptions import MissingParameter
26from .exceptions import UsageError
27from .formatting import HelpFormatter
28from .formatting import join_options
29from .globals import pop_context
30from .globals import push_context
31from .parser import _flag_needs_value
32from .parser import _OptionParser
33from .parser import _split_opt
34from .termui import confirm
35from .termui import prompt
36from .termui import style
37from .utils import _detect_program_name
38from .utils import _expand_args
39from .utils import echo
40from .utils import make_default_short_help
41from .utils import make_str
42from .utils import PacifyFlushWrapper
44if t.TYPE_CHECKING:
45 from .shell_completion import CompletionItem
47F = t.TypeVar("F", bound="t.Callable[..., t.Any]")
48V = t.TypeVar("V")
51def _complete_visible_commands(
52 ctx: Context, incomplete: str
53) -> cabc.Iterator[tuple[str, Command]]:
54 """List all the subcommands of a group that start with the
55 incomplete value and aren't hidden.
57 :param ctx: Invocation context for the group.
58 :param incomplete: Value being completed. May be empty.
59 """
60 multi = t.cast(Group, ctx.command)
62 for name in multi.list_commands(ctx):
63 if name.startswith(incomplete):
64 command = multi.get_command(ctx, name)
66 if command is not None and not command.hidden:
67 yield name, command
70def _check_nested_chain(
71 base_command: Group, cmd_name: str, cmd: Command, register: bool = False
72) -> None:
73 if not base_command.chain or not isinstance(cmd, Group):
74 return
76 if register:
77 message = (
78 f"It is not possible to add the group {cmd_name!r} to another"
79 f" group {base_command.name!r} that is in chain mode."
80 )
81 else:
82 message = (
83 f"Found the group {cmd_name!r} as subcommand to another group "
84 f" {base_command.name!r} that is in chain mode. This is not supported."
85 )
87 raise RuntimeError(message)
90def batch(iterable: cabc.Iterable[V], batch_size: int) -> list[tuple[V, ...]]:
91 return list(zip(*repeat(iter(iterable), batch_size)))
94@contextmanager
95def augment_usage_errors(
96 ctx: Context, param: Parameter | None = None
97) -> cabc.Iterator[None]:
98 """Context manager that attaches extra information to exceptions."""
99 try:
100 yield
101 except BadParameter as e:
102 if e.ctx is None:
103 e.ctx = ctx
104 if param is not None and e.param is None:
105 e.param = param
106 raise
107 except UsageError as e:
108 if e.ctx is None:
109 e.ctx = ctx
110 raise
113def iter_params_for_processing(
114 invocation_order: cabc.Sequence[Parameter],
115 declaration_order: cabc.Sequence[Parameter],
116) -> list[Parameter]:
117 """Given a sequence of parameters in the order as should be considered
118 for processing and an iterable of parameters that exist, this returns
119 a list in the correct order as they should be processed.
120 """
122 def sort_key(item: Parameter) -> tuple[bool, float]:
123 try:
124 idx: float = invocation_order.index(item)
125 except ValueError:
126 idx = float("inf")
128 return not item.is_eager, idx
130 return sorted(declaration_order, key=sort_key)
133class ParameterSource(enum.Enum):
134 """This is an :class:`~enum.Enum` that indicates the source of a
135 parameter's value.
137 Use :meth:`click.Context.get_parameter_source` to get the
138 source for a parameter by name.
140 .. versionchanged:: 8.0
141 Use :class:`~enum.Enum` and drop the ``validate`` method.
143 .. versionchanged:: 8.0
144 Added the ``PROMPT`` value.
145 """
147 COMMANDLINE = enum.auto()
148 """The value was provided by the command line args."""
149 ENVIRONMENT = enum.auto()
150 """The value was provided with an environment variable."""
151 DEFAULT = enum.auto()
152 """Used the default specified by the parameter."""
153 DEFAULT_MAP = enum.auto()
154 """Used a default provided by :attr:`Context.default_map`."""
155 PROMPT = enum.auto()
156 """Used a prompt to confirm a default or provide a value."""
159class Context:
160 """The context is a special internal object that holds state relevant
161 for the script execution at every single level. It's normally invisible
162 to commands unless they opt-in to getting access to it.
164 The context is useful as it can pass internal objects around and can
165 control special execution features such as reading data from
166 environment variables.
168 A context can be used as context manager in which case it will call
169 :meth:`close` on teardown.
171 :param command: the command class for this context.
172 :param parent: the parent context.
173 :param info_name: the info name for this invocation. Generally this
174 is the most descriptive name for the script or
175 command. For the toplevel script it is usually
176 the name of the script, for commands below it it's
177 the name of the script.
178 :param obj: an arbitrary object of user data.
179 :param auto_envvar_prefix: the prefix to use for automatic environment
180 variables. If this is `None` then reading
181 from environment variables is disabled. This
182 does not affect manually set environment
183 variables which are always read.
184 :param default_map: a dictionary (like object) with default values
185 for parameters.
186 :param terminal_width: the width of the terminal. The default is
187 inherit from parent context. If no context
188 defines the terminal width then auto
189 detection will be applied.
190 :param max_content_width: the maximum width for content rendered by
191 Click (this currently only affects help
192 pages). This defaults to 80 characters if
193 not overridden. In other words: even if the
194 terminal is larger than that, Click will not
195 format things wider than 80 characters by
196 default. In addition to that, formatters might
197 add some safety mapping on the right.
198 :param resilient_parsing: if this flag is enabled then Click will
199 parse without any interactivity or callback
200 invocation. Default values will also be
201 ignored. This is useful for implementing
202 things such as completion support.
203 :param allow_extra_args: if this is set to `True` then extra arguments
204 at the end will not raise an error and will be
205 kept on the context. The default is to inherit
206 from the command.
207 :param allow_interspersed_args: if this is set to `False` then options
208 and arguments cannot be mixed. The
209 default is to inherit from the command.
210 :param ignore_unknown_options: instructs click to ignore options it does
211 not know and keeps them for later
212 processing.
213 :param help_option_names: optionally a list of strings that define how
214 the default help parameter is named. The
215 default is ``['--help']``.
216 :param token_normalize_func: an optional function that is used to
217 normalize tokens (options, choices,
218 etc.). This for instance can be used to
219 implement case insensitive behavior.
220 :param color: controls if the terminal supports ANSI colors or not. The
221 default is autodetection. This is only needed if ANSI
222 codes are used in texts that Click prints which is by
223 default not the case. This for instance would affect
224 help output.
225 :param show_default: Show the default value for commands. If this
226 value is not set, it defaults to the value from the parent
227 context. ``Command.show_default`` overrides this default for the
228 specific command.
230 .. versionchanged:: 8.2
231 The ``protected_args`` attribute is deprecated and will be removed in
232 Click 9.0. ``args`` will contain remaining unparsed tokens.
234 .. versionchanged:: 8.1
235 The ``show_default`` parameter is overridden by
236 ``Command.show_default``, instead of the other way around.
238 .. versionchanged:: 8.0
239 The ``show_default`` parameter defaults to the value from the
240 parent context.
242 .. versionchanged:: 7.1
243 Added the ``show_default`` parameter.
245 .. versionchanged:: 4.0
246 Added the ``color``, ``ignore_unknown_options``, and
247 ``max_content_width`` parameters.
249 .. versionchanged:: 3.0
250 Added the ``allow_extra_args`` and ``allow_interspersed_args``
251 parameters.
253 .. versionchanged:: 2.0
254 Added the ``resilient_parsing``, ``help_option_names``, and
255 ``token_normalize_func`` parameters.
256 """
258 #: The formatter class to create with :meth:`make_formatter`.
259 #:
260 #: .. versionadded:: 8.0
261 formatter_class: type[HelpFormatter] = HelpFormatter
263 def __init__(
264 self,
265 command: Command,
266 parent: Context | None = None,
267 info_name: str | None = None,
268 obj: t.Any | None = None,
269 auto_envvar_prefix: str | None = None,
270 default_map: cabc.MutableMapping[str, t.Any] | None = None,
271 terminal_width: int | None = None,
272 max_content_width: int | None = None,
273 resilient_parsing: bool = False,
274 allow_extra_args: bool | None = None,
275 allow_interspersed_args: bool | None = None,
276 ignore_unknown_options: bool | None = None,
277 help_option_names: list[str] | None = None,
278 token_normalize_func: t.Callable[[str], str] | None = None,
279 color: bool | None = None,
280 show_default: bool | None = None,
281 ) -> None:
282 #: the parent context or `None` if none exists.
283 self.parent = parent
284 #: the :class:`Command` for this context.
285 self.command = command
286 #: the descriptive information name
287 self.info_name = info_name
288 #: Map of parameter names to their parsed values. Parameters
289 #: with ``expose_value=False`` are not stored.
290 self.params: dict[str, t.Any] = {}
291 #: the leftover arguments.
292 self.args: list[str] = []
293 #: protected arguments. These are arguments that are prepended
294 #: to `args` when certain parsing scenarios are encountered but
295 #: must be never propagated to another arguments. This is used
296 #: to implement nested parsing.
297 self._protected_args: list[str] = []
298 #: the collected prefixes of the command's options.
299 self._opt_prefixes: set[str] = set(parent._opt_prefixes) if parent else set()
301 if obj is None and parent is not None:
302 obj = parent.obj
304 #: the user object stored.
305 self.obj: t.Any = obj
306 self._meta: dict[str, t.Any] = getattr(parent, "meta", {})
308 #: A dictionary (-like object) with defaults for parameters.
309 if (
310 default_map is None
311 and info_name is not None
312 and parent is not None
313 and parent.default_map is not None
314 ):
315 default_map = parent.default_map.get(info_name)
317 self.default_map: cabc.MutableMapping[str, t.Any] | None = default_map
319 #: This flag indicates if a subcommand is going to be executed. A
320 #: group callback can use this information to figure out if it's
321 #: being executed directly or because the execution flow passes
322 #: onwards to a subcommand. By default it's None, but it can be
323 #: the name of the subcommand to execute.
324 #:
325 #: If chaining is enabled this will be set to ``'*'`` in case
326 #: any commands are executed. It is however not possible to
327 #: figure out which ones. If you require this knowledge you
328 #: should use a :func:`result_callback`.
329 self.invoked_subcommand: str | None = None
331 if terminal_width is None and parent is not None:
332 terminal_width = parent.terminal_width
334 #: The width of the terminal (None is autodetection).
335 self.terminal_width: int | None = terminal_width
337 if max_content_width is None and parent is not None:
338 max_content_width = parent.max_content_width
340 #: The maximum width of formatted content (None implies a sensible
341 #: default which is 80 for most things).
342 self.max_content_width: int | None = max_content_width
344 if allow_extra_args is None:
345 allow_extra_args = command.allow_extra_args
347 #: Indicates if the context allows extra args or if it should
348 #: fail on parsing.
349 #:
350 #: .. versionadded:: 3.0
351 self.allow_extra_args = allow_extra_args
353 if allow_interspersed_args is None:
354 allow_interspersed_args = command.allow_interspersed_args
356 #: Indicates if the context allows mixing of arguments and
357 #: options or not.
358 #:
359 #: .. versionadded:: 3.0
360 self.allow_interspersed_args: bool = allow_interspersed_args
362 if ignore_unknown_options is None:
363 ignore_unknown_options = command.ignore_unknown_options
365 #: Instructs click to ignore options that a command does not
366 #: understand and will store it on the context for later
367 #: processing. This is primarily useful for situations where you
368 #: want to call into external programs. Generally this pattern is
369 #: strongly discouraged because it's not possibly to losslessly
370 #: forward all arguments.
371 #:
372 #: .. versionadded:: 4.0
373 self.ignore_unknown_options: bool = ignore_unknown_options
375 if help_option_names is None:
376 if parent is not None:
377 help_option_names = parent.help_option_names
378 else:
379 help_option_names = ["--help"]
381 #: The names for the help options.
382 self.help_option_names: list[str] = help_option_names
384 if token_normalize_func is None and parent is not None:
385 token_normalize_func = parent.token_normalize_func
387 #: An optional normalization function for tokens. This is
388 #: options, choices, commands etc.
389 self.token_normalize_func: t.Callable[[str], str] | None = token_normalize_func
391 #: Indicates if resilient parsing is enabled. In that case Click
392 #: will do its best to not cause any failures and default values
393 #: will be ignored. Useful for completion.
394 self.resilient_parsing: bool = resilient_parsing
396 # If there is no envvar prefix yet, but the parent has one and
397 # the command on this level has a name, we can expand the envvar
398 # prefix automatically.
399 if auto_envvar_prefix is None:
400 if (
401 parent is not None
402 and parent.auto_envvar_prefix is not None
403 and self.info_name is not None
404 ):
405 auto_envvar_prefix = (
406 f"{parent.auto_envvar_prefix}_{self.info_name.upper()}"
407 )
408 else:
409 auto_envvar_prefix = auto_envvar_prefix.upper()
411 if auto_envvar_prefix is not None:
412 auto_envvar_prefix = auto_envvar_prefix.replace("-", "_")
414 self.auto_envvar_prefix: str | None = auto_envvar_prefix
416 if color is None and parent is not None:
417 color = parent.color
419 #: Controls if styling output is wanted or not.
420 self.color: bool | None = color
422 if show_default is None and parent is not None:
423 show_default = parent.show_default
425 #: Show option default values when formatting help text.
426 self.show_default: bool | None = show_default
428 self._close_callbacks: list[t.Callable[[], t.Any]] = []
429 self._depth = 0
430 self._parameter_source: dict[str, ParameterSource] = {}
431 self._exit_stack = ExitStack()
433 @property
434 def protected_args(self) -> list[str]:
435 import warnings
437 warnings.warn(
438 "'protected_args' is deprecated and will be removed in Click 9.0."
439 " 'args' will contain remaining unparsed tokens.",
440 DeprecationWarning,
441 stacklevel=2,
442 )
443 return self._protected_args
445 def to_info_dict(self) -> dict[str, t.Any]:
446 """Gather information that could be useful for a tool generating
447 user-facing documentation. This traverses the entire CLI
448 structure.
450 .. code-block:: python
452 with Context(cli) as ctx:
453 info = ctx.to_info_dict()
455 .. versionadded:: 8.0
456 """
457 return {
458 "command": self.command.to_info_dict(self),
459 "info_name": self.info_name,
460 "allow_extra_args": self.allow_extra_args,
461 "allow_interspersed_args": self.allow_interspersed_args,
462 "ignore_unknown_options": self.ignore_unknown_options,
463 "auto_envvar_prefix": self.auto_envvar_prefix,
464 }
466 def __enter__(self) -> Context:
467 self._depth += 1
468 push_context(self)
469 return self
471 def __exit__(
472 self,
473 exc_type: type[BaseException] | None,
474 exc_value: BaseException | None,
475 tb: TracebackType | None,
476 ) -> None:
477 self._depth -= 1
478 if self._depth == 0:
479 self.close()
480 pop_context()
482 @contextmanager
483 def scope(self, cleanup: bool = True) -> cabc.Iterator[Context]:
484 """This helper method can be used with the context object to promote
485 it to the current thread local (see :func:`get_current_context`).
486 The default behavior of this is to invoke the cleanup functions which
487 can be disabled by setting `cleanup` to `False`. The cleanup
488 functions are typically used for things such as closing file handles.
490 If the cleanup is intended the context object can also be directly
491 used as a context manager.
493 Example usage::
495 with ctx.scope():
496 assert get_current_context() is ctx
498 This is equivalent::
500 with ctx:
501 assert get_current_context() is ctx
503 .. versionadded:: 5.0
505 :param cleanup: controls if the cleanup functions should be run or
506 not. The default is to run these functions. In
507 some situations the context only wants to be
508 temporarily pushed in which case this can be disabled.
509 Nested pushes automatically defer the cleanup.
510 """
511 if not cleanup:
512 self._depth += 1
513 try:
514 with self as rv:
515 yield rv
516 finally:
517 if not cleanup:
518 self._depth -= 1
520 @property
521 def meta(self) -> dict[str, t.Any]:
522 """This is a dictionary which is shared with all the contexts
523 that are nested. It exists so that click utilities can store some
524 state here if they need to. It is however the responsibility of
525 that code to manage this dictionary well.
527 The keys are supposed to be unique dotted strings. For instance
528 module paths are a good choice for it. What is stored in there is
529 irrelevant for the operation of click. However what is important is
530 that code that places data here adheres to the general semantics of
531 the system.
533 Example usage::
535 LANG_KEY = f'{__name__}.lang'
537 def set_language(value):
538 ctx = get_current_context()
539 ctx.meta[LANG_KEY] = value
541 def get_language():
542 return get_current_context().meta.get(LANG_KEY, 'en_US')
544 .. versionadded:: 5.0
545 """
546 return self._meta
548 def make_formatter(self) -> HelpFormatter:
549 """Creates the :class:`~click.HelpFormatter` for the help and
550 usage output.
552 To quickly customize the formatter class used without overriding
553 this method, set the :attr:`formatter_class` attribute.
555 .. versionchanged:: 8.0
556 Added the :attr:`formatter_class` attribute.
557 """
558 return self.formatter_class(
559 width=self.terminal_width, max_width=self.max_content_width
560 )
562 def with_resource(self, context_manager: AbstractContextManager[V]) -> V:
563 """Register a resource as if it were used in a ``with``
564 statement. The resource will be cleaned up when the context is
565 popped.
567 Uses :meth:`contextlib.ExitStack.enter_context`. It calls the
568 resource's ``__enter__()`` method and returns the result. When
569 the context is popped, it closes the stack, which calls the
570 resource's ``__exit__()`` method.
572 To register a cleanup function for something that isn't a
573 context manager, use :meth:`call_on_close`. Or use something
574 from :mod:`contextlib` to turn it into a context manager first.
576 .. code-block:: python
578 @click.group()
579 @click.option("--name")
580 @click.pass_context
581 def cli(ctx):
582 ctx.obj = ctx.with_resource(connect_db(name))
584 :param context_manager: The context manager to enter.
585 :return: Whatever ``context_manager.__enter__()`` returns.
587 .. versionadded:: 8.0
588 """
589 return self._exit_stack.enter_context(context_manager)
591 def call_on_close(self, f: t.Callable[..., t.Any]) -> t.Callable[..., t.Any]:
592 """Register a function to be called when the context tears down.
594 This can be used to close resources opened during the script
595 execution. Resources that support Python's context manager
596 protocol which would be used in a ``with`` statement should be
597 registered with :meth:`with_resource` instead.
599 :param f: The function to execute on teardown.
600 """
601 return self._exit_stack.callback(f)
603 def close(self) -> None:
604 """Invoke all close callbacks registered with
605 :meth:`call_on_close`, and exit all context managers entered
606 with :meth:`with_resource`.
607 """
608 self._exit_stack.close()
609 # In case the context is reused, create a new exit stack.
610 self._exit_stack = ExitStack()
612 @property
613 def command_path(self) -> str:
614 """The computed command path. This is used for the ``usage``
615 information on the help page. It's automatically created by
616 combining the info names of the chain of contexts to the root.
617 """
618 rv = ""
619 if self.info_name is not None:
620 rv = self.info_name
621 if self.parent is not None:
622 parent_command_path = [self.parent.command_path]
624 if isinstance(self.parent.command, Command):
625 for param in self.parent.command.get_params(self):
626 parent_command_path.extend(param.get_usage_pieces(self))
628 rv = f"{' '.join(parent_command_path)} {rv}"
629 return rv.lstrip()
631 def find_root(self) -> Context:
632 """Finds the outermost context."""
633 node = self
634 while node.parent is not None:
635 node = node.parent
636 return node
638 def find_object(self, object_type: type[V]) -> V | None:
639 """Finds the closest object of a given type."""
640 node: Context | None = self
642 while node is not None:
643 if isinstance(node.obj, object_type):
644 return node.obj
646 node = node.parent
648 return None
650 def ensure_object(self, object_type: type[V]) -> V:
651 """Like :meth:`find_object` but sets the innermost object to a
652 new instance of `object_type` if it does not exist.
653 """
654 rv = self.find_object(object_type)
655 if rv is None:
656 self.obj = rv = object_type()
657 return rv
659 @t.overload
660 def lookup_default(
661 self, name: str, call: t.Literal[True] = True
662 ) -> t.Any | None: ...
664 @t.overload
665 def lookup_default(
666 self, name: str, call: t.Literal[False] = ...
667 ) -> t.Any | t.Callable[[], t.Any] | None: ...
669 def lookup_default(self, name: str, call: bool = True) -> t.Any | None:
670 """Get the default for a parameter from :attr:`default_map`.
672 :param name: Name of the parameter.
673 :param call: If the default is a callable, call it. Disable to
674 return the callable instead.
676 .. versionchanged:: 8.0
677 Added the ``call`` parameter.
678 """
679 if self.default_map is not None:
680 value = self.default_map.get(name)
682 if call and callable(value):
683 return value()
685 return value
687 return None
689 def fail(self, message: str) -> t.NoReturn:
690 """Aborts the execution of the program with a specific error
691 message.
693 :param message: the error message to fail with.
694 """
695 raise UsageError(message, self)
697 def abort(self) -> t.NoReturn:
698 """Aborts the script."""
699 raise Abort()
701 def exit(self, code: int = 0) -> t.NoReturn:
702 """Exits the application with a given exit code."""
703 raise Exit(code)
705 def get_usage(self) -> str:
706 """Helper method to get formatted usage string for the current
707 context and command.
708 """
709 return self.command.get_usage(self)
711 def get_help(self) -> str:
712 """Helper method to get formatted help page for the current
713 context and command.
714 """
715 return self.command.get_help(self)
717 def _make_sub_context(self, command: Command) -> Context:
718 """Create a new context of the same type as this context, but
719 for a new command.
721 :meta private:
722 """
723 return type(self)(command, info_name=command.name, parent=self)
725 @t.overload
726 def invoke(
727 self, callback: t.Callable[..., V], /, *args: t.Any, **kwargs: t.Any
728 ) -> V: ...
730 @t.overload
731 def invoke(self, callback: Command, /, *args: t.Any, **kwargs: t.Any) -> t.Any: ...
733 def invoke(
734 self, callback: Command | t.Callable[..., V], /, *args: t.Any, **kwargs: t.Any
735 ) -> t.Any | V:
736 """Invokes a command callback in exactly the way it expects. There
737 are two ways to invoke this method:
739 1. the first argument can be a callback and all other arguments and
740 keyword arguments are forwarded directly to the function.
741 2. the first argument is a click command object. In that case all
742 arguments are forwarded as well but proper click parameters
743 (options and click arguments) must be keyword arguments and Click
744 will fill in defaults.
746 .. versionchanged:: 8.0
747 All ``kwargs`` are tracked in :attr:`params` so they will be
748 passed if :meth:`forward` is called at multiple levels.
750 .. versionchanged:: 3.2
751 A new context is created, and missing arguments use default values.
752 """
753 if isinstance(callback, Command):
754 other_cmd = callback
756 if other_cmd.callback is None:
757 raise TypeError(
758 "The given command does not have a callback that can be invoked."
759 )
760 else:
761 callback = t.cast("t.Callable[..., V]", other_cmd.callback)
763 ctx = self._make_sub_context(other_cmd)
765 for param in other_cmd.params:
766 if param.name not in kwargs and param.expose_value:
767 kwargs[param.name] = param.type_cast_value( # type: ignore
768 ctx, param.get_default(ctx)
769 )
771 # Track all kwargs as params, so that forward() will pass
772 # them on in subsequent calls.
773 ctx.params.update(kwargs)
774 else:
775 ctx = self
777 with augment_usage_errors(self):
778 with ctx:
779 return callback(*args, **kwargs)
781 def forward(self, cmd: Command, /, *args: t.Any, **kwargs: t.Any) -> t.Any:
782 """Similar to :meth:`invoke` but fills in default keyword
783 arguments from the current context if the other command expects
784 it. This cannot invoke callbacks directly, only other commands.
786 .. versionchanged:: 8.0
787 All ``kwargs`` are tracked in :attr:`params` so they will be
788 passed if ``forward`` is called at multiple levels.
789 """
790 # Can only forward to other commands, not direct callbacks.
791 if not isinstance(cmd, Command):
792 raise TypeError("Callback is not a command.")
794 for param in self.params:
795 if param not in kwargs:
796 kwargs[param] = self.params[param]
798 return self.invoke(cmd, *args, **kwargs)
800 def set_parameter_source(self, name: str, source: ParameterSource) -> None:
801 """Set the source of a parameter. This indicates the location
802 from which the value of the parameter was obtained.
804 :param name: The name of the parameter.
805 :param source: A member of :class:`~click.core.ParameterSource`.
806 """
807 self._parameter_source[name] = source
809 def get_parameter_source(self, name: str) -> ParameterSource | None:
810 """Get the source of a parameter. This indicates the location
811 from which the value of the parameter was obtained.
813 This can be useful for determining when a user specified a value
814 on the command line that is the same as the default value. It
815 will be :attr:`~click.core.ParameterSource.DEFAULT` only if the
816 value was actually taken from the default.
818 :param name: The name of the parameter.
819 :rtype: ParameterSource
821 .. versionchanged:: 8.0
822 Returns ``None`` if the parameter was not provided from any
823 source.
824 """
825 return self._parameter_source.get(name)
828class Command:
829 """Commands are the basic building block of command line interfaces in
830 Click. A basic command handles command line parsing and might dispatch
831 more parsing to commands nested below it.
833 :param name: the name of the command to use unless a group overrides it.
834 :param context_settings: an optional dictionary with defaults that are
835 passed to the context object.
836 :param callback: the callback to invoke. This is optional.
837 :param params: the parameters to register with this command. This can
838 be either :class:`Option` or :class:`Argument` objects.
839 :param help: the help string to use for this command.
840 :param epilog: like the help string but it's printed at the end of the
841 help page after everything else.
842 :param short_help: the short help to use for this command. This is
843 shown on the command listing of the parent command.
844 :param add_help_option: by default each command registers a ``--help``
845 option. This can be disabled by this parameter.
846 :param no_args_is_help: this controls what happens if no arguments are
847 provided. This option is disabled by default.
848 If enabled this will add ``--help`` as argument
849 if no arguments are passed
850 :param hidden: hide this command from help outputs.
852 :param deprecated: issues a message indicating that
853 the command is deprecated.
855 .. versionchanged:: 8.2
856 This is the base class for all commands, not ``BaseCommand``.
858 .. versionchanged:: 8.1
859 ``help``, ``epilog``, and ``short_help`` are stored unprocessed,
860 all formatting is done when outputting help text, not at init,
861 and is done even if not using the ``@command`` decorator.
863 .. versionchanged:: 8.0
864 Added a ``repr`` showing the command name.
866 .. versionchanged:: 7.1
867 Added the ``no_args_is_help`` parameter.
869 .. versionchanged:: 2.0
870 Added the ``context_settings`` parameter.
871 """
873 #: The context class to create with :meth:`make_context`.
874 #:
875 #: .. versionadded:: 8.0
876 context_class: type[Context] = Context
878 #: the default for the :attr:`Context.allow_extra_args` flag.
879 allow_extra_args = False
881 #: the default for the :attr:`Context.allow_interspersed_args` flag.
882 allow_interspersed_args = True
884 #: the default for the :attr:`Context.ignore_unknown_options` flag.
885 ignore_unknown_options = False
887 def __init__(
888 self,
889 name: str | None,
890 context_settings: cabc.MutableMapping[str, t.Any] | None = None,
891 callback: t.Callable[..., t.Any] | None = None,
892 params: list[Parameter] | None = None,
893 help: str | None = None,
894 epilog: str | None = None,
895 short_help: str | None = None,
896 options_metavar: str | None = "[OPTIONS]",
897 add_help_option: bool = True,
898 no_args_is_help: bool = False,
899 hidden: bool = False,
900 deprecated: bool = False,
901 ) -> None:
902 #: the name the command thinks it has. Upon registering a command
903 #: on a :class:`Group` the group will default the command name
904 #: with this information. You should instead use the
905 #: :class:`Context`\'s :attr:`~Context.info_name` attribute.
906 self.name = name
908 if context_settings is None:
909 context_settings = {}
911 #: an optional dictionary with defaults passed to the context.
912 self.context_settings: cabc.MutableMapping[str, t.Any] = context_settings
914 #: the callback to execute when the command fires. This might be
915 #: `None` in which case nothing happens.
916 self.callback = callback
917 #: the list of parameters for this command in the order they
918 #: should show up in the help page and execute. Eager parameters
919 #: will automatically be handled before non eager ones.
920 self.params: list[Parameter] = params or []
921 self.help = help
922 self.epilog = epilog
923 self.options_metavar = options_metavar
924 self.short_help = short_help
925 self.add_help_option = add_help_option
926 self.no_args_is_help = no_args_is_help
927 self.hidden = hidden
928 self.deprecated = deprecated
930 def to_info_dict(self, ctx: Context) -> dict[str, t.Any]:
931 return {
932 "name": self.name,
933 "params": [param.to_info_dict() for param in self.get_params(ctx)],
934 "help": self.help,
935 "epilog": self.epilog,
936 "short_help": self.short_help,
937 "hidden": self.hidden,
938 "deprecated": self.deprecated,
939 }
941 def __repr__(self) -> str:
942 return f"<{self.__class__.__name__} {self.name}>"
944 def get_usage(self, ctx: Context) -> str:
945 """Formats the usage line into a string and returns it.
947 Calls :meth:`format_usage` internally.
948 """
949 formatter = ctx.make_formatter()
950 self.format_usage(ctx, formatter)
951 return formatter.getvalue().rstrip("\n")
953 def get_params(self, ctx: Context) -> list[Parameter]:
954 rv = self.params
955 help_option = self.get_help_option(ctx)
957 if help_option is not None:
958 rv = [*rv, help_option]
960 return rv
962 def format_usage(self, ctx: Context, formatter: HelpFormatter) -> None:
963 """Writes the usage line into the formatter.
965 This is a low-level method called by :meth:`get_usage`.
966 """
967 pieces = self.collect_usage_pieces(ctx)
968 formatter.write_usage(ctx.command_path, " ".join(pieces))
970 def collect_usage_pieces(self, ctx: Context) -> list[str]:
971 """Returns all the pieces that go into the usage line and returns
972 it as a list of strings.
973 """
974 rv = [self.options_metavar] if self.options_metavar else []
976 for param in self.get_params(ctx):
977 rv.extend(param.get_usage_pieces(ctx))
979 return rv
981 def get_help_option_names(self, ctx: Context) -> list[str]:
982 """Returns the names for the help option."""
983 all_names = set(ctx.help_option_names)
984 for param in self.params:
985 all_names.difference_update(param.opts)
986 all_names.difference_update(param.secondary_opts)
987 return list(all_names)
989 def get_help_option(self, ctx: Context) -> Option | None:
990 """Returns the help option object."""
991 help_options = self.get_help_option_names(ctx)
993 if not help_options or not self.add_help_option:
994 return None
996 def show_help(ctx: Context, param: Parameter, value: str) -> None:
997 if value and not ctx.resilient_parsing:
998 echo(ctx.get_help(), color=ctx.color)
999 ctx.exit()
1001 return Option(
1002 help_options,
1003 is_flag=True,
1004 is_eager=True,
1005 expose_value=False,
1006 callback=show_help,
1007 help=_("Show this message and exit."),
1008 )
1010 def make_parser(self, ctx: Context) -> _OptionParser:
1011 """Creates the underlying option parser for this command."""
1012 parser = _OptionParser(ctx)
1013 for param in self.get_params(ctx):
1014 param.add_to_parser(parser, ctx)
1015 return parser
1017 def get_help(self, ctx: Context) -> str:
1018 """Formats the help into a string and returns it.
1020 Calls :meth:`format_help` internally.
1021 """
1022 formatter = ctx.make_formatter()
1023 self.format_help(ctx, formatter)
1024 return formatter.getvalue().rstrip("\n")
1026 def get_short_help_str(self, limit: int = 45) -> str:
1027 """Gets short help for the command or makes it by shortening the
1028 long help string.
1029 """
1030 if self.short_help:
1031 text = inspect.cleandoc(self.short_help)
1032 elif self.help:
1033 text = make_default_short_help(self.help, limit)
1034 else:
1035 text = ""
1037 if self.deprecated:
1038 text = _("(Deprecated) {text}").format(text=text)
1040 return text.strip()
1042 def format_help(self, ctx: Context, formatter: HelpFormatter) -> None:
1043 """Writes the help into the formatter if it exists.
1045 This is a low-level method called by :meth:`get_help`.
1047 This calls the following methods:
1049 - :meth:`format_usage`
1050 - :meth:`format_help_text`
1051 - :meth:`format_options`
1052 - :meth:`format_epilog`
1053 """
1054 self.format_usage(ctx, formatter)
1055 self.format_help_text(ctx, formatter)
1056 self.format_options(ctx, formatter)
1057 self.format_epilog(ctx, formatter)
1059 def format_help_text(self, ctx: Context, formatter: HelpFormatter) -> None:
1060 """Writes the help text to the formatter if it exists."""
1061 if self.help is not None:
1062 # truncate the help text to the first form feed
1063 text = inspect.cleandoc(self.help).partition("\f")[0]
1064 else:
1065 text = ""
1067 if self.deprecated:
1068 text = _("(Deprecated) {text}").format(text=text)
1070 if text:
1071 formatter.write_paragraph()
1073 with formatter.indentation():
1074 formatter.write_text(text)
1076 def format_options(self, ctx: Context, formatter: HelpFormatter) -> None:
1077 """Writes all the options into the formatter if they exist."""
1078 opts = []
1079 for param in self.get_params(ctx):
1080 rv = param.get_help_record(ctx)
1081 if rv is not None:
1082 opts.append(rv)
1084 if opts:
1085 with formatter.section(_("Options")):
1086 formatter.write_dl(opts)
1088 def format_epilog(self, ctx: Context, formatter: HelpFormatter) -> None:
1089 """Writes the epilog into the formatter if it exists."""
1090 if self.epilog:
1091 epilog = inspect.cleandoc(self.epilog)
1092 formatter.write_paragraph()
1094 with formatter.indentation():
1095 formatter.write_text(epilog)
1097 def make_context(
1098 self,
1099 info_name: str | None,
1100 args: list[str],
1101 parent: Context | None = None,
1102 **extra: t.Any,
1103 ) -> Context:
1104 """This function when given an info name and arguments will kick
1105 off the parsing and create a new :class:`Context`. It does not
1106 invoke the actual command callback though.
1108 To quickly customize the context class used without overriding
1109 this method, set the :attr:`context_class` attribute.
1111 :param info_name: the info name for this invocation. Generally this
1112 is the most descriptive name for the script or
1113 command. For the toplevel script it's usually
1114 the name of the script, for commands below it's
1115 the name of the command.
1116 :param args: the arguments to parse as list of strings.
1117 :param parent: the parent context if available.
1118 :param extra: extra keyword arguments forwarded to the context
1119 constructor.
1121 .. versionchanged:: 8.0
1122 Added the :attr:`context_class` attribute.
1123 """
1124 for key, value in self.context_settings.items():
1125 if key not in extra:
1126 extra[key] = value
1128 ctx = self.context_class(self, info_name=info_name, parent=parent, **extra)
1130 with ctx.scope(cleanup=False):
1131 self.parse_args(ctx, args)
1132 return ctx
1134 def parse_args(self, ctx: Context, args: list[str]) -> list[str]:
1135 if not args and self.no_args_is_help and not ctx.resilient_parsing:
1136 echo(ctx.get_help(), color=ctx.color)
1137 ctx.exit()
1139 parser = self.make_parser(ctx)
1140 opts, args, param_order = parser.parse_args(args=args)
1142 for param in iter_params_for_processing(param_order, self.get_params(ctx)):
1143 value, args = param.handle_parse_result(ctx, opts, args)
1145 if args and not ctx.allow_extra_args and not ctx.resilient_parsing:
1146 ctx.fail(
1147 ngettext(
1148 "Got unexpected extra argument ({args})",
1149 "Got unexpected extra arguments ({args})",
1150 len(args),
1151 ).format(args=" ".join(map(str, args)))
1152 )
1154 ctx.args = args
1155 ctx._opt_prefixes.update(parser._opt_prefixes)
1156 return args
1158 def invoke(self, ctx: Context) -> t.Any:
1159 """Given a context, this invokes the attached callback (if it exists)
1160 in the right way.
1161 """
1162 if self.deprecated:
1163 message = _(
1164 "DeprecationWarning: The command {name!r} is deprecated."
1165 ).format(name=self.name)
1166 echo(style(message, fg="red"), err=True)
1168 if self.callback is not None:
1169 return ctx.invoke(self.callback, **ctx.params)
1171 def shell_complete(self, ctx: Context, incomplete: str) -> list[CompletionItem]:
1172 """Return a list of completions for the incomplete value. Looks
1173 at the names of options and chained multi-commands.
1175 Any command could be part of a chained multi-command, so sibling
1176 commands are valid at any point during command completion.
1178 :param ctx: Invocation context for this command.
1179 :param incomplete: Value being completed. May be empty.
1181 .. versionadded:: 8.0
1182 """
1183 from click.shell_completion import CompletionItem
1185 results: list[CompletionItem] = []
1187 if incomplete and not incomplete[0].isalnum():
1188 for param in self.get_params(ctx):
1189 if (
1190 not isinstance(param, Option)
1191 or param.hidden
1192 or (
1193 not param.multiple
1194 and ctx.get_parameter_source(param.name) # type: ignore
1195 is ParameterSource.COMMANDLINE
1196 )
1197 ):
1198 continue
1200 results.extend(
1201 CompletionItem(name, help=param.help)
1202 for name in [*param.opts, *param.secondary_opts]
1203 if name.startswith(incomplete)
1204 )
1206 while ctx.parent is not None:
1207 ctx = ctx.parent
1209 if isinstance(ctx.command, Group) and ctx.command.chain:
1210 results.extend(
1211 CompletionItem(name, help=command.get_short_help_str())
1212 for name, command in _complete_visible_commands(ctx, incomplete)
1213 if name not in ctx._protected_args
1214 )
1216 return results
1218 @t.overload
1219 def main(
1220 self,
1221 args: cabc.Sequence[str] | None = None,
1222 prog_name: str | None = None,
1223 complete_var: str | None = None,
1224 standalone_mode: t.Literal[True] = True,
1225 **extra: t.Any,
1226 ) -> t.NoReturn: ...
1228 @t.overload
1229 def main(
1230 self,
1231 args: cabc.Sequence[str] | None = None,
1232 prog_name: str | None = None,
1233 complete_var: str | None = None,
1234 standalone_mode: bool = ...,
1235 **extra: t.Any,
1236 ) -> t.Any: ...
1238 def main(
1239 self,
1240 args: cabc.Sequence[str] | None = None,
1241 prog_name: str | None = None,
1242 complete_var: str | None = None,
1243 standalone_mode: bool = True,
1244 windows_expand_args: bool = True,
1245 **extra: t.Any,
1246 ) -> t.Any:
1247 """This is the way to invoke a script with all the bells and
1248 whistles as a command line application. This will always terminate
1249 the application after a call. If this is not wanted, ``SystemExit``
1250 needs to be caught.
1252 This method is also available by directly calling the instance of
1253 a :class:`Command`.
1255 :param args: the arguments that should be used for parsing. If not
1256 provided, ``sys.argv[1:]`` is used.
1257 :param prog_name: the program name that should be used. By default
1258 the program name is constructed by taking the file
1259 name from ``sys.argv[0]``.
1260 :param complete_var: the environment variable that controls the
1261 bash completion support. The default is
1262 ``"_<prog_name>_COMPLETE"`` with prog_name in
1263 uppercase.
1264 :param standalone_mode: the default behavior is to invoke the script
1265 in standalone mode. Click will then
1266 handle exceptions and convert them into
1267 error messages and the function will never
1268 return but shut down the interpreter. If
1269 this is set to `False` they will be
1270 propagated to the caller and the return
1271 value of this function is the return value
1272 of :meth:`invoke`.
1273 :param windows_expand_args: Expand glob patterns, user dir, and
1274 env vars in command line args on Windows.
1275 :param extra: extra keyword arguments are forwarded to the context
1276 constructor. See :class:`Context` for more information.
1278 .. versionchanged:: 8.0.1
1279 Added the ``windows_expand_args`` parameter to allow
1280 disabling command line arg expansion on Windows.
1282 .. versionchanged:: 8.0
1283 When taking arguments from ``sys.argv`` on Windows, glob
1284 patterns, user dir, and env vars are expanded.
1286 .. versionchanged:: 3.0
1287 Added the ``standalone_mode`` parameter.
1288 """
1289 if args is None:
1290 args = sys.argv[1:]
1292 if os.name == "nt" and windows_expand_args:
1293 args = _expand_args(args)
1294 else:
1295 args = list(args)
1297 if prog_name is None:
1298 prog_name = _detect_program_name()
1300 # Process shell completion requests and exit early.
1301 self._main_shell_completion(extra, prog_name, complete_var)
1303 try:
1304 try:
1305 with self.make_context(prog_name, args, **extra) as ctx:
1306 rv = self.invoke(ctx)
1307 if not standalone_mode:
1308 return rv
1309 # it's not safe to `ctx.exit(rv)` here!
1310 # note that `rv` may actually contain data like "1" which
1311 # has obvious effects
1312 # more subtle case: `rv=[None, None]` can come out of
1313 # chained commands which all returned `None` -- so it's not
1314 # even always obvious that `rv` indicates success/failure
1315 # by its truthiness/falsiness
1316 ctx.exit()
1317 except (EOFError, KeyboardInterrupt) as e:
1318 echo(file=sys.stderr)
1319 raise Abort() from e
1320 except ClickException as e:
1321 if not standalone_mode:
1322 raise
1323 e.show()
1324 sys.exit(e.exit_code)
1325 except OSError as e:
1326 if e.errno == errno.EPIPE:
1327 sys.stdout = t.cast(t.TextIO, PacifyFlushWrapper(sys.stdout))
1328 sys.stderr = t.cast(t.TextIO, PacifyFlushWrapper(sys.stderr))
1329 sys.exit(1)
1330 else:
1331 raise
1332 except Exit as e:
1333 if standalone_mode:
1334 sys.exit(e.exit_code)
1335 else:
1336 # in non-standalone mode, return the exit code
1337 # note that this is only reached if `self.invoke` above raises
1338 # an Exit explicitly -- thus bypassing the check there which
1339 # would return its result
1340 # the results of non-standalone execution may therefore be
1341 # somewhat ambiguous: if there are codepaths which lead to
1342 # `ctx.exit(1)` and to `return 1`, the caller won't be able to
1343 # tell the difference between the two
1344 return e.exit_code
1345 except Abort:
1346 if not standalone_mode:
1347 raise
1348 echo(_("Aborted!"), file=sys.stderr)
1349 sys.exit(1)
1351 def _main_shell_completion(
1352 self,
1353 ctx_args: cabc.MutableMapping[str, t.Any],
1354 prog_name: str,
1355 complete_var: str | None = None,
1356 ) -> None:
1357 """Check if the shell is asking for tab completion, process
1358 that, then exit early. Called from :meth:`main` before the
1359 program is invoked.
1361 :param prog_name: Name of the executable in the shell.
1362 :param complete_var: Name of the environment variable that holds
1363 the completion instruction. Defaults to
1364 ``_{PROG_NAME}_COMPLETE``.
1366 .. versionchanged:: 8.2.0
1367 Dots (``.``) in ``prog_name`` are replaced with underscores (``_``).
1368 """
1369 if complete_var is None:
1370 complete_name = prog_name.replace("-", "_").replace(".", "_")
1371 complete_var = f"_{complete_name}_COMPLETE".upper()
1373 instruction = os.environ.get(complete_var)
1375 if not instruction:
1376 return
1378 from .shell_completion import shell_complete
1380 rv = shell_complete(self, ctx_args, prog_name, complete_var, instruction)
1381 sys.exit(rv)
1383 def __call__(self, *args: t.Any, **kwargs: t.Any) -> t.Any:
1384 """Alias for :meth:`main`."""
1385 return self.main(*args, **kwargs)
1388class _FakeSubclassCheck(type):
1389 def __subclasscheck__(cls, subclass: type) -> bool:
1390 return issubclass(subclass, cls.__bases__[0])
1392 def __instancecheck__(cls, instance: t.Any) -> bool:
1393 return isinstance(instance, cls.__bases__[0])
1396class _BaseCommand(Command, metaclass=_FakeSubclassCheck):
1397 """
1398 .. deprecated:: 8.2
1399 Will be removed in Click 9.0. Use ``Command`` instead.
1400 """
1403class Group(Command):
1404 """A group is a command that nests other commands (or more groups).
1406 :param name: The name of the group command.
1407 :param commands: Map names to :class:`Command` objects. Can be a list, which
1408 will use :attr:`Command.name` as the keys.
1409 :param invoke_without_command: Invoke the group's callback even if a
1410 subcommand is not given.
1411 :param no_args_is_help: If no arguments are given, show the group's help and
1412 exit. Defaults to the opposite of ``invoke_without_command``.
1413 :param subcommand_metavar: How to represent the subcommand argument in help.
1414 The default will represent whether ``chain`` is set or not.
1415 :param chain: Allow passing more than one subcommand argument. After parsing
1416 a command's arguments, if any arguments remain another command will be
1417 matched, and so on.
1418 :param result_callback: A function to call after the group's and
1419 subcommand's callbacks. The value returned by the subcommand is passed.
1420 If ``chain`` is enabled, the value will be a list of values returned by
1421 all the commands. If ``invoke_without_command`` is enabled, the value
1422 will be the value returned by the group's callback, or an empty list if
1423 ``chain`` is enabled.
1424 :param kwargs: Other arguments passed to :class:`Command`.
1426 .. versionchanged:: 8.2
1427 Merged with and replaces the ``MultiCommand`` base class.
1429 .. versionchanged:: 8.0
1430 The ``commands`` argument can be a list of command objects.
1431 """
1433 allow_extra_args = True
1434 allow_interspersed_args = False
1436 #: If set, this is used by the group's :meth:`command` decorator
1437 #: as the default :class:`Command` class. This is useful to make all
1438 #: subcommands use a custom command class.
1439 #:
1440 #: .. versionadded:: 8.0
1441 command_class: type[Command] | None = None
1443 #: If set, this is used by the group's :meth:`group` decorator
1444 #: as the default :class:`Group` class. This is useful to make all
1445 #: subgroups use a custom group class.
1446 #:
1447 #: If set to the special value :class:`type` (literally
1448 #: ``group_class = type``), this group's class will be used as the
1449 #: default class. This makes a custom group class continue to make
1450 #: custom groups.
1451 #:
1452 #: .. versionadded:: 8.0
1453 group_class: type[Group] | type[type] | None = None
1454 # Literal[type] isn't valid, so use Type[type]
1456 def __init__(
1457 self,
1458 name: str | None = None,
1459 commands: cabc.MutableMapping[str, Command]
1460 | cabc.Sequence[Command]
1461 | None = None,
1462 invoke_without_command: bool = False,
1463 no_args_is_help: bool | None = None,
1464 subcommand_metavar: str | None = None,
1465 chain: bool = False,
1466 result_callback: t.Callable[..., t.Any] | None = None,
1467 **kwargs: t.Any,
1468 ) -> None:
1469 super().__init__(name, **kwargs)
1471 if commands is None:
1472 commands = {}
1473 elif isinstance(commands, abc.Sequence):
1474 commands = {c.name: c for c in commands if c.name is not None}
1476 #: The registered subcommands by their exported names.
1477 self.commands: cabc.MutableMapping[str, Command] = commands
1479 if no_args_is_help is None:
1480 no_args_is_help = not invoke_without_command
1482 self.no_args_is_help = no_args_is_help
1483 self.invoke_without_command = invoke_without_command
1485 if subcommand_metavar is None:
1486 if chain:
1487 subcommand_metavar = "COMMAND1 [ARGS]... [COMMAND2 [ARGS]...]..."
1488 else:
1489 subcommand_metavar = "COMMAND [ARGS]..."
1491 self.subcommand_metavar = subcommand_metavar
1492 self.chain = chain
1493 # The result callback that is stored. This can be set or
1494 # overridden with the :func:`result_callback` decorator.
1495 self._result_callback = result_callback
1497 if self.chain:
1498 for param in self.params:
1499 if isinstance(param, Argument) and not param.required:
1500 raise RuntimeError(
1501 "A group in chain mode cannot have optional arguments."
1502 )
1504 def to_info_dict(self, ctx: Context) -> dict[str, t.Any]:
1505 info_dict = super().to_info_dict(ctx)
1506 commands = {}
1508 for name in self.list_commands(ctx):
1509 command = self.get_command(ctx, name)
1511 if command is None:
1512 continue
1514 sub_ctx = ctx._make_sub_context(command)
1516 with sub_ctx.scope(cleanup=False):
1517 commands[name] = command.to_info_dict(sub_ctx)
1519 info_dict.update(commands=commands, chain=self.chain)
1520 return info_dict
1522 def add_command(self, cmd: Command, name: str | None = None) -> None:
1523 """Registers another :class:`Command` with this group. If the name
1524 is not provided, the name of the command is used.
1525 """
1526 name = name or cmd.name
1527 if name is None:
1528 raise TypeError("Command has no name.")
1529 _check_nested_chain(self, name, cmd, register=True)
1530 self.commands[name] = cmd
1532 @t.overload
1533 def command(self, __func: t.Callable[..., t.Any]) -> Command: ...
1535 @t.overload
1536 def command(
1537 self, *args: t.Any, **kwargs: t.Any
1538 ) -> t.Callable[[t.Callable[..., t.Any]], Command]: ...
1540 def command(
1541 self, *args: t.Any, **kwargs: t.Any
1542 ) -> t.Callable[[t.Callable[..., t.Any]], Command] | Command:
1543 """A shortcut decorator for declaring and attaching a command to
1544 the group. This takes the same arguments as :func:`command` and
1545 immediately registers the created command with this group by
1546 calling :meth:`add_command`.
1548 To customize the command class used, set the
1549 :attr:`command_class` attribute.
1551 .. versionchanged:: 8.1
1552 This decorator can be applied without parentheses.
1554 .. versionchanged:: 8.0
1555 Added the :attr:`command_class` attribute.
1556 """
1557 from .decorators import command
1559 func: t.Callable[..., t.Any] | None = None
1561 if args and callable(args[0]):
1562 assert (
1563 len(args) == 1 and not kwargs
1564 ), "Use 'command(**kwargs)(callable)' to provide arguments."
1565 (func,) = args
1566 args = ()
1568 if self.command_class and kwargs.get("cls") is None:
1569 kwargs["cls"] = self.command_class
1571 def decorator(f: t.Callable[..., t.Any]) -> Command:
1572 cmd: Command = command(*args, **kwargs)(f)
1573 self.add_command(cmd)
1574 return cmd
1576 if func is not None:
1577 return decorator(func)
1579 return decorator
1581 @t.overload
1582 def group(self, __func: t.Callable[..., t.Any]) -> Group: ...
1584 @t.overload
1585 def group(
1586 self, *args: t.Any, **kwargs: t.Any
1587 ) -> t.Callable[[t.Callable[..., t.Any]], Group]: ...
1589 def group(
1590 self, *args: t.Any, **kwargs: t.Any
1591 ) -> t.Callable[[t.Callable[..., t.Any]], Group] | Group:
1592 """A shortcut decorator for declaring and attaching a group to
1593 the group. This takes the same arguments as :func:`group` and
1594 immediately registers the created group with this group by
1595 calling :meth:`add_command`.
1597 To customize the group class used, set the :attr:`group_class`
1598 attribute.
1600 .. versionchanged:: 8.1
1601 This decorator can be applied without parentheses.
1603 .. versionchanged:: 8.0
1604 Added the :attr:`group_class` attribute.
1605 """
1606 from .decorators import group
1608 func: t.Callable[..., t.Any] | None = None
1610 if args and callable(args[0]):
1611 assert (
1612 len(args) == 1 and not kwargs
1613 ), "Use 'group(**kwargs)(callable)' to provide arguments."
1614 (func,) = args
1615 args = ()
1617 if self.group_class is not None and kwargs.get("cls") is None:
1618 if self.group_class is type:
1619 kwargs["cls"] = type(self)
1620 else:
1621 kwargs["cls"] = self.group_class
1623 def decorator(f: t.Callable[..., t.Any]) -> Group:
1624 cmd: Group = group(*args, **kwargs)(f)
1625 self.add_command(cmd)
1626 return cmd
1628 if func is not None:
1629 return decorator(func)
1631 return decorator
1633 def result_callback(self, replace: bool = False) -> t.Callable[[F], F]:
1634 """Adds a result callback to the command. By default if a
1635 result callback is already registered this will chain them but
1636 this can be disabled with the `replace` parameter. The result
1637 callback is invoked with the return value of the subcommand
1638 (or the list of return values from all subcommands if chaining
1639 is enabled) as well as the parameters as they would be passed
1640 to the main callback.
1642 Example::
1644 @click.group()
1645 @click.option('-i', '--input', default=23)
1646 def cli(input):
1647 return 42
1649 @cli.result_callback()
1650 def process_result(result, input):
1651 return result + input
1653 :param replace: if set to `True` an already existing result
1654 callback will be removed.
1656 .. versionchanged:: 8.0
1657 Renamed from ``resultcallback``.
1659 .. versionadded:: 3.0
1660 """
1662 def decorator(f: F) -> F:
1663 old_callback = self._result_callback
1665 if old_callback is None or replace:
1666 self._result_callback = f
1667 return f
1669 def function(value: t.Any, /, *args: t.Any, **kwargs: t.Any) -> t.Any:
1670 inner = old_callback(value, *args, **kwargs)
1671 return f(inner, *args, **kwargs)
1673 self._result_callback = rv = update_wrapper(t.cast(F, function), f)
1674 return rv # type: ignore[return-value]
1676 return decorator
1678 def get_command(self, ctx: Context, cmd_name: str) -> Command | None:
1679 """Given a context and a command name, this returns a :class:`Command`
1680 object if it exists or returns ``None``.
1681 """
1682 return self.commands.get(cmd_name)
1684 def list_commands(self, ctx: Context) -> list[str]:
1685 """Returns a list of subcommand names in the order they should appear."""
1686 return sorted(self.commands)
1688 def collect_usage_pieces(self, ctx: Context) -> list[str]:
1689 rv = super().collect_usage_pieces(ctx)
1690 rv.append(self.subcommand_metavar)
1691 return rv
1693 def format_options(self, ctx: Context, formatter: HelpFormatter) -> None:
1694 super().format_options(ctx, formatter)
1695 self.format_commands(ctx, formatter)
1697 def format_commands(self, ctx: Context, formatter: HelpFormatter) -> None:
1698 """Extra format methods for multi methods that adds all the commands
1699 after the options.
1700 """
1701 commands = []
1702 for subcommand in self.list_commands(ctx):
1703 cmd = self.get_command(ctx, subcommand)
1704 # What is this, the tool lied about a command. Ignore it
1705 if cmd is None:
1706 continue
1707 if cmd.hidden:
1708 continue
1710 commands.append((subcommand, cmd))
1712 # allow for 3 times the default spacing
1713 if len(commands):
1714 limit = formatter.width - 6 - max(len(cmd[0]) for cmd in commands)
1716 rows = []
1717 for subcommand, cmd in commands:
1718 help = cmd.get_short_help_str(limit)
1719 rows.append((subcommand, help))
1721 if rows:
1722 with formatter.section(_("Commands")):
1723 formatter.write_dl(rows)
1725 def parse_args(self, ctx: Context, args: list[str]) -> list[str]:
1726 if not args and self.no_args_is_help and not ctx.resilient_parsing:
1727 echo(ctx.get_help(), color=ctx.color)
1728 ctx.exit()
1730 rest = super().parse_args(ctx, args)
1732 if self.chain:
1733 ctx._protected_args = rest
1734 ctx.args = []
1735 elif rest:
1736 ctx._protected_args, ctx.args = rest[:1], rest[1:]
1738 return ctx.args
1740 def invoke(self, ctx: Context) -> t.Any:
1741 def _process_result(value: t.Any) -> t.Any:
1742 if self._result_callback is not None:
1743 value = ctx.invoke(self._result_callback, value, **ctx.params)
1744 return value
1746 if not ctx._protected_args:
1747 if self.invoke_without_command:
1748 # No subcommand was invoked, so the result callback is
1749 # invoked with the group return value for regular
1750 # groups, or an empty list for chained groups.
1751 with ctx:
1752 rv = super().invoke(ctx)
1753 return _process_result([] if self.chain else rv)
1754 ctx.fail(_("Missing command."))
1756 # Fetch args back out
1757 args = [*ctx._protected_args, *ctx.args]
1758 ctx.args = []
1759 ctx._protected_args = []
1761 # If we're not in chain mode, we only allow the invocation of a
1762 # single command but we also inform the current context about the
1763 # name of the command to invoke.
1764 if not self.chain:
1765 # Make sure the context is entered so we do not clean up
1766 # resources until the result processor has worked.
1767 with ctx:
1768 cmd_name, cmd, args = self.resolve_command(ctx, args)
1769 assert cmd is not None
1770 ctx.invoked_subcommand = cmd_name
1771 super().invoke(ctx)
1772 sub_ctx = cmd.make_context(cmd_name, args, parent=ctx)
1773 with sub_ctx:
1774 return _process_result(sub_ctx.command.invoke(sub_ctx))
1776 # In chain mode we create the contexts step by step, but after the
1777 # base command has been invoked. Because at that point we do not
1778 # know the subcommands yet, the invoked subcommand attribute is
1779 # set to ``*`` to inform the command that subcommands are executed
1780 # but nothing else.
1781 with ctx:
1782 ctx.invoked_subcommand = "*" if args else None
1783 super().invoke(ctx)
1785 # Otherwise we make every single context and invoke them in a
1786 # chain. In that case the return value to the result processor
1787 # is the list of all invoked subcommand's results.
1788 contexts = []
1789 while args:
1790 cmd_name, cmd, args = self.resolve_command(ctx, args)
1791 assert cmd is not None
1792 sub_ctx = cmd.make_context(
1793 cmd_name,
1794 args,
1795 parent=ctx,
1796 allow_extra_args=True,
1797 allow_interspersed_args=False,
1798 )
1799 contexts.append(sub_ctx)
1800 args, sub_ctx.args = sub_ctx.args, []
1802 rv = []
1803 for sub_ctx in contexts:
1804 with sub_ctx:
1805 rv.append(sub_ctx.command.invoke(sub_ctx))
1806 return _process_result(rv)
1808 def resolve_command(
1809 self, ctx: Context, args: list[str]
1810 ) -> tuple[str | None, Command | None, list[str]]:
1811 cmd_name = make_str(args[0])
1812 original_cmd_name = cmd_name
1814 # Get the command
1815 cmd = self.get_command(ctx, cmd_name)
1817 # If we can't find the command but there is a normalization
1818 # function available, we try with that one.
1819 if cmd is None and ctx.token_normalize_func is not None:
1820 cmd_name = ctx.token_normalize_func(cmd_name)
1821 cmd = self.get_command(ctx, cmd_name)
1823 # If we don't find the command we want to show an error message
1824 # to the user that it was not provided. However, there is
1825 # something else we should do: if the first argument looks like
1826 # an option we want to kick off parsing again for arguments to
1827 # resolve things like --help which now should go to the main
1828 # place.
1829 if cmd is None and not ctx.resilient_parsing:
1830 if _split_opt(cmd_name)[0]:
1831 self.parse_args(ctx, ctx.args)
1832 ctx.fail(_("No such command {name!r}.").format(name=original_cmd_name))
1833 return cmd_name if cmd else None, cmd, args[1:]
1835 def shell_complete(self, ctx: Context, incomplete: str) -> list[CompletionItem]:
1836 """Return a list of completions for the incomplete value. Looks
1837 at the names of options, subcommands, and chained
1838 multi-commands.
1840 :param ctx: Invocation context for this command.
1841 :param incomplete: Value being completed. May be empty.
1843 .. versionadded:: 8.0
1844 """
1845 from click.shell_completion import CompletionItem
1847 results = [
1848 CompletionItem(name, help=command.get_short_help_str())
1849 for name, command in _complete_visible_commands(ctx, incomplete)
1850 ]
1851 results.extend(super().shell_complete(ctx, incomplete))
1852 return results
1855class _MultiCommand(Group, metaclass=_FakeSubclassCheck):
1856 """
1857 .. deprecated:: 8.2
1858 Will be removed in Click 9.0. Use ``Group`` instead.
1859 """
1862class CommandCollection(Group):
1863 """A :class:`Group` that looks up subcommands on other groups. If a command
1864 is not found on this group, each registered source is checked in order.
1865 Parameters on a source are not added to this group, and a source's callback
1866 is not invoked when invoking its commands. In other words, this "flattens"
1867 commands in many groups into this one group.
1869 :param name: The name of the group command.
1870 :param sources: A list of :class:`Group` objects to look up commands from.
1871 :param kwargs: Other arguments passed to :class:`Group`.
1873 .. versionchanged:: 8.2
1874 This is a subclass of ``Group``. Commands are looked up first on this
1875 group, then each of its sources.
1876 """
1878 def __init__(
1879 self,
1880 name: str | None = None,
1881 sources: list[Group] | None = None,
1882 **kwargs: t.Any,
1883 ) -> None:
1884 super().__init__(name, **kwargs)
1885 #: The list of registered groups.
1886 self.sources: list[Group] = sources or []
1888 def add_source(self, group: Group) -> None:
1889 """Add a group as a source of commands."""
1890 self.sources.append(group)
1892 def get_command(self, ctx: Context, cmd_name: str) -> Command | None:
1893 rv = super().get_command(ctx, cmd_name)
1895 if rv is not None:
1896 return rv
1898 for source in self.sources:
1899 rv = source.get_command(ctx, cmd_name)
1901 if rv is not None:
1902 if self.chain:
1903 _check_nested_chain(self, cmd_name, rv)
1905 return rv
1907 return None
1909 def list_commands(self, ctx: Context) -> list[str]:
1910 rv: set[str] = set(super().list_commands(ctx))
1912 for source in self.sources:
1913 rv.update(source.list_commands(ctx))
1915 return sorted(rv)
1918def _check_iter(value: t.Any) -> cabc.Iterator[t.Any]:
1919 """Check if the value is iterable but not a string. Raises a type
1920 error, or return an iterator over the value.
1921 """
1922 if isinstance(value, str):
1923 raise TypeError
1925 return iter(value)
1928class Parameter:
1929 r"""A parameter to a command comes in two versions: they are either
1930 :class:`Option`\s or :class:`Argument`\s. Other subclasses are currently
1931 not supported by design as some of the internals for parsing are
1932 intentionally not finalized.
1934 Some settings are supported by both options and arguments.
1936 :param param_decls: the parameter declarations for this option or
1937 argument. This is a list of flags or argument
1938 names.
1939 :param type: the type that should be used. Either a :class:`ParamType`
1940 or a Python type. The latter is converted into the former
1941 automatically if supported.
1942 :param required: controls if this is optional or not.
1943 :param default: the default value if omitted. This can also be a callable,
1944 in which case it's invoked when the default is needed
1945 without any arguments.
1946 :param callback: A function to further process or validate the value
1947 after type conversion. It is called as ``f(ctx, param, value)``
1948 and must return the value. It is called for all sources,
1949 including prompts.
1950 :param nargs: the number of arguments to match. If not ``1`` the return
1951 value is a tuple instead of single value. The default for
1952 nargs is ``1`` (except if the type is a tuple, then it's
1953 the arity of the tuple). If ``nargs=-1``, all remaining
1954 parameters are collected.
1955 :param metavar: how the value is represented in the help page.
1956 :param expose_value: if this is `True` then the value is passed onwards
1957 to the command callback and stored on the context,
1958 otherwise it's skipped.
1959 :param is_eager: eager values are processed before non eager ones. This
1960 should not be set for arguments or it will inverse the
1961 order of processing.
1962 :param envvar: a string or list of strings that are environment variables
1963 that should be checked.
1964 :param shell_complete: A function that returns custom shell
1965 completions. Used instead of the param's type completion if
1966 given. Takes ``ctx, param, incomplete`` and must return a list
1967 of :class:`~click.shell_completion.CompletionItem` or a list of
1968 strings.
1970 .. versionchanged:: 8.0
1971 ``process_value`` validates required parameters and bounded
1972 ``nargs``, and invokes the parameter callback before returning
1973 the value. This allows the callback to validate prompts.
1974 ``full_process_value`` is removed.
1976 .. versionchanged:: 8.0
1977 ``autocompletion`` is renamed to ``shell_complete`` and has new
1978 semantics described above. The old name is deprecated and will
1979 be removed in 8.1, until then it will be wrapped to match the
1980 new requirements.
1982 .. versionchanged:: 8.0
1983 For ``multiple=True, nargs>1``, the default must be a list of
1984 tuples.
1986 .. versionchanged:: 8.0
1987 Setting a default is no longer required for ``nargs>1``, it will
1988 default to ``None``. ``multiple=True`` or ``nargs=-1`` will
1989 default to ``()``.
1991 .. versionchanged:: 7.1
1992 Empty environment variables are ignored rather than taking the
1993 empty string value. This makes it possible for scripts to clear
1994 variables if they can't unset them.
1996 .. versionchanged:: 2.0
1997 Changed signature for parameter callback to also be passed the
1998 parameter. The old callback format will still work, but it will
1999 raise a warning to give you a chance to migrate the code easier.
2000 """
2002 param_type_name = "parameter"
2004 def __init__(
2005 self,
2006 param_decls: cabc.Sequence[str] | None = None,
2007 type: types.ParamType | t.Any | None = None,
2008 required: bool = False,
2009 default: t.Any | t.Callable[[], t.Any] | None = None,
2010 callback: t.Callable[[Context, Parameter, t.Any], t.Any] | None = None,
2011 nargs: int | None = None,
2012 multiple: bool = False,
2013 metavar: str | None = None,
2014 expose_value: bool = True,
2015 is_eager: bool = False,
2016 envvar: str | cabc.Sequence[str] | None = None,
2017 shell_complete: t.Callable[
2018 [Context, Parameter, str], list[CompletionItem] | list[str]
2019 ]
2020 | None = None,
2021 ) -> None:
2022 self.name: str | None
2023 self.opts: list[str]
2024 self.secondary_opts: list[str]
2025 self.name, self.opts, self.secondary_opts = self._parse_decls(
2026 param_decls or (), expose_value
2027 )
2028 self.type: types.ParamType = types.convert_type(type, default)
2030 # Default nargs to what the type tells us if we have that
2031 # information available.
2032 if nargs is None:
2033 if self.type.is_composite:
2034 nargs = self.type.arity
2035 else:
2036 nargs = 1
2038 self.required = required
2039 self.callback = callback
2040 self.nargs = nargs
2041 self.multiple = multiple
2042 self.expose_value = expose_value
2043 self.default = default
2044 self.is_eager = is_eager
2045 self.metavar = metavar
2046 self.envvar = envvar
2047 self._custom_shell_complete = shell_complete
2049 if __debug__:
2050 if self.type.is_composite and nargs != self.type.arity:
2051 raise ValueError(
2052 f"'nargs' must be {self.type.arity} (or None) for"
2053 f" type {self.type!r}, but it was {nargs}."
2054 )
2056 # Skip no default or callable default.
2057 check_default = default if not callable(default) else None
2059 if check_default is not None:
2060 if multiple:
2061 try:
2062 # Only check the first value against nargs.
2063 check_default = next(_check_iter(check_default), None)
2064 except TypeError:
2065 raise ValueError(
2066 "'default' must be a list when 'multiple' is true."
2067 ) from None
2069 # Can be None for multiple with empty default.
2070 if nargs != 1 and check_default is not None:
2071 try:
2072 _check_iter(check_default)
2073 except TypeError:
2074 if multiple:
2075 message = (
2076 "'default' must be a list of lists when 'multiple' is"
2077 " true and 'nargs' != 1."
2078 )
2079 else:
2080 message = "'default' must be a list when 'nargs' != 1."
2082 raise ValueError(message) from None
2084 if nargs > 1 and len(check_default) != nargs:
2085 subject = "item length" if multiple else "length"
2086 raise ValueError(
2087 f"'default' {subject} must match nargs={nargs}."
2088 )
2090 def to_info_dict(self) -> dict[str, t.Any]:
2091 """Gather information that could be useful for a tool generating
2092 user-facing documentation.
2094 Use :meth:`click.Context.to_info_dict` to traverse the entire
2095 CLI structure.
2097 .. versionadded:: 8.0
2098 """
2099 return {
2100 "name": self.name,
2101 "param_type_name": self.param_type_name,
2102 "opts": self.opts,
2103 "secondary_opts": self.secondary_opts,
2104 "type": self.type.to_info_dict(),
2105 "required": self.required,
2106 "nargs": self.nargs,
2107 "multiple": self.multiple,
2108 "default": self.default,
2109 "envvar": self.envvar,
2110 }
2112 def __repr__(self) -> str:
2113 return f"<{self.__class__.__name__} {self.name}>"
2115 def _parse_decls(
2116 self, decls: cabc.Sequence[str], expose_value: bool
2117 ) -> tuple[str | None, list[str], list[str]]:
2118 raise NotImplementedError()
2120 @property
2121 def human_readable_name(self) -> str:
2122 """Returns the human readable name of this parameter. This is the
2123 same as the name for options, but the metavar for arguments.
2124 """
2125 return self.name # type: ignore
2127 def make_metavar(self) -> str:
2128 if self.metavar is not None:
2129 return self.metavar
2131 metavar = self.type.get_metavar(self)
2133 if metavar is None:
2134 metavar = self.type.name.upper()
2136 if self.nargs != 1:
2137 metavar += "..."
2139 return metavar
2141 @t.overload
2142 def get_default(
2143 self, ctx: Context, call: t.Literal[True] = True
2144 ) -> t.Any | None: ...
2146 @t.overload
2147 def get_default(
2148 self, ctx: Context, call: bool = ...
2149 ) -> t.Any | t.Callable[[], t.Any] | None: ...
2151 def get_default(
2152 self, ctx: Context, call: bool = True
2153 ) -> t.Any | t.Callable[[], t.Any] | None:
2154 """Get the default for the parameter. Tries
2155 :meth:`Context.lookup_default` first, then the local default.
2157 :param ctx: Current context.
2158 :param call: If the default is a callable, call it. Disable to
2159 return the callable instead.
2161 .. versionchanged:: 8.0.2
2162 Type casting is no longer performed when getting a default.
2164 .. versionchanged:: 8.0.1
2165 Type casting can fail in resilient parsing mode. Invalid
2166 defaults will not prevent showing help text.
2168 .. versionchanged:: 8.0
2169 Looks at ``ctx.default_map`` first.
2171 .. versionchanged:: 8.0
2172 Added the ``call`` parameter.
2173 """
2174 value = ctx.lookup_default(self.name, call=False) # type: ignore
2176 if value is None:
2177 value = self.default
2179 if call and callable(value):
2180 value = value()
2182 return value
2184 def add_to_parser(self, parser: _OptionParser, ctx: Context) -> None:
2185 raise NotImplementedError()
2187 def consume_value(
2188 self, ctx: Context, opts: cabc.Mapping[str, t.Any]
2189 ) -> tuple[t.Any, ParameterSource]:
2190 value = opts.get(self.name) # type: ignore
2191 source = ParameterSource.COMMANDLINE
2193 if value is None:
2194 value = self.value_from_envvar(ctx)
2195 source = ParameterSource.ENVIRONMENT
2197 if value is None:
2198 value = ctx.lookup_default(self.name) # type: ignore
2199 source = ParameterSource.DEFAULT_MAP
2201 if value is None:
2202 value = self.get_default(ctx)
2203 source = ParameterSource.DEFAULT
2205 return value, source
2207 def type_cast_value(self, ctx: Context, value: t.Any) -> t.Any:
2208 """Convert and validate a value against the option's
2209 :attr:`type`, :attr:`multiple`, and :attr:`nargs`.
2210 """
2211 if value is None:
2212 return () if self.multiple or self.nargs == -1 else None
2214 def check_iter(value: t.Any) -> cabc.Iterator[t.Any]:
2215 try:
2216 return _check_iter(value)
2217 except TypeError:
2218 # This should only happen when passing in args manually,
2219 # the parser should construct an iterable when parsing
2220 # the command line.
2221 raise BadParameter(
2222 _("Value must be an iterable."), ctx=ctx, param=self
2223 ) from None
2225 if self.nargs == 1 or self.type.is_composite:
2227 def convert(value: t.Any) -> t.Any:
2228 return self.type(value, param=self, ctx=ctx)
2230 elif self.nargs == -1:
2232 def convert(value: t.Any) -> t.Any: # tuple[t.Any, ...]
2233 return tuple(self.type(x, self, ctx) for x in check_iter(value))
2235 else: # nargs > 1
2237 def convert(value: t.Any) -> t.Any: # tuple[t.Any, ...]
2238 value = tuple(check_iter(value))
2240 if len(value) != self.nargs:
2241 raise BadParameter(
2242 ngettext(
2243 "Takes {nargs} values but 1 was given.",
2244 "Takes {nargs} values but {len} were given.",
2245 len(value),
2246 ).format(nargs=self.nargs, len=len(value)),
2247 ctx=ctx,
2248 param=self,
2249 )
2251 return tuple(self.type(x, self, ctx) for x in value)
2253 if self.multiple:
2254 return tuple(convert(x) for x in check_iter(value))
2256 return convert(value)
2258 def value_is_missing(self, value: t.Any) -> bool:
2259 if value is None:
2260 return True
2262 if (self.nargs != 1 or self.multiple) and value == ():
2263 return True
2265 return False
2267 def process_value(self, ctx: Context, value: t.Any) -> t.Any:
2268 value = self.type_cast_value(ctx, value)
2270 if self.required and self.value_is_missing(value):
2271 raise MissingParameter(ctx=ctx, param=self)
2273 if self.callback is not None:
2274 value = self.callback(ctx, self, value)
2276 return value
2278 def resolve_envvar_value(self, ctx: Context) -> str | None:
2279 if self.envvar is None:
2280 return None
2282 if isinstance(self.envvar, str):
2283 rv = os.environ.get(self.envvar)
2285 if rv:
2286 return rv
2287 else:
2288 for envvar in self.envvar:
2289 rv = os.environ.get(envvar)
2291 if rv:
2292 return rv
2294 return None
2296 def value_from_envvar(self, ctx: Context) -> t.Any | None:
2297 rv: t.Any | None = self.resolve_envvar_value(ctx)
2299 if rv is not None and self.nargs != 1:
2300 rv = self.type.split_envvar_value(rv)
2302 return rv
2304 def handle_parse_result(
2305 self, ctx: Context, opts: cabc.Mapping[str, t.Any], args: list[str]
2306 ) -> tuple[t.Any, list[str]]:
2307 with augment_usage_errors(ctx, param=self):
2308 value, source = self.consume_value(ctx, opts)
2309 ctx.set_parameter_source(self.name, source) # type: ignore
2311 try:
2312 value = self.process_value(ctx, value)
2313 except Exception:
2314 if not ctx.resilient_parsing:
2315 raise
2317 value = None
2319 if self.expose_value:
2320 ctx.params[self.name] = value # type: ignore
2322 return value, args
2324 def get_help_record(self, ctx: Context) -> tuple[str, str] | None:
2325 pass
2327 def get_usage_pieces(self, ctx: Context) -> list[str]:
2328 return []
2330 def get_error_hint(self, ctx: Context) -> str:
2331 """Get a stringified version of the param for use in error messages to
2332 indicate which param caused the error.
2333 """
2334 hint_list = self.opts or [self.human_readable_name]
2335 return " / ".join(f"'{x}'" for x in hint_list)
2337 def shell_complete(self, ctx: Context, incomplete: str) -> list[CompletionItem]:
2338 """Return a list of completions for the incomplete value. If a
2339 ``shell_complete`` function was given during init, it is used.
2340 Otherwise, the :attr:`type`
2341 :meth:`~click.types.ParamType.shell_complete` function is used.
2343 :param ctx: Invocation context for this command.
2344 :param incomplete: Value being completed. May be empty.
2346 .. versionadded:: 8.0
2347 """
2348 if self._custom_shell_complete is not None:
2349 results = self._custom_shell_complete(ctx, self, incomplete)
2351 if results and isinstance(results[0], str):
2352 from click.shell_completion import CompletionItem
2354 results = [CompletionItem(c) for c in results]
2356 return t.cast("list[CompletionItem]", results)
2358 return self.type.shell_complete(ctx, self, incomplete)
2361class Option(Parameter):
2362 """Options are usually optional values on the command line and
2363 have some extra features that arguments don't have.
2365 All other parameters are passed onwards to the parameter constructor.
2367 :param show_default: Show the default value for this option in its
2368 help text. Values are not shown by default, unless
2369 :attr:`Context.show_default` is ``True``. If this value is a
2370 string, it shows that string in parentheses instead of the
2371 actual value. This is particularly useful for dynamic options.
2372 For single option boolean flags, the default remains hidden if
2373 its value is ``False``.
2374 :param show_envvar: Controls if an environment variable should be
2375 shown on the help page. Normally, environment variables are not
2376 shown.
2377 :param prompt: If set to ``True`` or a non empty string then the
2378 user will be prompted for input. If set to ``True`` the prompt
2379 will be the option name capitalized.
2380 :param confirmation_prompt: Prompt a second time to confirm the
2381 value if it was prompted for. Can be set to a string instead of
2382 ``True`` to customize the message.
2383 :param prompt_required: If set to ``False``, the user will be
2384 prompted for input only when the option was specified as a flag
2385 without a value.
2386 :param hide_input: If this is ``True`` then the input on the prompt
2387 will be hidden from the user. This is useful for password input.
2388 :param is_flag: forces this option to act as a flag. The default is
2389 auto detection.
2390 :param flag_value: which value should be used for this flag if it's
2391 enabled. This is set to a boolean automatically if
2392 the option string contains a slash to mark two options.
2393 :param multiple: if this is set to `True` then the argument is accepted
2394 multiple times and recorded. This is similar to ``nargs``
2395 in how it works but supports arbitrary number of
2396 arguments.
2397 :param count: this flag makes an option increment an integer.
2398 :param allow_from_autoenv: if this is enabled then the value of this
2399 parameter will be pulled from an environment
2400 variable in case a prefix is defined on the
2401 context.
2402 :param help: the help string.
2403 :param hidden: hide this option from help outputs.
2404 :param attrs: Other command arguments described in :class:`Parameter`.
2406 .. versionchanged:: 8.1.0
2407 Help text indentation is cleaned here instead of only in the
2408 ``@option`` decorator.
2410 .. versionchanged:: 8.1.0
2411 The ``show_default`` parameter overrides
2412 ``Context.show_default``.
2414 .. versionchanged:: 8.1.0
2415 The default of a single option boolean flag is not shown if the
2416 default value is ``False``.
2418 .. versionchanged:: 8.0.1
2419 ``type`` is detected from ``flag_value`` if given.
2420 """
2422 param_type_name = "option"
2424 def __init__(
2425 self,
2426 param_decls: cabc.Sequence[str] | None = None,
2427 show_default: bool | str | None = None,
2428 prompt: bool | str = False,
2429 confirmation_prompt: bool | str = False,
2430 prompt_required: bool = True,
2431 hide_input: bool = False,
2432 is_flag: bool | None = None,
2433 flag_value: t.Any | None = None,
2434 multiple: bool = False,
2435 count: bool = False,
2436 allow_from_autoenv: bool = True,
2437 type: types.ParamType | t.Any | None = None,
2438 help: str | None = None,
2439 hidden: bool = False,
2440 show_choices: bool = True,
2441 show_envvar: bool = False,
2442 **attrs: t.Any,
2443 ) -> None:
2444 if help:
2445 help = inspect.cleandoc(help)
2447 default_is_missing = "default" not in attrs
2448 super().__init__(param_decls, type=type, multiple=multiple, **attrs)
2450 if prompt is True:
2451 if self.name is None:
2452 raise TypeError("'name' is required with 'prompt=True'.")
2454 prompt_text: str | None = self.name.replace("_", " ").capitalize()
2455 elif prompt is False:
2456 prompt_text = None
2457 else:
2458 prompt_text = prompt
2460 self.prompt = prompt_text
2461 self.confirmation_prompt = confirmation_prompt
2462 self.prompt_required = prompt_required
2463 self.hide_input = hide_input
2464 self.hidden = hidden
2466 # If prompt is enabled but not required, then the option can be
2467 # used as a flag to indicate using prompt or flag_value.
2468 self._flag_needs_value = self.prompt is not None and not self.prompt_required
2470 if is_flag is None:
2471 if flag_value is not None:
2472 # Implicitly a flag because flag_value was set.
2473 is_flag = True
2474 elif self._flag_needs_value:
2475 # Not a flag, but when used as a flag it shows a prompt.
2476 is_flag = False
2477 else:
2478 # Implicitly a flag because flag options were given.
2479 is_flag = bool(self.secondary_opts)
2480 elif is_flag is False and not self._flag_needs_value:
2481 # Not a flag, and prompt is not enabled, can be used as a
2482 # flag if flag_value is set.
2483 self._flag_needs_value = flag_value is not None
2485 self.default: t.Any | t.Callable[[], t.Any]
2487 if is_flag and default_is_missing and not self.required:
2488 if multiple:
2489 self.default = ()
2490 else:
2491 self.default = False
2493 if flag_value is None:
2494 flag_value = not self.default
2496 self.type: types.ParamType
2497 if is_flag and type is None:
2498 # Re-guess the type from the flag value instead of the
2499 # default.
2500 self.type = types.convert_type(None, flag_value)
2502 self.is_flag: bool = is_flag
2503 self.is_bool_flag: bool = is_flag and isinstance(self.type, types.BoolParamType)
2504 self.flag_value: t.Any = flag_value
2506 # Counting
2507 self.count = count
2508 if count:
2509 if type is None:
2510 self.type = types.IntRange(min=0)
2511 if default_is_missing:
2512 self.default = 0
2514 self.allow_from_autoenv = allow_from_autoenv
2515 self.help = help
2516 self.show_default = show_default
2517 self.show_choices = show_choices
2518 self.show_envvar = show_envvar
2520 if __debug__:
2521 if self.nargs == -1:
2522 raise TypeError("nargs=-1 is not supported for options.")
2524 if self.prompt and self.is_flag and not self.is_bool_flag:
2525 raise TypeError("'prompt' is not valid for non-boolean flag.")
2527 if not self.is_bool_flag and self.secondary_opts:
2528 raise TypeError("Secondary flag is not valid for non-boolean flag.")
2530 if self.is_bool_flag and self.hide_input and self.prompt is not None:
2531 raise TypeError(
2532 "'prompt' with 'hide_input' is not valid for boolean flag."
2533 )
2535 if self.count:
2536 if self.multiple:
2537 raise TypeError("'count' is not valid with 'multiple'.")
2539 if self.is_flag:
2540 raise TypeError("'count' is not valid with 'is_flag'.")
2542 def to_info_dict(self) -> dict[str, t.Any]:
2543 info_dict = super().to_info_dict()
2544 info_dict.update(
2545 help=self.help,
2546 prompt=self.prompt,
2547 is_flag=self.is_flag,
2548 flag_value=self.flag_value,
2549 count=self.count,
2550 hidden=self.hidden,
2551 )
2552 return info_dict
2554 def _parse_decls(
2555 self, decls: cabc.Sequence[str], expose_value: bool
2556 ) -> tuple[str | None, list[str], list[str]]:
2557 opts = []
2558 secondary_opts = []
2559 name = None
2560 possible_names = []
2562 for decl in decls:
2563 if decl.isidentifier():
2564 if name is not None:
2565 raise TypeError(f"Name '{name}' defined twice")
2566 name = decl
2567 else:
2568 split_char = ";" if decl[:1] == "/" else "/"
2569 if split_char in decl:
2570 first, second = decl.split(split_char, 1)
2571 first = first.rstrip()
2572 if first:
2573 possible_names.append(_split_opt(first))
2574 opts.append(first)
2575 second = second.lstrip()
2576 if second:
2577 secondary_opts.append(second.lstrip())
2578 if first == second:
2579 raise ValueError(
2580 f"Boolean option {decl!r} cannot use the"
2581 " same flag for true/false."
2582 )
2583 else:
2584 possible_names.append(_split_opt(decl))
2585 opts.append(decl)
2587 if name is None and possible_names:
2588 possible_names.sort(key=lambda x: -len(x[0])) # group long options first
2589 name = possible_names[0][1].replace("-", "_").lower()
2590 if not name.isidentifier():
2591 name = None
2593 if name is None:
2594 if not expose_value:
2595 return None, opts, secondary_opts
2596 raise TypeError("Could not determine name for option")
2598 if not opts and not secondary_opts:
2599 raise TypeError(
2600 f"No options defined but a name was passed ({name})."
2601 " Did you mean to declare an argument instead? Did"
2602 f" you mean to pass '--{name}'?"
2603 )
2605 return name, opts, secondary_opts
2607 def add_to_parser(self, parser: _OptionParser, ctx: Context) -> None:
2608 if self.multiple:
2609 action = "append"
2610 elif self.count:
2611 action = "count"
2612 else:
2613 action = "store"
2615 if self.is_flag:
2616 action = f"{action}_const"
2618 if self.is_bool_flag and self.secondary_opts:
2619 parser.add_option(
2620 obj=self, opts=self.opts, dest=self.name, action=action, const=True
2621 )
2622 parser.add_option(
2623 obj=self,
2624 opts=self.secondary_opts,
2625 dest=self.name,
2626 action=action,
2627 const=False,
2628 )
2629 else:
2630 parser.add_option(
2631 obj=self,
2632 opts=self.opts,
2633 dest=self.name,
2634 action=action,
2635 const=self.flag_value,
2636 )
2637 else:
2638 parser.add_option(
2639 obj=self,
2640 opts=self.opts,
2641 dest=self.name,
2642 action=action,
2643 nargs=self.nargs,
2644 )
2646 def get_help_record(self, ctx: Context) -> tuple[str, str] | None:
2647 if self.hidden:
2648 return None
2650 any_prefix_is_slash = False
2652 def _write_opts(opts: cabc.Sequence[str]) -> str:
2653 nonlocal any_prefix_is_slash
2655 rv, any_slashes = join_options(opts)
2657 if any_slashes:
2658 any_prefix_is_slash = True
2660 if not self.is_flag and not self.count:
2661 rv += f" {self.make_metavar()}"
2663 return rv
2665 rv = [_write_opts(self.opts)]
2667 if self.secondary_opts:
2668 rv.append(_write_opts(self.secondary_opts))
2670 help = self.help or ""
2671 extra = []
2673 if self.show_envvar:
2674 envvar = self.envvar
2676 if envvar is None:
2677 if (
2678 self.allow_from_autoenv
2679 and ctx.auto_envvar_prefix is not None
2680 and self.name is not None
2681 ):
2682 envvar = f"{ctx.auto_envvar_prefix}_{self.name.upper()}"
2684 if envvar is not None:
2685 var_str = (
2686 envvar
2687 if isinstance(envvar, str)
2688 else ", ".join(str(d) for d in envvar)
2689 )
2690 extra.append(_("env var: {var}").format(var=var_str))
2692 # Temporarily enable resilient parsing to avoid type casting
2693 # failing for the default. Might be possible to extend this to
2694 # help formatting in general.
2695 resilient = ctx.resilient_parsing
2696 ctx.resilient_parsing = True
2698 try:
2699 default_value = self.get_default(ctx, call=False)
2700 finally:
2701 ctx.resilient_parsing = resilient
2703 show_default = False
2704 show_default_is_str = False
2706 if self.show_default is not None:
2707 if isinstance(self.show_default, str):
2708 show_default_is_str = show_default = True
2709 else:
2710 show_default = self.show_default
2711 elif ctx.show_default is not None:
2712 show_default = ctx.show_default
2714 if show_default_is_str or (show_default and (default_value is not None)):
2715 if show_default_is_str:
2716 default_string = f"({self.show_default})"
2717 elif isinstance(default_value, (list, tuple)):
2718 default_string = ", ".join(str(d) for d in default_value)
2719 elif inspect.isfunction(default_value):
2720 default_string = _("(dynamic)")
2721 elif self.is_bool_flag and self.secondary_opts:
2722 # For boolean flags that have distinct True/False opts,
2723 # use the opt without prefix instead of the value.
2724 default_string = _split_opt(
2725 (self.opts if self.default else self.secondary_opts)[0]
2726 )[1]
2727 elif self.is_bool_flag and not self.secondary_opts and not default_value:
2728 default_string = ""
2729 else:
2730 default_string = str(default_value)
2732 if default_string:
2733 extra.append(_("default: {default}").format(default=default_string))
2735 if (
2736 isinstance(self.type, types._NumberRangeBase)
2737 # skip count with default range type
2738 and not (self.count and self.type.min == 0 and self.type.max is None)
2739 ):
2740 range_str = self.type._describe_range()
2742 if range_str:
2743 extra.append(range_str)
2745 if self.required:
2746 extra.append(_("required"))
2748 if extra:
2749 extra_str = "; ".join(extra)
2750 help = f"{help} [{extra_str}]" if help else f"[{extra_str}]"
2752 return ("; " if any_prefix_is_slash else " / ").join(rv), help
2754 @t.overload
2755 def get_default(
2756 self, ctx: Context, call: t.Literal[True] = True
2757 ) -> t.Any | None: ...
2759 @t.overload
2760 def get_default(
2761 self, ctx: Context, call: bool = ...
2762 ) -> t.Any | t.Callable[[], t.Any] | None: ...
2764 def get_default(
2765 self, ctx: Context, call: bool = True
2766 ) -> t.Any | t.Callable[[], t.Any] | None:
2767 # If we're a non boolean flag our default is more complex because
2768 # we need to look at all flags in the same group to figure out
2769 # if we're the default one in which case we return the flag
2770 # value as default.
2771 if self.is_flag and not self.is_bool_flag:
2772 for param in ctx.command.params:
2773 if param.name == self.name and param.default:
2774 return t.cast(Option, param).flag_value
2776 return None
2778 return super().get_default(ctx, call=call)
2780 def prompt_for_value(self, ctx: Context) -> t.Any:
2781 """This is an alternative flow that can be activated in the full
2782 value processing if a value does not exist. It will prompt the
2783 user until a valid value exists and then returns the processed
2784 value as result.
2785 """
2786 assert self.prompt is not None
2788 # Calculate the default before prompting anything to be stable.
2789 default = self.get_default(ctx)
2791 # If this is a prompt for a flag we need to handle this
2792 # differently.
2793 if self.is_bool_flag:
2794 return confirm(self.prompt, default)
2796 return prompt(
2797 self.prompt,
2798 default=default,
2799 type=self.type,
2800 hide_input=self.hide_input,
2801 show_choices=self.show_choices,
2802 confirmation_prompt=self.confirmation_prompt,
2803 value_proc=lambda x: self.process_value(ctx, x),
2804 )
2806 def resolve_envvar_value(self, ctx: Context) -> str | None:
2807 rv = super().resolve_envvar_value(ctx)
2809 if rv is not None:
2810 return rv
2812 if (
2813 self.allow_from_autoenv
2814 and ctx.auto_envvar_prefix is not None
2815 and self.name is not None
2816 ):
2817 envvar = f"{ctx.auto_envvar_prefix}_{self.name.upper()}"
2818 rv = os.environ.get(envvar)
2820 if rv:
2821 return rv
2823 return None
2825 def value_from_envvar(self, ctx: Context) -> t.Any | None:
2826 rv: t.Any | None = self.resolve_envvar_value(ctx)
2828 if rv is None:
2829 return None
2831 value_depth = (self.nargs != 1) + bool(self.multiple)
2833 if value_depth > 0:
2834 rv = self.type.split_envvar_value(rv)
2836 if self.multiple and self.nargs != 1:
2837 rv = batch(rv, self.nargs)
2839 return rv
2841 def consume_value(
2842 self, ctx: Context, opts: cabc.Mapping[str, Parameter]
2843 ) -> tuple[t.Any, ParameterSource]:
2844 value, source = super().consume_value(ctx, opts)
2846 # The parser will emit a sentinel value if the option can be
2847 # given as a flag without a value. This is different from None
2848 # to distinguish from the flag not being given at all.
2849 if value is _flag_needs_value:
2850 if self.prompt is not None and not ctx.resilient_parsing:
2851 value = self.prompt_for_value(ctx)
2852 source = ParameterSource.PROMPT
2853 else:
2854 value = self.flag_value
2855 source = ParameterSource.COMMANDLINE
2857 elif (
2858 self.multiple
2859 and value is not None
2860 and any(v is _flag_needs_value for v in value)
2861 ):
2862 value = [self.flag_value if v is _flag_needs_value else v for v in value]
2863 source = ParameterSource.COMMANDLINE
2865 # The value wasn't set, or used the param's default, prompt if
2866 # prompting is enabled.
2867 elif (
2868 source in {None, ParameterSource.DEFAULT}
2869 and self.prompt is not None
2870 and (self.required or self.prompt_required)
2871 and not ctx.resilient_parsing
2872 ):
2873 value = self.prompt_for_value(ctx)
2874 source = ParameterSource.PROMPT
2876 return value, source
2879class Argument(Parameter):
2880 """Arguments are positional parameters to a command. They generally
2881 provide fewer features than options but can have infinite ``nargs``
2882 and are required by default.
2884 All parameters are passed onwards to the constructor of :class:`Parameter`.
2885 """
2887 param_type_name = "argument"
2889 def __init__(
2890 self,
2891 param_decls: cabc.Sequence[str],
2892 required: bool | None = None,
2893 **attrs: t.Any,
2894 ) -> None:
2895 if required is None:
2896 if attrs.get("default") is not None:
2897 required = False
2898 else:
2899 required = attrs.get("nargs", 1) > 0
2901 if "multiple" in attrs:
2902 raise TypeError("__init__() got an unexpected keyword argument 'multiple'.")
2904 super().__init__(param_decls, required=required, **attrs)
2906 if __debug__:
2907 if self.default is not None and self.nargs == -1:
2908 raise TypeError("'default' is not supported for nargs=-1.")
2910 @property
2911 def human_readable_name(self) -> str:
2912 if self.metavar is not None:
2913 return self.metavar
2914 return self.name.upper() # type: ignore
2916 def make_metavar(self) -> str:
2917 if self.metavar is not None:
2918 return self.metavar
2919 var = self.type.get_metavar(self)
2920 if not var:
2921 var = self.name.upper() # type: ignore
2922 if not self.required:
2923 var = f"[{var}]"
2924 if self.nargs != 1:
2925 var += "..."
2926 return var
2928 def _parse_decls(
2929 self, decls: cabc.Sequence[str], expose_value: bool
2930 ) -> tuple[str | None, list[str], list[str]]:
2931 if not decls:
2932 if not expose_value:
2933 return None, [], []
2934 raise TypeError("Could not determine name for argument")
2935 if len(decls) == 1:
2936 name = arg = decls[0]
2937 name = name.replace("-", "_").lower()
2938 else:
2939 raise TypeError(
2940 "Arguments take exactly one parameter declaration, got"
2941 f" {len(decls)}."
2942 )
2943 return name, [arg], []
2945 def get_usage_pieces(self, ctx: Context) -> list[str]:
2946 return [self.make_metavar()]
2948 def get_error_hint(self, ctx: Context) -> str:
2949 return f"'{self.make_metavar()}'"
2951 def add_to_parser(self, parser: _OptionParser, ctx: Context) -> None:
2952 parser.add_argument(dest=self.name, nargs=self.nargs, obj=self)
2955def __getattr__(name: str) -> object:
2956 import warnings
2958 if name == "BaseCommand":
2959 warnings.warn(
2960 "'BaseCommand' is deprecated and will be removed in Click 9.0. Use"
2961 " 'Command' instead.",
2962 DeprecationWarning,
2963 stacklevel=2,
2964 )
2965 return _BaseCommand
2967 if name == "MultiCommand":
2968 warnings.warn(
2969 "'MultiCommand' is deprecated and will be removed in Click 9.0. Use"
2970 " 'Group' instead.",
2971 DeprecationWarning,
2972 stacklevel=2,
2973 )
2974 return _MultiCommand
2976 raise AttributeError(name)