Debian Codegraph @

src/asyncclick/core.py

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