Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/click/core.py: 35%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1416 statements  

1from __future__ import annotations 

2 

3import collections.abc as cabc 

4import enum 

5import errno 

6import inspect 

7import os 

8import sys 

9import typing as t 

10from abc import ABC 

11from abc import abstractmethod 

12from collections import abc 

13from collections import Counter 

14from contextlib import AbstractContextManager 

15from contextlib import contextmanager 

16from contextlib import ExitStack 

17from functools import update_wrapper 

18from gettext import gettext as _ 

19from gettext import ngettext 

20from itertools import repeat 

21from types import FrameType 

22from types import TracebackType 

23 

24from . import types 

25from ._utils import FLAG_NEEDS_VALUE 

26from ._utils import UNSET 

27from .exceptions import Abort 

28from .exceptions import BadParameter 

29from .exceptions import ClickException 

30from .exceptions import Exit 

31from .exceptions import MissingParameter 

32from .exceptions import NoArgsIsHelpError 

33from .exceptions import NoSuchCommand 

34from .exceptions import UsageError 

35from .formatting import HelpFormatter 

36from .formatting import join_options 

37from .globals import pop_context 

38from .globals import push_context 

39from .parser import _OptionParser 

40from .parser import _split_opt 

41from .termui import confirm 

42from .termui import prompt 

43from .termui import style 

44from .utils import _detect_program_name 

45from .utils import _expand_args 

46from .utils import _make_default_short_help 

47from .utils import _PacifyFlushWrapper 

48from .utils import echo 

49from .utils import make_str 

50 

51if t.TYPE_CHECKING: 

52 from typing_extensions import Self 

53 

54 from .shell_completion import CompletionItem 

55 

56F = t.TypeVar("F", bound="t.Callable[..., t.Any]") 

57V = t.TypeVar("V") 

58 

59# Reserved storage name of the automatic help option. No user parameter is 

60# expected to claim it. 

61_HELP_OPTION_STORAGE_NAME = "_click_default_help" 

62 

63 

64def _complete_visible_commands( 

65 ctx: Context, incomplete: str 

66) -> cabc.Iterator[tuple[str, Command]]: 

67 """List all the subcommands of a group that start with the 

68 incomplete value and aren't hidden. 

69 

70 :param ctx: Invocation context for the group. 

71 :param incomplete: Value being completed. May be empty. 

72 """ 

73 multi = t.cast(Group, ctx.command) 

74 

75 for name in multi.list_commands(ctx): 

76 if name.startswith(incomplete): 

77 command = multi.get_command(ctx, name) 

78 

79 if command is not None and not command.hidden: 

80 yield name, command 

81 

82 

83def _check_nested_chain( 

84 base_command: Group, cmd_name: str, cmd: Command, register: bool = False 

85) -> None: 

86 if not base_command.chain or not isinstance(cmd, Group): 

87 return 

88 

89 if register: 

90 message = ( 

91 f"It is not possible to add the group {cmd_name!r} to another" 

92 f" group {base_command.name!r} that is in chain mode." 

93 ) 

94 else: 

95 message = ( 

96 f"Found the group {cmd_name!r} as subcommand to another group " 

97 f" {base_command.name!r} that is in chain mode. This is not supported." 

98 ) 

99 

100 raise RuntimeError(message) 

101 

102 

103def _echo_aborted() -> None: 

104 """Write the final abort message to standard error.""" 

105 echo(_("Aborted!"), file=sys.stderr) 

106 

107 

108def _outside_click_stacklevel() -> int: 

109 """Depth of the first stack frame outside Click. 

110 

111 .. versionadded:: 8.6.0 

112 """ 

113 frame: FrameType | None = sys._getframe(1) 

114 level = 1 

115 

116 while frame is not None: 

117 module = frame.f_globals.get("__name__", "") 

118 

119 if module != "click" and not module.startswith("click."): 

120 return level 

121 

122 frame = frame.f_back 

123 level += 1 

124 

125 return level 

126 

127 

128def _format_deprecated_label(deprecated: bool | str) -> str: 

129 """Return the parenthesized deprecation label shown in help text.""" 

130 label = _("deprecated").upper() 

131 if isinstance(deprecated, str): 

132 return f"({label}: {deprecated})" 

133 return f"({label})" 

134 

135 

136def _format_deprecated_suffix(deprecated: bool | str) -> str: 

137 """Return the trailing reason for a ``DeprecationWarning`` message, 

138 prefixed with a space, or an empty string when no reason was given. 

139 """ 

140 if isinstance(deprecated, str): 

141 return f" {deprecated}" 

142 return "" 

143 

144 

145def batch(iterable: cabc.Iterable[V], batch_size: int) -> list[tuple[V, ...]]: 

146 return list(zip(*repeat(iter(iterable), batch_size), strict=False)) 

147 

148 

149@contextmanager 

150def augment_usage_errors( 

151 ctx: Context, param: Parameter | None = None 

152) -> cabc.Generator[None]: 

153 """Context manager that attaches extra information to exceptions.""" 

154 try: 

155 yield 

156 except BadParameter as e: 

157 if e.ctx is None: 

158 e.ctx = ctx 

159 if param is not None and e.param is None: 

160 e.param = param 

161 raise 

162 except UsageError as e: 

163 if e.ctx is None: 

164 e.ctx = ctx 

165 raise 

166 

167 

168def iter_params_for_processing( 

169 invocation_order: cabc.Sequence[Parameter], 

170 declaration_order: cabc.Sequence[Parameter], 

171) -> list[Parameter]: 

172 """Returns all declared parameters in the order they should be processed. 

173 

174 The declared parameters are re-shuffled depending on the order in which 

175 they were invoked, as well as the eagerness of each parameters. 

176 

177 The invocation order takes precedence over the declaration order. I.e. the 

178 order in which the user provided them to the CLI is respected. 

179 

180 This behavior and its effect on callback evaluation is detailed at: 

181 https://click.palletsprojects.com/en/stable/advanced/#callback-evaluation-order 

182 """ 

183 

184 def sort_key(item: Parameter) -> tuple[bool, float]: 

185 try: 

186 idx: float = invocation_order.index(item) 

187 except ValueError: 

188 idx = float("inf") 

189 

190 return not item.is_eager, idx 

191 

192 return sorted(declaration_order, key=sort_key) 

193 

194 

195class ParameterSource(enum.IntEnum): 

196 """This is an :class:`~enum.IntEnum` that indicates the source of a 

197 parameter's value. 

198 

199 Use :meth:`click.Context.get_parameter_source` to get the 

200 source for a parameter by name. 

201 

202 Members are ordered from most explicit to least explicit source. 

203 This allows comparison to check if a value was explicitly provided: 

204 

205 .. code-block:: python 

206 

207 source = ctx.get_parameter_source("port") 

208 if source < click.ParameterSource.DEFAULT_MAP: 

209 ... # value was explicitly set 

210 

211 .. versionchanged:: 8.3.3 

212 Use :class:`~enum.IntEnum` and reorder members from most to 

213 least explicit. Supports comparison operators. 

214 

215 .. versionchanged:: 8.0 

216 Use :class:`~enum.Enum` and drop the ``validate`` method. 

217 

218 .. versionchanged:: 8.0 

219 Added the ``PROMPT`` value. 

220 """ 

221 

222 PROMPT = enum.auto() 

223 """Used a prompt to confirm a default or provide a value.""" 

224 COMMANDLINE = enum.auto() 

225 """The value was provided by the command line args.""" 

226 ENVIRONMENT = enum.auto() 

227 """The value was provided with an environment variable.""" 

228 DEFAULT_MAP = enum.auto() 

229 """Used a default provided by :attr:`Context.default_map`.""" 

230 DEFAULT = enum.auto() 

231 """Used the default specified by the parameter.""" 

232 

233 

234class Context: 

235 """The context is a special internal object that holds state relevant 

236 for the script execution at every single level. It's normally invisible 

237 to commands unless they opt-in to getting access to it. 

238 

239 The context is useful as it can pass internal objects around and can 

240 control special execution features such as reading data from 

241 environment variables. 

242 

243 A context can be used as context manager in which case it will call 

244 :meth:`close` on teardown. 

245 

246 :param command: the command class for this context. 

247 :param parent: the parent context. 

248 :param info_name: the info name for this invocation. Generally this 

249 is the most descriptive name for the script or 

250 command. For the toplevel script it is usually 

251 the name of the script, for commands below that it's 

252 the name of the script. 

253 :param obj: an arbitrary object of user data. 

254 :param auto_envvar_prefix: the prefix to use for automatic environment 

255 variables. If this is `None` then reading 

256 from environment variables is disabled. This 

257 does not affect manually set environment 

258 variables which are always read. 

259 :param default_map: a dictionary (like object) with default values 

260 for parameters. 

261 :param terminal_width: the width of the terminal. The default is 

262 inherit from parent context. If no context 

263 defines the terminal width then auto 

264 detection will be applied. 

265 :param max_content_width: the maximum width for content rendered by 

266 Click (this currently only affects help 

267 pages). This defaults to 80 characters if 

268 not overridden. In other words: even if the 

269 terminal is larger than that, Click will not 

270 format things wider than 80 characters by 

271 default. In addition to that, formatters might 

272 add some safety mapping on the right. 

273 :param resilient_parsing: if this flag is enabled then Click will 

274 parse without any interactivity or callback 

275 invocation. Default values will also be 

276 ignored. This is useful for implementing 

277 things such as completion support. 

278 :param allow_extra_args: if this is set to `True` then extra arguments 

279 at the end will not raise an error and will be 

280 kept on the context. The default is to inherit 

281 from the command. 

282 :param allow_interspersed_args: if this is set to `False` then options 

283 and arguments cannot be mixed. The 

284 default is to inherit from the command. 

285 :param ignore_unknown_options: instructs click to ignore options it does 

286 not know and keeps them for later 

287 processing. 

288 :param help_option_names: optionally a list of strings that define how 

289 the default help parameter is named. The 

290 default is ``['--help']``. 

291 :param token_normalize_func: an optional function that is used to 

292 normalize tokens (options, choices, 

293 etc.). This for instance can be used to 

294 implement case insensitive behavior. 

295 :param color: controls if the terminal supports ANSI colors or not. The 

296 default is autodetection. This is only needed if ANSI 

297 codes are used in texts that Click prints which is by 

298 default not the case. This for instance would affect 

299 help output. 

300 :param show_default: Show the default value for commands. If this 

301 value is not set, it defaults to the value from the parent 

302 context. ``Command.show_default`` overrides this default for the 

303 specific command. 

304 

305 .. versionchanged:: 8.2 

306 The ``protected_args`` attribute is deprecated and will be removed in 

307 Click 9.0. ``args`` will contain remaining unparsed tokens. 

308 

309 .. versionchanged:: 8.1 

310 The ``show_default`` parameter is overridden by 

311 ``Command.show_default``, instead of the other way around. 

312 

313 .. versionchanged:: 8.0 

314 The ``show_default`` parameter defaults to the value from the 

315 parent context. 

316 

317 .. versionchanged:: 7.1 

318 Added the ``show_default`` parameter. 

319 

320 .. versionchanged:: 4.0 

321 Added the ``color``, ``ignore_unknown_options``, and 

322 ``max_content_width`` parameters. 

323 

324 .. versionchanged:: 3.0 

325 Added the ``allow_extra_args`` and ``allow_interspersed_args`` 

326 parameters. 

327 

328 .. versionchanged:: 2.0 

329 Added the ``resilient_parsing``, ``help_option_names``, and 

330 ``token_normalize_func`` parameters. 

331 """ 

332 

333 #: The formatter class to create with :meth:`make_formatter`. 

334 #: 

335 #: .. versionadded:: 8.0 

336 formatter_class: type[HelpFormatter] = HelpFormatter 

337 

338 parent: Context | None 

339 command: Command 

340 info_name: str | None 

341 params: dict[str, t.Any] 

342 args: list[str] 

343 _protected_args: list[str] 

344 _opt_prefixes: set[str] 

345 obj: t.Any 

346 _meta: dict[str, t.Any] 

347 default_map: cabc.MutableMapping[str, t.Any] | None 

348 invoked_subcommand: str | None 

349 terminal_width: int | None 

350 max_content_width: int | None 

351 allow_extra_args: bool 

352 allow_interspersed_args: bool 

353 ignore_unknown_options: bool 

354 help_option_names: list[str] 

355 token_normalize_func: t.Callable[[str], str] | None 

356 resilient_parsing: bool 

357 auto_envvar_prefix: str | None 

358 color: bool | None 

359 show_default: bool | None 

360 _close_callbacks: list[t.Callable[[], t.Any]] 

361 _depth: int 

362 _parameter_source: dict[str, ParameterSource] 

363 _param_default_explicit: dict[str, bool] 

364 _exit_stack: ExitStack 

365 

366 def __init__( 

367 self, 

368 command: Command, 

369 parent: Context | None = None, 

370 info_name: str | None = None, 

371 obj: t.Any | None = None, 

372 auto_envvar_prefix: str | None = None, 

373 default_map: cabc.MutableMapping[str, t.Any] | None = None, 

374 terminal_width: int | None = None, 

375 max_content_width: int | None = None, 

376 resilient_parsing: bool = False, 

377 allow_extra_args: bool | None = None, 

378 allow_interspersed_args: bool | None = None, 

379 ignore_unknown_options: bool | None = None, 

380 help_option_names: list[str] | None = None, 

381 token_normalize_func: t.Callable[[str], str] | None = None, 

382 color: bool | None = None, 

383 show_default: bool | None = None, 

384 ) -> None: 

385 #: the parent context or `None` if none exists. 

386 self.parent = parent 

387 #: the :class:`Command` for this context. 

388 self.command = command 

389 #: the descriptive information name 

390 self.info_name = info_name 

391 #: Map of parameter names to their parsed values. Parameters 

392 #: with ``expose_value=False`` are not stored. 

393 self.params = {} 

394 #: the leftover arguments. 

395 self.args = [] 

396 #: protected arguments. These are arguments that are prepended 

397 #: to `args` when certain parsing scenarios are encountered but 

398 #: must be never propagated to another arguments. This is used 

399 #: to implement nested parsing. 

400 self._protected_args = [] 

401 #: the collected prefixes of the command's options. 

402 self._opt_prefixes = set(parent._opt_prefixes) if parent else set() 

403 

404 if obj is None and parent is not None: 

405 obj = parent.obj 

406 

407 #: the user object stored. 

408 self.obj = obj 

409 self._meta = getattr(parent, "meta", {}) 

410 

411 #: A dictionary (-like object) with defaults for parameters. 

412 if ( 

413 default_map is None 

414 and info_name is not None 

415 and parent is not None 

416 and parent.default_map is not None 

417 ): 

418 default_map = parent.default_map.get(info_name) 

419 

420 self.default_map = default_map 

421 

422 #: This flag indicates if a subcommand is going to be executed. A 

423 #: group callback can use this information to figure out if it's 

424 #: being executed directly or because the execution flow passes 

425 #: onwards to a subcommand. By default it's None, but it can be 

426 #: the name of the subcommand to execute. 

427 #: 

428 #: If chaining is enabled this will be set to ``'*'`` in case 

429 #: any commands are executed. It is however not possible to 

430 #: figure out which ones. If you require this knowledge you 

431 #: should use a :func:`result_callback`. 

432 self.invoked_subcommand = None 

433 

434 if terminal_width is None and parent is not None: 

435 terminal_width = parent.terminal_width 

436 

437 #: The width of the terminal (None is autodetection). 

438 self.terminal_width = terminal_width 

439 

440 if max_content_width is None and parent is not None: 

441 max_content_width = parent.max_content_width 

442 

443 #: The maximum width of formatted content (None implies a sensible 

444 #: default which is 80 for most things). 

445 self.max_content_width = max_content_width 

446 

447 if allow_extra_args is None: 

448 allow_extra_args = command.allow_extra_args 

449 

450 #: Indicates if the context allows extra args or if it should 

451 #: fail on parsing. 

452 #: 

453 #: .. versionadded:: 3.0 

454 self.allow_extra_args = allow_extra_args 

455 

456 if allow_interspersed_args is None: 

457 allow_interspersed_args = command.allow_interspersed_args 

458 

459 #: Indicates if the context allows mixing of arguments and 

460 #: options or not. 

461 #: 

462 #: .. versionadded:: 3.0 

463 self.allow_interspersed_args = allow_interspersed_args 

464 

465 if ignore_unknown_options is None: 

466 ignore_unknown_options = command.ignore_unknown_options 

467 

468 #: Instructs click to ignore options that a command does not 

469 #: understand and will store it on the context for later 

470 #: processing. This is primarily useful for situations where you 

471 #: want to call into external programs. Generally this pattern is 

472 #: strongly discouraged because it's not possibly to losslessly 

473 #: forward all arguments. 

474 #: 

475 #: .. versionadded:: 4.0 

476 self.ignore_unknown_options = ignore_unknown_options 

477 

478 if help_option_names is None: 

479 if parent is not None: 

480 help_option_names = parent.help_option_names 

481 else: 

482 help_option_names = ["--help"] 

483 

484 #: The names for the help options. 

485 self.help_option_names = help_option_names 

486 

487 if token_normalize_func is None and parent is not None: 

488 token_normalize_func = parent.token_normalize_func 

489 

490 #: An optional normalization function for tokens. This is 

491 #: options, choices, commands etc. 

492 self.token_normalize_func = token_normalize_func 

493 

494 #: Indicates if resilient parsing is enabled. In that case Click 

495 #: will do its best to not cause any failures and default values 

496 #: will be ignored. Useful for completion. 

497 self.resilient_parsing = resilient_parsing 

498 

499 # If there is no envvar prefix yet, but the parent has one and 

500 # the command on this level has a name, we can expand the envvar 

501 # prefix automatically. 

502 if auto_envvar_prefix is None: 

503 if ( 

504 parent is not None 

505 and parent.auto_envvar_prefix is not None 

506 and self.info_name is not None 

507 ): 

508 auto_envvar_prefix = ( 

509 f"{parent.auto_envvar_prefix}_{self.info_name.upper()}" 

510 ) 

511 else: 

512 auto_envvar_prefix = auto_envvar_prefix.upper() 

513 

514 if auto_envvar_prefix is not None: 

515 auto_envvar_prefix = auto_envvar_prefix.replace("-", "_") 

516 

517 self.auto_envvar_prefix = auto_envvar_prefix 

518 

519 if color is None and parent is not None: 

520 color = parent.color 

521 

522 #: Controls if styling output is wanted or not. 

523 self.color = color 

524 

525 if show_default is None and parent is not None: 

526 show_default = parent.show_default 

527 

528 #: Show option default values when formatting help text. 

529 self.show_default = show_default 

530 

531 self._close_callbacks = [] 

532 self._depth = 0 

533 self._parameter_source = {} 

534 # Tracks whether the option that currently owns each parameter slot in 

535 # :attr:`params` had its ``default`` set explicitly by the user. Used 

536 # to tie-break feature-switch groups where multiple options share a 

537 # parameter name and both fall back to their default value. 

538 # Refs: https://github.com/pallets/click/issues/3403 

539 self._param_default_explicit = {} 

540 self._exit_stack = ExitStack() 

541 

542 @property 

543 def protected_args(self) -> list[str]: 

544 import warnings 

545 

546 warnings.warn( 

547 "'protected_args' is deprecated and will be removed in Click 9.0." 

548 " 'args' will contain remaining unparsed tokens.", 

549 DeprecationWarning, 

550 stacklevel=2, 

551 ) 

552 return self._protected_args 

553 

554 def to_info_dict(self) -> dict[str, t.Any]: 

555 """Gather information that could be useful for a tool generating 

556 user-facing documentation. This traverses the entire CLI 

557 structure. 

558 

559 .. code-block:: python 

560 

561 with Context(cli) as ctx: 

562 info = ctx.to_info_dict() 

563 

564 .. versionadded:: 8.0 

565 """ 

566 return { 

567 "command": self.command.to_info_dict(self), 

568 "info_name": self.info_name, 

569 "allow_extra_args": self.allow_extra_args, 

570 "allow_interspersed_args": self.allow_interspersed_args, 

571 "ignore_unknown_options": self.ignore_unknown_options, 

572 "auto_envvar_prefix": self.auto_envvar_prefix, 

573 } 

574 

575 def __enter__(self) -> Self: 

576 self._depth += 1 

577 push_context(self) 

578 return self 

579 

580 def __exit__( 

581 self, 

582 exc_type: type[BaseException] | None, 

583 exc_value: BaseException | None, 

584 tb: TracebackType | None, 

585 ) -> bool | None: 

586 self._depth -= 1 

587 exit_result: bool | None = None 

588 if self._depth == 0: 

589 exit_result = self._close_with_exception_info(exc_type, exc_value, tb) 

590 pop_context() 

591 

592 return exit_result 

593 

594 @contextmanager 

595 def scope(self, cleanup: bool = True) -> cabc.Generator[Context]: 

596 """This helper method can be used with the context object to promote 

597 it to the current thread local (see :func:`get_current_context`). 

598 The default behavior of this is to invoke the cleanup functions which 

599 can be disabled by setting `cleanup` to `False`. The cleanup 

600 functions are typically used for things such as closing file handles. 

601 

602 If the cleanup is intended the context object can also be directly 

603 used as a context manager. 

604 

605 Example usage:: 

606 

607 with ctx.scope(): 

608 assert get_current_context() is ctx 

609 

610 This is equivalent:: 

611 

612 with ctx: 

613 assert get_current_context() is ctx 

614 

615 .. versionadded:: 5.0 

616 

617 :param cleanup: controls if the cleanup functions should be run or 

618 not. The default is to run these functions. In 

619 some situations the context only wants to be 

620 temporarily pushed in which case this can be disabled. 

621 Nested pushes automatically defer the cleanup. 

622 """ 

623 if not cleanup: 

624 self._depth += 1 

625 try: 

626 with self as rv: 

627 yield rv 

628 finally: 

629 if not cleanup: 

630 self._depth -= 1 

631 

632 @property 

633 def meta(self) -> dict[str, t.Any]: 

634 """This is a dictionary which is shared with all the contexts 

635 that are nested. It exists so that click utilities can store some 

636 state here if they need to. It is however the responsibility of 

637 that code to manage this dictionary well. 

638 

639 The keys are supposed to be unique dotted strings. For instance 

640 module paths are a good choice for it. What is stored in there is 

641 irrelevant for the operation of click. However what is important is 

642 that code that places data here adheres to the general semantics of 

643 the system. 

644 

645 Example usage:: 

646 

647 LANG_KEY = f'{__name__}.lang' 

648 

649 def set_language(value): 

650 ctx = get_current_context() 

651 ctx.meta[LANG_KEY] = value 

652 

653 def get_language(): 

654 return get_current_context().meta.get(LANG_KEY, 'en_US') 

655 

656 .. versionadded:: 5.0 

657 """ 

658 return self._meta 

659 

660 def make_formatter(self) -> HelpFormatter: 

661 """Creates the :class:`~click.HelpFormatter` for the help and 

662 usage output. 

663 

664 To quickly customize the formatter class used without overriding 

665 this method, set the :attr:`formatter_class` attribute. 

666 

667 .. versionchanged:: 8.0 

668 Added the :attr:`formatter_class` attribute. 

669 """ 

670 return self.formatter_class( 

671 width=self.terminal_width, max_width=self.max_content_width 

672 ) 

673 

674 def with_resource(self, context_manager: AbstractContextManager[V]) -> V: 

675 """Register a resource as if it were used in a ``with`` 

676 statement. The resource will be cleaned up when the context is 

677 popped. 

678 

679 Uses :meth:`contextlib.ExitStack.enter_context`. It calls the 

680 resource's ``__enter__()`` method and returns the result. When 

681 the context is popped, it closes the stack, which calls the 

682 resource's ``__exit__()`` method. 

683 

684 To register a cleanup function for something that isn't a 

685 context manager, use :meth:`call_on_close`. Or use something 

686 from :mod:`contextlib` to turn it into a context manager first. 

687 

688 .. code-block:: python 

689 

690 @click.group() 

691 @click.option("--name") 

692 @click.pass_context 

693 def cli(ctx): 

694 ctx.obj = ctx.with_resource(connect_db(name)) 

695 

696 :param context_manager: The context manager to enter. 

697 :return: Whatever ``context_manager.__enter__()`` returns. 

698 

699 .. versionadded:: 8.0 

700 """ 

701 return self._exit_stack.enter_context(context_manager) 

702 

703 def call_on_close(self, f: t.Callable[..., t.Any]) -> t.Callable[..., t.Any]: 

704 """Register a function to be called when the context tears down. 

705 

706 This can be used to close resources opened during the script 

707 execution. Resources that support Python's context manager 

708 protocol which would be used in a ``with`` statement should be 

709 registered with :meth:`with_resource` instead. 

710 

711 :param f: The function to execute on teardown. 

712 """ 

713 return self._exit_stack.callback(f) 

714 

715 def close(self) -> None: 

716 """Invoke all close callbacks registered with 

717 :meth:`call_on_close`, and exit all context managers entered 

718 with :meth:`with_resource`. 

719 """ 

720 self._close_with_exception_info(None, None, None) 

721 

722 def _close_with_exception_info( 

723 self, 

724 exc_type: type[BaseException] | None, 

725 exc_value: BaseException | None, 

726 tb: TracebackType | None, 

727 ) -> bool | None: 

728 """Unwind the exit stack by calling its :meth:`__exit__` providing the exception 

729 information to allow for exception handling by the various resources registered 

730 using :meth;`with_resource` 

731 

732 :return: Whatever ``exit_stack.__exit__()`` returns. 

733 """ 

734 exit_result = self._exit_stack.__exit__(exc_type, exc_value, tb) 

735 # In case the context is reused, create a new exit stack. 

736 self._exit_stack = ExitStack() 

737 

738 return exit_result 

739 

740 @property 

741 def command_path(self) -> str: 

742 """The computed command path. This is used for the ``usage`` 

743 information on the help page. It's automatically created by 

744 combining the info names of the chain of contexts to the root. 

745 """ 

746 rv = "" 

747 if self.info_name is not None: 

748 rv = self.info_name 

749 if self.parent is not None: 

750 parent_command_path = [self.parent.command_path] 

751 

752 if isinstance(self.parent.command, Command): 

753 for param in self.parent.command.get_params(self): 

754 parent_command_path.extend(param.get_usage_pieces(self)) 

755 

756 rv = f"{' '.join(parent_command_path)} {rv}" 

757 return rv.lstrip() 

758 

759 def find_root(self) -> Context: 

760 """Finds the outermost context.""" 

761 node = self 

762 while node.parent is not None: 

763 node = node.parent 

764 return node 

765 

766 def find_object(self, object_type: type[V]) -> V | None: 

767 """Finds the closest object of a given type.""" 

768 node: Context | None = self 

769 

770 while node is not None: 

771 if isinstance(node.obj, object_type): 

772 return node.obj 

773 

774 node = node.parent 

775 

776 return None 

777 

778 def ensure_object(self, object_type: type[V]) -> V: 

779 """Like :meth:`find_object` but sets the innermost object to a 

780 new instance of `object_type` if it does not exist. 

781 """ 

782 rv = self.find_object(object_type) 

783 if rv is None: 

784 self.obj = rv = object_type() 

785 return rv 

786 

787 def _default_map_has(self, name: str | None) -> bool: 

788 """Check if :attr:`default_map` contains a real value for ``name``. 

789 

790 Returns ``False`` when the key is absent, the map is ``None``, 

791 ``name`` is ``None``, or the stored value is the internal 

792 :data:`UNSET` sentinel. 

793 """ 

794 return ( 

795 name is not None 

796 and self.default_map is not None 

797 and name in self.default_map 

798 and self.default_map[name] is not UNSET 

799 ) 

800 

801 @t.overload 

802 def lookup_default( 

803 self, name: str, call: t.Literal[True] = True 

804 ) -> t.Any | None: ... 

805 

806 @t.overload 

807 def lookup_default( 

808 self, name: str, call: t.Literal[False] = ... 

809 ) -> t.Any | t.Callable[[], t.Any] | None: ... 

810 

811 def lookup_default(self, name: str, call: bool = True) -> t.Any | None: 

812 """Get the default for a parameter from :attr:`default_map`. 

813 

814 :param name: Name of the parameter. 

815 :param call: If the default is a callable, call it. Disable to 

816 return the callable instead. 

817 

818 .. versionchanged:: 8.0 

819 Added the ``call`` parameter. 

820 """ 

821 if not self._default_map_has(name): 

822 return None 

823 

824 # Assert to make the type checker happy. 

825 assert self.default_map is not None 

826 value = self.default_map[name] 

827 

828 if call and callable(value): 

829 return value() 

830 

831 return value 

832 

833 def fail(self, message: str) -> t.NoReturn: 

834 """Aborts the execution of the program with a specific error 

835 message. 

836 

837 :param message: the error message to fail with. 

838 """ 

839 raise UsageError(message, self) 

840 

841 def abort(self) -> t.NoReturn: 

842 """Aborts the script.""" 

843 raise Abort() 

844 

845 def exit(self, code: int = 0) -> t.NoReturn: 

846 """Exits the application with a given exit code. 

847 

848 .. versionchanged:: 8.2 

849 Callbacks and context managers registered with :meth:`call_on_close` 

850 and :meth:`with_resource` are closed before exiting. 

851 """ 

852 self.close() 

853 raise Exit(code) 

854 

855 def get_usage(self) -> str: 

856 """Helper method to get formatted usage string for the current 

857 context and command. 

858 """ 

859 return self.command.get_usage(self) 

860 

861 def get_help(self) -> str: 

862 """Helper method to get formatted help page for the current 

863 context and command. 

864 """ 

865 return self.command.get_help(self) 

866 

867 def _make_sub_context(self, command: Command) -> Context: 

868 """Create a new context of the same type as this context, but 

869 for a new command. 

870 

871 :meta private: 

872 """ 

873 return type(self)(command, info_name=command.name, parent=self) 

874 

875 @t.overload 

876 def invoke( 

877 self, callback: t.Callable[..., V], /, *args: t.Any, **kwargs: t.Any 

878 ) -> V: ... 

879 

880 @t.overload 

881 def invoke(self, callback: Command, /, *args: t.Any, **kwargs: t.Any) -> t.Any: ... 

882 

883 def invoke( 

884 self, callback: Command | t.Callable[..., V], /, *args: t.Any, **kwargs: t.Any 

885 ) -> t.Any | V: 

886 """Invokes a command callback in exactly the way it expects. There 

887 are two ways to invoke this method: 

888 

889 1. the first argument can be a callback and all other arguments and 

890 keyword arguments are forwarded directly to the function. 

891 2. the first argument is a click command object. In that case all 

892 arguments are forwarded as well but proper click parameters 

893 (options and click arguments) must be keyword arguments and Click 

894 will fill in defaults. 

895 

896 .. versionchanged:: 8.0 

897 All ``kwargs`` are tracked in :attr:`params` so they will be 

898 passed if :meth:`forward` is called at multiple levels. 

899 

900 .. versionchanged:: 3.2 

901 A new context is created, and missing arguments use default values. 

902 """ 

903 if isinstance(callback, Command): 

904 other_cmd = callback 

905 

906 if other_cmd.callback is None: 

907 raise TypeError( 

908 "The given command does not have a callback that can be invoked." 

909 ) 

910 else: 

911 callback = t.cast("t.Callable[..., V]", other_cmd.callback) 

912 

913 ctx = self._make_sub_context(other_cmd) 

914 

915 for param in other_cmd.params: 

916 if param.name not in kwargs and param.expose_value: 

917 default_value = param.get_default(ctx) 

918 # We explicitly hide the :attr:`UNSET` value to the user, as we 

919 # choose to make it an implementation detail. And because ``invoke`` 

920 # has been designed as part of Click public API, we return ``None`` 

921 # instead. Refs: 

922 # https://github.com/pallets/click/issues/3066 

923 # https://github.com/pallets/click/issues/3065 

924 # https://github.com/pallets/click/pull/3068 

925 if default_value is UNSET: 

926 default_value = None 

927 kwargs[param.name] = param.type_cast_value(ctx, default_value) 

928 

929 # Track all kwargs as params, so that forward() will pass 

930 # them on in subsequent calls. 

931 ctx.params.update(kwargs) 

932 else: 

933 ctx = self 

934 

935 with augment_usage_errors(self), ctx: 

936 return callback(*args, **kwargs) 

937 

938 def forward(self, cmd: Command, /, *args: t.Any, **kwargs: t.Any) -> t.Any: 

939 """Similar to :meth:`invoke` but fills in default keyword 

940 arguments from the current context if the other command expects 

941 it. This cannot invoke callbacks directly, only other commands. 

942 

943 .. versionchanged:: 8.0 

944 All ``kwargs`` are tracked in :attr:`params` so they will be 

945 passed if ``forward`` is called at multiple levels. 

946 """ 

947 # Can only forward to other commands, not direct callbacks. 

948 if not isinstance(cmd, Command): 

949 raise TypeError("Callback is not a command.") 

950 

951 for param in self.params: 

952 if param not in kwargs: 

953 kwargs[param] = self.params[param] 

954 

955 return self.invoke(cmd, *args, **kwargs) 

956 

957 def set_parameter_source(self, name: str, source: ParameterSource) -> None: 

958 """Set the source of a parameter. This indicates the location 

959 from which the value of the parameter was obtained. 

960 

961 :param name: The name of the parameter. 

962 :param source: A member of :class:`~click.core.ParameterSource`. 

963 """ 

964 self._parameter_source[name] = source 

965 

966 def get_parameter_source(self, name: str) -> ParameterSource | None: 

967 """Get the source of a parameter. This indicates the location 

968 from which the value of the parameter was obtained. 

969 

970 This can be useful for determining when a user specified a value 

971 on the command line that is the same as the default value. It 

972 will be :attr:`~click.core.ParameterSource.DEFAULT` only if the 

973 value was actually taken from the default. 

974 

975 :param name: The name of the parameter. 

976 :rtype: ParameterSource 

977 

978 .. versionchanged:: 8.0 

979 Returns ``None`` if the parameter was not provided from any 

980 source. 

981 """ 

982 return self._parameter_source.get(name) 

983 

984 

985class Command: 

986 """Commands are the basic building block of command line interfaces in 

987 Click. A basic command handles command line parsing and might dispatch 

988 more parsing to commands nested below it. 

989 

990 :param name: the name of the command to use unless a group overrides it. 

991 :param context_settings: an optional dictionary with defaults that are 

992 passed to the context object. 

993 :param callback: the callback to invoke. This is optional. 

994 :param params: the parameters to register with this command. This can 

995 be either :class:`Option` or :class:`Argument` objects. 

996 :param help: the help string to use for this command. 

997 :param epilog: like the help string but it's printed at the end of the 

998 help page after everything else. 

999 :param short_help: the short help to use for this command. This is 

1000 shown on the command listing of the parent command. 

1001 :param add_help_option: by default each command registers a ``--help`` 

1002 option. This can be disabled by this parameter. 

1003 :param no_args_is_help: this controls what happens if no arguments are 

1004 provided. This option is disabled by default. 

1005 If enabled this will add ``--help`` as argument 

1006 if no arguments are passed 

1007 :param hidden: hide this command from help outputs. 

1008 :param deprecated: If ``True`` or non-empty string, issues a message 

1009 indicating that the command is deprecated and highlights 

1010 its deprecation in --help. The message can be customized 

1011 by using a string as the value. 

1012 

1013 .. versionchanged:: 8.2 

1014 This is the base class for all commands, not ``BaseCommand``. 

1015 ``deprecated`` can be set to a string as well to customize the 

1016 deprecation message. 

1017 

1018 .. versionchanged:: 8.1 

1019 ``help``, ``epilog``, and ``short_help`` are stored unprocessed, 

1020 all formatting is done when outputting help text, not at init, 

1021 and is done even if not using the ``@command`` decorator. 

1022 

1023 .. versionchanged:: 8.0 

1024 Added a ``repr`` showing the command name. 

1025 

1026 .. versionchanged:: 7.1 

1027 Added the ``no_args_is_help`` parameter. 

1028 

1029 .. versionchanged:: 2.0 

1030 Added the ``context_settings`` parameter. 

1031 """ 

1032 

1033 #: The context class to create with :meth:`make_context`. 

1034 #: 

1035 #: .. versionadded:: 8.0 

1036 context_class: type[Context] = Context 

1037 

1038 #: the default for the :attr:`Context.allow_extra_args` flag. 

1039 allow_extra_args = False 

1040 

1041 #: the default for the :attr:`Context.allow_interspersed_args` flag. 

1042 allow_interspersed_args = True 

1043 

1044 #: the default for the :attr:`Context.ignore_unknown_options` flag. 

1045 ignore_unknown_options = False 

1046 

1047 name: str | None 

1048 context_settings: cabc.MutableMapping[str, t.Any] 

1049 callback: t.Callable[..., t.Any] | None 

1050 params: list[Parameter] 

1051 help: str | None 

1052 epilog: str | None 

1053 options_metavar: str | None 

1054 short_help: str | None 

1055 add_help_option: bool 

1056 _help_option: Option | None 

1057 no_args_is_help: bool 

1058 hidden: bool 

1059 deprecated: bool | str 

1060 

1061 def __init__( 

1062 self, 

1063 name: str | None, 

1064 context_settings: cabc.MutableMapping[str, t.Any] | None = None, 

1065 callback: t.Callable[..., t.Any] | None = None, 

1066 params: list[Parameter] | None = None, 

1067 help: str | None = None, 

1068 epilog: str | None = None, 

1069 short_help: str | None = None, 

1070 options_metavar: str | None = "[OPTIONS]", 

1071 add_help_option: bool = True, 

1072 no_args_is_help: bool = False, 

1073 hidden: bool = False, 

1074 deprecated: bool | str = False, 

1075 ) -> None: 

1076 #: the name the command thinks it has. Upon registering a command 

1077 #: on a :class:`Group` the group will default the command name 

1078 #: with this information. You should instead use the 

1079 #: :class:`Context`\'s :attr:`~Context.info_name` attribute. 

1080 self.name = name 

1081 

1082 if context_settings is None: 

1083 context_settings = {} 

1084 

1085 #: an optional dictionary with defaults passed to the context. 

1086 self.context_settings = context_settings 

1087 

1088 #: the callback to execute when the command fires. This might be 

1089 #: `None` in which case nothing happens. 

1090 self.callback = callback 

1091 #: the list of parameters for this command in the order they 

1092 #: should show up in the help page and execute. Eager parameters 

1093 #: will automatically be handled before non eager ones. 

1094 self.params = params or [] 

1095 self.help = help 

1096 self.epilog = epilog 

1097 self.options_metavar = options_metavar 

1098 self.short_help = short_help 

1099 self.add_help_option = add_help_option 

1100 self._help_option = None 

1101 self.no_args_is_help = no_args_is_help 

1102 self.hidden = hidden 

1103 self.deprecated = deprecated 

1104 

1105 def to_info_dict(self, ctx: Context) -> dict[str, t.Any]: 

1106 return { 

1107 "name": self.name, 

1108 "params": [param.to_info_dict() for param in self.get_params(ctx)], 

1109 "help": self.help, 

1110 "epilog": self.epilog, 

1111 "short_help": self.short_help, 

1112 "hidden": self.hidden, 

1113 "deprecated": self.deprecated, 

1114 } 

1115 

1116 def __repr__(self) -> str: 

1117 return f"<{self.__class__.__name__} {self.name}>" 

1118 

1119 def get_usage(self, ctx: Context) -> str: 

1120 """Formats the usage line into a string and returns it. 

1121 

1122 Calls :meth:`format_usage` internally. 

1123 """ 

1124 formatter = ctx.make_formatter() 

1125 self.format_usage(ctx, formatter) 

1126 return formatter.getvalue().rstrip("\n") 

1127 

1128 def get_params(self, ctx: Context) -> list[Parameter]: 

1129 params = self.params 

1130 help_option = self.get_help_option(ctx) 

1131 

1132 if help_option is not None: 

1133 params = [*params, help_option] 

1134 

1135 if __debug__: 

1136 import warnings 

1137 

1138 opts = [opt for param in params for opt in param.opts] 

1139 opts_counter = Counter(opts) 

1140 duplicate_opts = (opt for opt, count in opts_counter.items() if count > 1) 

1141 

1142 for duplicate_opt in duplicate_opts: 

1143 warnings.warn( 

1144 ( 

1145 f"The parameter {duplicate_opt} is used more than once. " 

1146 "Remove its duplicate as parameters should be unique." 

1147 ), 

1148 stacklevel=3, 

1149 ) 

1150 

1151 # Options may deliberately share a storage name to compete for 

1152 # the same value (feature switches), but an argument sharing a 

1153 # name silently overwrites the other parameter's value. 

1154 names_counter = Counter(param.name for param in params) 

1155 duplicate_names = ( 

1156 name for name, count in names_counter.items() if count > 1 

1157 ) 

1158 

1159 for duplicate_name in duplicate_names: 

1160 sharers = [param for param in params if param.name == duplicate_name] 

1161 

1162 if help_option in sharers: 

1163 warnings.warn( 

1164 ( 

1165 f"The name {duplicate_name!r} is reserved for the " 

1166 "automatic help option. Give the parameter a " 

1167 "different name." 

1168 ), 

1169 stacklevel=3, 

1170 ) 

1171 elif any(isinstance(param, Argument) for param in sharers): 

1172 warnings.warn( 

1173 ( 

1174 f"The name {duplicate_name!r} is used by an argument " 

1175 "and another parameter. They will overwrite each " 

1176 "other's value during parsing. Give each parameter " 

1177 "a unique name." 

1178 ), 

1179 stacklevel=3, 

1180 ) 

1181 

1182 return params 

1183 

1184 def format_usage(self, ctx: Context, formatter: HelpFormatter) -> None: 

1185 """Writes the usage line into the formatter. 

1186 

1187 This is a low-level method called by :meth:`get_usage`. 

1188 """ 

1189 pieces = self.collect_usage_pieces(ctx) 

1190 formatter.write_usage(ctx.command_path, " ".join(pieces)) 

1191 

1192 def collect_usage_pieces(self, ctx: Context) -> list[str]: 

1193 """Returns all the pieces that go into the usage line and returns 

1194 it as a list of strings. 

1195 """ 

1196 rv = [self.options_metavar] if self.options_metavar else [] 

1197 

1198 for param in self.get_params(ctx): 

1199 rv.extend(param.get_usage_pieces(ctx)) 

1200 

1201 return rv 

1202 

1203 def get_help_option_names(self, ctx: Context) -> list[str]: 

1204 """Returns the names for the help option. 

1205 

1206 Drops duplicates and names already reserved by another parameter. Order of 

1207 :attr:`Context.help_option_names` is preserved, so the result is stable. 

1208 

1209 .. versionchanged:: 8.5.0 

1210 Names keep their declaration order. 

1211 """ 

1212 all_names = dict.fromkeys(ctx.help_option_names) 

1213 for param in self.params: 

1214 for name in (*param.opts, *param.secondary_opts): 

1215 all_names.pop(name, None) 

1216 return list(all_names) 

1217 

1218 def get_help_option(self, ctx: Context) -> Option | None: 

1219 """Returns the help option object. 

1220 

1221 Skipped if :attr:`add_help_option` is ``False``. 

1222 

1223 .. versionchanged:: 8.5.0 

1224 The help option stores its value under the reserved name 

1225 ``_click_default_help``, so a parameter named ``help`` no 

1226 longer breaks parsing. 

1227 

1228 .. versionchanged:: 8.1.8 

1229 The help option is now cached to avoid creating it multiple times. 

1230 """ 

1231 help_option_names = self.get_help_option_names(ctx) 

1232 

1233 if not help_option_names or not self.add_help_option: 

1234 return None 

1235 

1236 # Cache the help option object in private _help_option attribute to 

1237 # avoid creating it multiple times. Not doing this will break the 

1238 # callback ordering by iter_params_for_processing(), which relies on 

1239 # object comparison. 

1240 if self._help_option is None: 

1241 # Avoid circular import. 

1242 from .decorators import help_option 

1243 

1244 # The help option never exposes its value, so it uses a reserved 

1245 # storage name, keeping it clear of user parameters (like an 

1246 # argument named "help") that would otherwise clobber its value. 

1247 help_option(*help_option_names, _HELP_OPTION_STORAGE_NAME)(self) 

1248 self._help_option = self.params.pop() # type: ignore[assignment] 

1249 

1250 return self._help_option 

1251 

1252 def make_parser(self, ctx: Context) -> _OptionParser: 

1253 """Creates the underlying option parser for this command.""" 

1254 parser = _OptionParser(ctx) 

1255 for param in self.get_params(ctx): 

1256 param.add_to_parser(parser, ctx) 

1257 return parser 

1258 

1259 def get_help(self, ctx: Context) -> str: 

1260 """Formats the help into a string and returns it. 

1261 

1262 Calls :meth:`format_help` internally. 

1263 """ 

1264 formatter = ctx.make_formatter() 

1265 self.format_help(ctx, formatter) 

1266 return formatter.getvalue().rstrip("\n") 

1267 

1268 def get_short_help_str(self, limit: int = 45) -> str: 

1269 """Gets short help for the command or makes it by shortening the 

1270 long help string. 

1271 """ 

1272 if self.short_help: 

1273 text = inspect.cleandoc(self.short_help) 

1274 elif self.help: 

1275 text = _make_default_short_help(self.help, limit) 

1276 else: 

1277 text = "" 

1278 

1279 if self.deprecated: 

1280 text = f"{_(text)} {_format_deprecated_label(self.deprecated)}" 

1281 

1282 return text.strip() 

1283 

1284 def format_help(self, ctx: Context, formatter: HelpFormatter) -> None: 

1285 """Writes the help into the formatter if it exists. 

1286 

1287 This is a low-level method called by :meth:`get_help`. 

1288 

1289 This calls the following methods: 

1290 

1291 - :meth:`format_usage` 

1292 - :meth:`format_help_text` 

1293 - :meth:`format_arguments` 

1294 - :meth:`format_options` 

1295 - :meth:`format_epilog` 

1296 """ 

1297 self.format_usage(ctx, formatter) 

1298 self.format_help_text(ctx, formatter) 

1299 self.format_arguments(ctx, formatter) 

1300 self.format_options(ctx, formatter) 

1301 self.format_epilog(ctx, formatter) 

1302 

1303 def format_help_text(self, ctx: Context, formatter: HelpFormatter) -> None: 

1304 """Writes the help text to the formatter if it exists.""" 

1305 if self.help is not None: 

1306 # truncate the help text to the first form feed 

1307 text = inspect.cleandoc(self.help).partition("\f")[0] 

1308 else: 

1309 text = "" 

1310 

1311 if self.deprecated: 

1312 label = _format_deprecated_label(self.deprecated) 

1313 text = f"{_(text)} {label}" if text else label 

1314 

1315 if text: 

1316 formatter.write_paragraph() 

1317 

1318 with formatter.indentation(): 

1319 formatter.write_text(text) 

1320 

1321 def format_options(self, ctx: Context, formatter: HelpFormatter) -> None: 

1322 """Writes all the options into the formatter if they exist.""" 

1323 opts = [] 

1324 for param in self.get_params(ctx): 

1325 rv = param.get_help_record(ctx) 

1326 if rv is not None and not isinstance(param, Argument): 

1327 opts.append(rv) 

1328 

1329 if opts: 

1330 with formatter.section(_("Options")): 

1331 formatter.write_dl(opts) 

1332 

1333 def format_arguments(self, ctx: Context, formatter: HelpFormatter) -> None: 

1334 """Writes all arguments into the formatter, if at least one is documented. 

1335 

1336 An argument with no help gets an empty description, the same way an option 

1337 with no help does. That keeps the section an exhaustive list of the 

1338 positional arguments, matching the usage line. 

1339 """ 

1340 args = [param for param in self.get_params(ctx) if isinstance(param, Argument)] 

1341 

1342 if any(arg.help is not None for arg in args): 

1343 with formatter.section(_("Positional arguments")): 

1344 formatter.write_dl([arg.get_help_record(ctx) for arg in args]) 

1345 

1346 def format_epilog(self, ctx: Context, formatter: HelpFormatter) -> None: 

1347 """Writes the epilog into the formatter if it exists.""" 

1348 if self.epilog: 

1349 epilog = inspect.cleandoc(self.epilog) 

1350 formatter.write_paragraph() 

1351 

1352 with formatter.indentation(): 

1353 formatter.write_text(epilog) 

1354 

1355 def make_context( 

1356 self, 

1357 info_name: str | None, 

1358 args: list[str], 

1359 parent: Context | None = None, 

1360 **extra: t.Any, 

1361 ) -> Context: 

1362 """This function when given an info name and arguments will kick 

1363 off the parsing and create a new :class:`Context`. It does not 

1364 invoke the actual command callback though. 

1365 

1366 To quickly customize the context class used without overriding 

1367 this method, set the :attr:`context_class` attribute. 

1368 

1369 :param info_name: the info name for this invocation. Generally this 

1370 is the most descriptive name for the script or 

1371 command. For the toplevel script it's usually 

1372 the name of the script, for commands below it's 

1373 the name of the command. 

1374 :param args: the arguments to parse as list of strings. 

1375 :param parent: the parent context if available. 

1376 :param extra: extra keyword arguments forwarded to the context 

1377 constructor. 

1378 

1379 .. versionchanged:: 8.0 

1380 Added the :attr:`context_class` attribute. 

1381 """ 

1382 for key, value in self.context_settings.items(): 

1383 if key not in extra: 

1384 extra[key] = value 

1385 

1386 ctx = self.context_class(self, info_name=info_name, parent=parent, **extra) 

1387 

1388 with ctx.scope(cleanup=False): 

1389 self.parse_args(ctx, args) 

1390 return ctx 

1391 

1392 def parse_args(self, ctx: Context, args: list[str]) -> list[str]: 

1393 if not args and self.no_args_is_help and not ctx.resilient_parsing: 

1394 raise NoArgsIsHelpError(ctx) 

1395 

1396 parser = self.make_parser(ctx) 

1397 opts, args, param_order = parser.parse_args(args=args) 

1398 

1399 for param in iter_params_for_processing(param_order, self.get_params(ctx)): 

1400 _, args = param.handle_parse_result(ctx, opts, args) 

1401 

1402 # We now have all parameters' values into `ctx.params`, but the data may contain 

1403 # the `UNSET` sentinel. 

1404 # Convert `UNSET` to `None` to ensure that the user doesn't see `UNSET`. 

1405 # 

1406 # Waiting until after the initial parse to convert allows us to treat `UNSET` 

1407 # more like a missing value when multiple params use the same name. 

1408 # Refs: 

1409 # https://github.com/pallets/click/issues/3071 

1410 # https://github.com/pallets/click/pull/3079 

1411 for name, value in ctx.params.items(): 

1412 if value is UNSET: 

1413 ctx.params[name] = None 

1414 

1415 if args and not ctx.allow_extra_args and not ctx.resilient_parsing: 

1416 ctx.fail( 

1417 ngettext( 

1418 "Got unexpected extra argument ({args})", 

1419 "Got unexpected extra arguments ({args})", 

1420 len(args), 

1421 ).format(args=" ".join(map(str, args))) 

1422 ) 

1423 

1424 ctx.args = args 

1425 ctx._opt_prefixes.update(parser._opt_prefixes) 

1426 return args 

1427 

1428 def invoke(self, ctx: Context) -> t.Any: 

1429 """Given a context, this invokes the attached callback (if it exists) 

1430 in the right way. 

1431 """ 

1432 if self.deprecated: 

1433 message = _( 

1434 "DeprecationWarning: The command {name!r} is deprecated.{extra_message}" 

1435 ).format( 

1436 name=self.name, 

1437 extra_message=_format_deprecated_suffix(self.deprecated), 

1438 ) 

1439 echo(style(message, fg="red"), err=True) 

1440 

1441 if self.callback is not None: 

1442 return ctx.invoke(self.callback, **ctx.params) 

1443 

1444 def shell_complete(self, ctx: Context, incomplete: str) -> list[CompletionItem]: 

1445 """Return a list of completions for the incomplete value. Looks 

1446 at the names of options and chained multi-commands. 

1447 

1448 Any command could be part of a chained multi-command, so sibling 

1449 commands are valid at any point during command completion. 

1450 

1451 :param ctx: Invocation context for this command. 

1452 :param incomplete: Value being completed. May be empty. 

1453 

1454 .. versionadded:: 8.0 

1455 """ 

1456 from click.shell_completion import CompletionItem 

1457 

1458 results: list[CompletionItem] = [] 

1459 

1460 if incomplete and not incomplete[0].isalnum(): 

1461 for param in self.get_params(ctx): 

1462 if ( 

1463 not isinstance(param, Option) 

1464 or param.hidden 

1465 or ( 

1466 not param.multiple 

1467 and ctx.get_parameter_source(param.name) 

1468 is ParameterSource.COMMANDLINE 

1469 ) 

1470 ): 

1471 continue 

1472 

1473 results.extend( 

1474 CompletionItem(name, help=param.help) 

1475 for name in [*param.opts, *param.secondary_opts] 

1476 if name.startswith(incomplete) 

1477 ) 

1478 

1479 while ctx.parent is not None: 

1480 ctx = ctx.parent 

1481 

1482 if isinstance(ctx.command, Group) and ctx.command.chain: 

1483 results.extend( 

1484 CompletionItem(name, help=command.get_short_help_str()) 

1485 for name, command in _complete_visible_commands(ctx, incomplete) 

1486 if name not in ctx._protected_args 

1487 ) 

1488 

1489 return results 

1490 

1491 @t.overload 

1492 def main( 

1493 self, 

1494 args: cabc.Sequence[str] | None = None, 

1495 prog_name: str | None = None, 

1496 complete_var: str | None = None, 

1497 standalone_mode: t.Literal[True] = True, 

1498 **extra: t.Any, 

1499 ) -> t.NoReturn: ... 

1500 

1501 @t.overload 

1502 def main( 

1503 self, 

1504 args: cabc.Sequence[str] | None = None, 

1505 prog_name: str | None = None, 

1506 complete_var: str | None = None, 

1507 standalone_mode: bool = ..., 

1508 **extra: t.Any, 

1509 ) -> t.Any: ... 

1510 

1511 def main( 

1512 self, 

1513 args: cabc.Sequence[str] | None = None, 

1514 prog_name: str | None = None, 

1515 complete_var: str | None = None, 

1516 standalone_mode: bool = True, 

1517 windows_expand_args: bool = True, 

1518 **extra: t.Any, 

1519 ) -> t.Any: 

1520 """This is the way to invoke a script with all the bells and 

1521 whistles as a command line application. This will always terminate 

1522 the application after a call. If this is not wanted, ``SystemExit`` 

1523 needs to be caught. 

1524 

1525 This method is also available by directly calling the instance of 

1526 a :class:`Command`. 

1527 

1528 :param args: the arguments that should be used for parsing. If not 

1529 provided, ``sys.argv[1:]`` is used. 

1530 :param prog_name: the program name that should be used. By default 

1531 the program name is constructed by taking the file 

1532 name from ``sys.argv[0]``. 

1533 :param complete_var: the environment variable that controls the 

1534 bash completion support. The default is 

1535 ``"_<prog_name>_COMPLETE"`` with prog_name in 

1536 uppercase. 

1537 :param standalone_mode: the default behavior is to invoke the script 

1538 in standalone mode. Click will then 

1539 handle exceptions and convert them into 

1540 error messages and the function will never 

1541 return but shut down the interpreter. If 

1542 this is set to `False` they will be 

1543 propagated to the caller and the return 

1544 value of this function is the return value 

1545 of :meth:`invoke`. 

1546 :param windows_expand_args: Expand glob patterns, user dir, and 

1547 env vars in command line args on Windows. 

1548 :param extra: extra keyword arguments are forwarded to the context 

1549 constructor. See :class:`Context` for more information. 

1550 

1551 .. versionchanged:: 8.0.1 

1552 Added the ``windows_expand_args`` parameter to allow 

1553 disabling command line arg expansion on Windows. 

1554 

1555 .. versionchanged:: 8.0 

1556 When taking arguments from ``sys.argv`` on Windows, glob 

1557 patterns, user dir, and env vars are expanded. 

1558 

1559 .. versionchanged:: 3.0 

1560 Added the ``standalone_mode`` parameter. 

1561 """ 

1562 if args is None: 

1563 args = sys.argv[1:] 

1564 

1565 if os.name == "nt" and windows_expand_args: 

1566 args = _expand_args(args) 

1567 else: 

1568 args = list(args) 

1569 

1570 if prog_name is None: 

1571 prog_name = _detect_program_name() 

1572 

1573 # Process shell completion requests and exit early. 

1574 self._main_shell_completion(extra, prog_name, complete_var) 

1575 

1576 # Every handler below takes the same two steps: propagate when 

1577 # standalone mode is disabled, otherwise collect the message and the 

1578 # exit code, and leave both to the teardown after the ``try``. The 

1579 # teardown writes the message and exits, and the outermost handler 

1580 # holds one policy for every interrupt arriving that late: the 

1581 # message may be lost, the intended exit code still wins. 

1582 report: cabc.Callable[[], None] | None = None 

1583 exit_code = 1 

1584 

1585 try: 

1586 try: 

1587 with self.make_context(prog_name, args, **extra) as ctx: 

1588 rv = self.invoke(ctx) 

1589 if not standalone_mode: 

1590 return rv 

1591 # it's not safe to `ctx.exit(rv)` here! 

1592 # note that `rv` may actually contain data like "1" which 

1593 # has obvious effects 

1594 # more subtle case: `rv=[None, None]` can come out of 

1595 # chained commands which all returned `None` -- so it's not 

1596 # even always obvious that `rv` indicates success/failure 

1597 # by its truthiness/falsiness 

1598 ctx.exit() 

1599 except Exit as e: 

1600 if not standalone_mode: 

1601 # in non-standalone mode, return the exit code 

1602 # note that this is only reached if `self.invoke` above raises 

1603 # an Exit explicitly -- thus bypassing the check there which 

1604 # would return its result 

1605 # the results of non-standalone execution may therefore be 

1606 # somewhat ambiguous: if there are codepaths which lead to 

1607 # `ctx.exit(1)` and to `return 1`, the caller won't be able to 

1608 # tell the difference between the two 

1609 return e.exit_code 

1610 

1611 exit_code = e.exit_code 

1612 except Abort: 

1613 if not standalone_mode: 

1614 raise 

1615 

1616 report = _echo_aborted 

1617 except (EOFError, KeyboardInterrupt) as e: 

1618 # The blank line closes the terminal's ``^C`` echo. 

1619 echo(file=sys.stderr) 

1620 

1621 if not standalone_mode: 

1622 raise Abort() from e 

1623 

1624 report = _echo_aborted 

1625 except ClickException as e: 

1626 if not standalone_mode: 

1627 raise 

1628 

1629 report, exit_code = e.show, e.exit_code 

1630 except OSError as e: 

1631 if e.errno != errno.EPIPE: 

1632 raise 

1633 

1634 sys.stdout = t.cast(t.TextIO, _PacifyFlushWrapper(sys.stdout)) 

1635 sys.stderr = t.cast(t.TextIO, _PacifyFlushWrapper(sys.stderr)) 

1636 

1637 if report is not None: 

1638 report() 

1639 

1640 sys.exit(exit_code) 

1641 except (EOFError, KeyboardInterrupt): 

1642 if not standalone_mode: 

1643 raise 

1644 

1645 sys.exit(exit_code) 

1646 

1647 def _main_shell_completion( 

1648 self, 

1649 ctx_args: cabc.MutableMapping[str, t.Any], 

1650 prog_name: str, 

1651 complete_var: str | None = None, 

1652 ) -> None: 

1653 """Check if the shell is asking for tab completion, process 

1654 that, then exit early. Called from :meth:`main` before the 

1655 program is invoked. 

1656 

1657 :param prog_name: Name of the executable in the shell. 

1658 :param complete_var: Name of the environment variable that holds 

1659 the completion instruction. Defaults to 

1660 ``_{PROG_NAME}_COMPLETE``. 

1661 

1662 .. versionchanged:: 8.2.0 

1663 Dots (``.``) in ``prog_name`` are replaced with underscores (``_``). 

1664 """ 

1665 if complete_var is None: 

1666 complete_name = prog_name.replace("-", "_").replace(".", "_") 

1667 complete_var = f"_{complete_name}_COMPLETE".upper() 

1668 

1669 instruction = os.environ.get(complete_var) 

1670 

1671 if not instruction: 

1672 return 

1673 

1674 from .shell_completion import shell_complete 

1675 

1676 rv = shell_complete(self, ctx_args, prog_name, complete_var, instruction) 

1677 sys.exit(rv) 

1678 

1679 def __call__(self, *args: t.Any, **kwargs: t.Any) -> t.Any: 

1680 """Alias for :meth:`main`.""" 

1681 return self.main(*args, **kwargs) 

1682 

1683 

1684class _FakeSubclassCheck(type): 

1685 def __subclasscheck__(cls, subclass: type) -> bool: 

1686 return issubclass(subclass, cls.__bases__[0]) 

1687 

1688 def __instancecheck__(cls, instance: t.Any) -> bool: 

1689 return isinstance(instance, cls.__bases__[0]) 

1690 

1691 

1692class _BaseCommand(Command, metaclass=_FakeSubclassCheck): 

1693 """ 

1694 .. deprecated:: 8.2 

1695 Will be removed in Click 9.0. Use ``Command`` instead. 

1696 """ 

1697 

1698 

1699class Group(Command): 

1700 """A group is a command that nests other commands (or more groups). 

1701 

1702 :param name: The name of the group command. 

1703 :param commands: Map names to :class:`Command` objects. Can be a list, which 

1704 will use :attr:`Command.name` as the keys. 

1705 :param invoke_without_command: Invoke the group's callback even if a 

1706 subcommand is not given. 

1707 :param no_args_is_help: If no arguments are given, show the group's help and 

1708 exit. Defaults to the opposite of ``invoke_without_command``. 

1709 :param subcommand_metavar: How to represent the subcommand argument in help. 

1710 The default will represent whether ``chain`` is set or not. 

1711 :param chain: Allow passing more than one subcommand argument. After parsing 

1712 a command's arguments, if any arguments remain another command will be 

1713 matched, and so on. 

1714 :param result_callback: A function to call after the group's and 

1715 subcommand's callbacks. The value returned by the subcommand is passed. 

1716 If ``chain`` is enabled, the value will be a list of values returned by 

1717 all the commands. If ``invoke_without_command`` is enabled, the value 

1718 will be the value returned by the group's callback, or an empty list if 

1719 ``chain`` is enabled. 

1720 :param kwargs: Other arguments passed to :class:`Command`. 

1721 

1722 .. versionchanged:: 8.0 

1723 The ``commands`` argument can be a list of command objects. 

1724 

1725 .. versionchanged:: 8.2 

1726 Merged with and replaces the ``MultiCommand`` base class. 

1727 """ 

1728 

1729 allow_extra_args = True 

1730 allow_interspersed_args = False 

1731 

1732 #: If set, this is used by the group's :meth:`command` decorator 

1733 #: as the default :class:`Command` class. This is useful to make all 

1734 #: subcommands use a custom command class. 

1735 #: 

1736 #: .. versionadded:: 8.0 

1737 command_class: type[Command] | None = None 

1738 

1739 #: If set, this is used by the group's :meth:`group` decorator 

1740 #: as the default :class:`Group` class. This is useful to make all 

1741 #: subgroups use a custom group class. 

1742 #: 

1743 #: If set to the special value :class:`type` (literally 

1744 #: ``group_class = type``), this group's class will be used as the 

1745 #: default class. This makes a custom group class continue to make 

1746 #: custom groups. 

1747 #: 

1748 #: .. versionadded:: 8.0 

1749 group_class: type[Group | type] | None = None 

1750 # Literal[type] isn't valid, so use Type[type] 

1751 

1752 commands: cabc.MutableMapping[str, Command] 

1753 invoke_without_command: bool 

1754 subcommand_metavar: str 

1755 chain: bool 

1756 _result_callback: t.Callable[..., t.Any] | None 

1757 

1758 def __init__( 

1759 self, 

1760 name: str | None = None, 

1761 commands: cabc.MutableMapping[str, Command] 

1762 | cabc.Sequence[Command] 

1763 | None = None, 

1764 invoke_without_command: bool = False, 

1765 no_args_is_help: bool | None = None, 

1766 subcommand_metavar: str | None = None, 

1767 chain: bool = False, 

1768 result_callback: t.Callable[..., t.Any] | None = None, 

1769 **kwargs: t.Any, 

1770 ) -> None: 

1771 super().__init__(name, **kwargs) 

1772 

1773 if commands is None: 

1774 commands = {} 

1775 elif isinstance(commands, abc.Sequence): 

1776 commands = {c.name: c for c in commands if c.name is not None} 

1777 

1778 #: The registered subcommands by their exported names. 

1779 self.commands = commands 

1780 

1781 if no_args_is_help is None: 

1782 no_args_is_help = not invoke_without_command 

1783 

1784 self.no_args_is_help = no_args_is_help 

1785 self.invoke_without_command = invoke_without_command 

1786 

1787 if subcommand_metavar is None: 

1788 # When the group can run without a subcommand, the leading command 

1789 # token is optional, so wrap it in brackets to reflect that. 

1790 if chain: 

1791 if invoke_without_command: 

1792 subcommand_metavar = "[COMMAND1] [ARGS]... [COMMAND2 [ARGS]...]..." 

1793 else: 

1794 subcommand_metavar = "COMMAND1 [ARGS]... [COMMAND2 [ARGS]...]..." 

1795 elif invoke_without_command: 

1796 subcommand_metavar = "[COMMAND] [ARGS]..." 

1797 else: 

1798 subcommand_metavar = "COMMAND [ARGS]..." 

1799 

1800 self.subcommand_metavar = subcommand_metavar 

1801 self.chain = chain 

1802 # The result callback that is stored. This can be set or 

1803 # overridden with the :func:`result_callback` decorator. 

1804 self._result_callback = result_callback 

1805 

1806 if self.chain: 

1807 for param in self.params: 

1808 if isinstance(param, Argument) and not param.required: 

1809 raise RuntimeError( 

1810 "A group in chain mode cannot have optional arguments." 

1811 ) 

1812 

1813 def to_info_dict(self, ctx: Context) -> dict[str, t.Any]: 

1814 info_dict = super().to_info_dict(ctx) 

1815 commands = {} 

1816 

1817 for name in self.list_commands(ctx): 

1818 command = self.get_command(ctx, name) 

1819 

1820 if command is None: 

1821 continue 

1822 

1823 sub_ctx = ctx._make_sub_context(command) 

1824 

1825 with sub_ctx.scope(cleanup=False): 

1826 commands[name] = command.to_info_dict(sub_ctx) 

1827 

1828 info_dict.update(commands=commands, chain=self.chain) 

1829 return info_dict 

1830 

1831 def add_command(self, cmd: Command, name: str | None = None) -> None: 

1832 """Registers another :class:`Command` with this group. If the name 

1833 is not provided, the name of the command is used. 

1834 """ 

1835 name = name or cmd.name 

1836 if name is None: 

1837 raise TypeError("Command has no name.") 

1838 _check_nested_chain(self, name, cmd, register=True) 

1839 self.commands[name] = cmd 

1840 

1841 @t.overload 

1842 def command(self, __func: t.Callable[..., t.Any]) -> Command: ... 

1843 

1844 @t.overload 

1845 def command( 

1846 self, *args: t.Any, **kwargs: t.Any 

1847 ) -> t.Callable[[t.Callable[..., t.Any]], Command]: ... 

1848 

1849 def command( 

1850 self, *args: t.Any, **kwargs: t.Any 

1851 ) -> t.Callable[[t.Callable[..., t.Any]], Command] | Command: 

1852 """A shortcut decorator for declaring and attaching a command to 

1853 the group. This takes the same arguments as :func:`command` and 

1854 immediately registers the created command with this group by 

1855 calling :meth:`add_command`. 

1856 

1857 To customize the command class used, set the 

1858 :attr:`command_class` attribute. 

1859 

1860 .. versionchanged:: 8.1 

1861 This decorator can be applied without parentheses. 

1862 

1863 .. versionchanged:: 8.0 

1864 Added the :attr:`command_class` attribute. 

1865 """ 

1866 from .decorators import command 

1867 

1868 func: t.Callable[..., t.Any] | None = None 

1869 

1870 if args and callable(args[0]): 

1871 assert len(args) == 1 and not kwargs, ( 

1872 "Use 'command(**kwargs)(callable)' to provide arguments." 

1873 ) 

1874 (func,) = args 

1875 args = () 

1876 

1877 if self.command_class and kwargs.get("cls") is None: 

1878 kwargs["cls"] = self.command_class 

1879 

1880 def decorator(f: t.Callable[..., t.Any]) -> Command: 

1881 cmd: Command = command(*args, **kwargs)(f) 

1882 self.add_command(cmd) 

1883 return cmd 

1884 

1885 if func is not None: 

1886 return decorator(func) 

1887 

1888 return decorator 

1889 

1890 @t.overload 

1891 def group(self, __func: t.Callable[..., t.Any]) -> Group: ... 

1892 

1893 @t.overload 

1894 def group( 

1895 self, *args: t.Any, **kwargs: t.Any 

1896 ) -> t.Callable[[t.Callable[..., t.Any]], Group]: ... 

1897 

1898 def group( 

1899 self, *args: t.Any, **kwargs: t.Any 

1900 ) -> t.Callable[[t.Callable[..., t.Any]], Group] | Group: 

1901 """A shortcut decorator for declaring and attaching a group to 

1902 the group. This takes the same arguments as :func:`group` and 

1903 immediately registers the created group with this group by 

1904 calling :meth:`add_command`. 

1905 

1906 To customize the group class used, set the :attr:`group_class` 

1907 attribute. 

1908 

1909 .. versionchanged:: 8.1 

1910 This decorator can be applied without parentheses. 

1911 

1912 .. versionchanged:: 8.0 

1913 Added the :attr:`group_class` attribute. 

1914 """ 

1915 from .decorators import group 

1916 

1917 func: t.Callable[..., t.Any] | None = None 

1918 

1919 if args and callable(args[0]): 

1920 assert len(args) == 1 and not kwargs, ( 

1921 "Use 'group(**kwargs)(callable)' to provide arguments." 

1922 ) 

1923 (func,) = args 

1924 args = () 

1925 

1926 if self.group_class is not None and kwargs.get("cls") is None: 

1927 if self.group_class is type: 

1928 kwargs["cls"] = type(self) 

1929 else: 

1930 kwargs["cls"] = self.group_class 

1931 

1932 def decorator(f: t.Callable[..., t.Any]) -> Group: 

1933 cmd: Group = group(*args, **kwargs)(f) 

1934 self.add_command(cmd) 

1935 return cmd 

1936 

1937 if func is not None: 

1938 return decorator(func) 

1939 

1940 return decorator 

1941 

1942 def result_callback(self, replace: bool = False) -> t.Callable[[F], F]: 

1943 """Adds a result callback to the command. By default if a 

1944 result callback is already registered this will chain them but 

1945 this can be disabled with the `replace` parameter. The result 

1946 callback is invoked with the return value of the subcommand 

1947 (or the list of return values from all subcommands if chaining 

1948 is enabled) as well as the parameters as they would be passed 

1949 to the main callback. 

1950 

1951 Example:: 

1952 

1953 @click.group() 

1954 @click.option('-i', '--input', default=23) 

1955 def cli(input): 

1956 return 42 

1957 

1958 @cli.result_callback() 

1959 def process_result(result, input): 

1960 return result + input 

1961 

1962 :param replace: if set to `True` an already existing result 

1963 callback will be removed. 

1964 

1965 .. versionchanged:: 8.0 

1966 Renamed from ``resultcallback``. 

1967 

1968 .. versionadded:: 3.0 

1969 """ 

1970 

1971 def decorator(f: F) -> F: 

1972 old_callback = self._result_callback 

1973 

1974 if old_callback is None or replace: 

1975 self._result_callback = f 

1976 return f 

1977 

1978 def function(value: t.Any, /, *args: t.Any, **kwargs: t.Any) -> t.Any: 

1979 inner = old_callback(value, *args, **kwargs) 

1980 return f(inner, *args, **kwargs) 

1981 

1982 self._result_callback = rv = update_wrapper(t.cast(F, function), f) 

1983 return rv # type: ignore[return-value] 

1984 

1985 return decorator 

1986 

1987 def get_command(self, ctx: Context, cmd_name: str) -> Command | None: 

1988 """Given a context and a command name, this returns a :class:`Command` 

1989 object if it exists or returns ``None``. 

1990 """ 

1991 return self.commands.get(cmd_name) 

1992 

1993 def list_commands(self, ctx: Context) -> list[str]: 

1994 """Returns a list of subcommand names in the order they should appear.""" 

1995 return sorted(self.commands) 

1996 

1997 def collect_usage_pieces(self, ctx: Context) -> list[str]: 

1998 rv = super().collect_usage_pieces(ctx) 

1999 rv.append(self.subcommand_metavar) 

2000 return rv 

2001 

2002 def format_options(self, ctx: Context, formatter: HelpFormatter) -> None: 

2003 super().format_options(ctx, formatter) 

2004 self.format_commands(ctx, formatter) 

2005 

2006 def format_commands(self, ctx: Context, formatter: HelpFormatter) -> None: 

2007 """Extra format methods for multi methods that adds all the commands 

2008 after the options. 

2009 """ 

2010 commands = [] 

2011 for subcommand in self.list_commands(ctx): 

2012 cmd = self.get_command(ctx, subcommand) 

2013 # What is this, the tool lied about a command. Ignore it 

2014 if cmd is None: 

2015 continue 

2016 if cmd.hidden: 

2017 continue 

2018 

2019 commands.append((subcommand, cmd)) 

2020 

2021 # allow for 3 times the default spacing 

2022 if len(commands): 

2023 limit = formatter.width - 6 - max(len(cmd[0]) for cmd in commands) 

2024 

2025 rows = [] 

2026 for subcommand, cmd in commands: 

2027 help = cmd.get_short_help_str(limit) 

2028 rows.append((subcommand, help)) 

2029 

2030 if rows: 

2031 with formatter.section(_("Commands")): 

2032 formatter.write_dl(rows) 

2033 

2034 def parse_args(self, ctx: Context, args: list[str]) -> list[str]: 

2035 if not args and self.no_args_is_help and not ctx.resilient_parsing: 

2036 raise NoArgsIsHelpError(ctx) 

2037 

2038 rest = super().parse_args(ctx, args) 

2039 

2040 if self.chain: 

2041 ctx._protected_args = rest 

2042 ctx.args = [] 

2043 elif rest: 

2044 ctx._protected_args, ctx.args = rest[:1], rest[1:] 

2045 

2046 return ctx.args 

2047 

2048 def invoke(self, ctx: Context) -> t.Any: 

2049 def _process_result(value: t.Any) -> t.Any: 

2050 if self._result_callback is not None: 

2051 value = ctx.invoke(self._result_callback, value, **ctx.params) 

2052 return value 

2053 

2054 if not ctx._protected_args: 

2055 if self.invoke_without_command: 

2056 # No subcommand was invoked, so the result callback is 

2057 # invoked with the group return value for regular 

2058 # groups, or an empty list for chained groups. 

2059 with ctx: 

2060 rv = super().invoke(ctx) 

2061 return _process_result([] if self.chain else rv) 

2062 ctx.fail(_("Missing command.")) 

2063 

2064 # Fetch args back out 

2065 args = [*ctx._protected_args, *ctx.args] 

2066 ctx.args = [] 

2067 ctx._protected_args = [] 

2068 

2069 # If we're not in chain mode, we only allow the invocation of a 

2070 # single command but we also inform the current context about the 

2071 # name of the command to invoke. 

2072 if not self.chain: 

2073 # Make sure the context is entered so we do not clean up 

2074 # resources until the result processor has worked. 

2075 with ctx: 

2076 cmd_name, cmd, args = self.resolve_command(ctx, args) 

2077 assert cmd is not None 

2078 ctx.invoked_subcommand = cmd_name 

2079 super().invoke(ctx) 

2080 sub_ctx = cmd.make_context(cmd_name, args, parent=ctx) 

2081 with sub_ctx: 

2082 return _process_result(sub_ctx.command.invoke(sub_ctx)) 

2083 

2084 # In chain mode we create the contexts step by step, but after the 

2085 # base command has been invoked. Because at that point we do not 

2086 # know the subcommands yet, the invoked subcommand attribute is 

2087 # set to ``*`` to inform the command that subcommands are executed 

2088 # but nothing else. 

2089 with ctx: 

2090 ctx.invoked_subcommand = "*" if args else None 

2091 super().invoke(ctx) 

2092 

2093 # Otherwise we make every single context and invoke them in a 

2094 # chain. In that case the return value to the result processor 

2095 # is the list of all invoked subcommand's results. 

2096 contexts = [] 

2097 while args: 

2098 cmd_name, cmd, args = self.resolve_command(ctx, args) 

2099 assert cmd is not None 

2100 sub_ctx = cmd.make_context( 

2101 cmd_name, 

2102 args, 

2103 parent=ctx, 

2104 allow_extra_args=True, 

2105 allow_interspersed_args=False, 

2106 ) 

2107 contexts.append(sub_ctx) 

2108 args, sub_ctx.args = sub_ctx.args, [] 

2109 

2110 rv = [] 

2111 for sub_ctx in contexts: 

2112 with sub_ctx: 

2113 rv.append(sub_ctx.command.invoke(sub_ctx)) 

2114 return _process_result(rv) 

2115 

2116 def resolve_command( 

2117 self, ctx: Context, args: list[str] 

2118 ) -> tuple[str | None, Command | None, list[str]]: 

2119 cmd_name = make_str(args[0]) 

2120 

2121 # Get the command 

2122 cmd = self.get_command(ctx, cmd_name) 

2123 

2124 # If we can't find the command but there is a normalization 

2125 # function available, we try with that one. 

2126 if cmd is None and ctx.token_normalize_func is not None: 

2127 cmd_name = ctx.token_normalize_func(cmd_name) 

2128 cmd = self.get_command(ctx, cmd_name) 

2129 

2130 # If we don't find the command we want to show an error message 

2131 # to the user that it was not provided. However, there is 

2132 # something else we should do: if the first argument looks like 

2133 # an option we want to kick off parsing again for arguments to 

2134 # resolve things like --help which now should go to the main 

2135 # place. 

2136 if cmd is None and not ctx.resilient_parsing: 

2137 if _split_opt(cmd_name)[0]: 

2138 self.parse_args(ctx, args) 

2139 raise NoSuchCommand(cmd_name, possibilities=self.commands, ctx=ctx) 

2140 return cmd_name if cmd else None, cmd, args[1:] 

2141 

2142 def shell_complete(self, ctx: Context, incomplete: str) -> list[CompletionItem]: 

2143 """Return a list of completions for the incomplete value. Looks 

2144 at the names of options, subcommands, and chained 

2145 multi-commands. 

2146 

2147 :param ctx: Invocation context for this command. 

2148 :param incomplete: Value being completed. May be empty. 

2149 

2150 .. versionadded:: 8.0 

2151 """ 

2152 from click.shell_completion import CompletionItem 

2153 

2154 results = [ 

2155 CompletionItem(name, help=command.get_short_help_str()) 

2156 for name, command in _complete_visible_commands(ctx, incomplete) 

2157 ] 

2158 results.extend(super().shell_complete(ctx, incomplete)) 

2159 return results 

2160 

2161 

2162class _MultiCommand(Group, metaclass=_FakeSubclassCheck): 

2163 """ 

2164 .. deprecated:: 8.2 

2165 Will be removed in Click 9.0. Use ``Group`` instead. 

2166 """ 

2167 

2168 

2169class CommandCollection(Group): 

2170 """A :class:`Group` that looks up subcommands on other groups. If a command 

2171 is not found on this group, each registered source is checked in order. 

2172 Parameters on a source are not added to this group, and a source's callback 

2173 is not invoked when invoking its commands. In other words, this "flattens" 

2174 commands in many groups into this one group. 

2175 

2176 :param name: The name of the group command. 

2177 :param sources: A list of :class:`Group` objects to look up commands from. 

2178 :param kwargs: Other arguments passed to :class:`Group`. 

2179 

2180 .. versionchanged:: 8.2 

2181 This is a subclass of ``Group``. Commands are looked up first on this 

2182 group, then each of its sources. 

2183 """ 

2184 

2185 sources: list[Group] 

2186 

2187 def __init__( 

2188 self, 

2189 name: str | None = None, 

2190 sources: list[Group] | None = None, 

2191 **kwargs: t.Any, 

2192 ) -> None: 

2193 super().__init__(name, **kwargs) 

2194 #: The list of registered groups. 

2195 self.sources = sources or [] 

2196 

2197 def add_source(self, group: Group) -> None: 

2198 """Add a group as a source of commands.""" 

2199 self.sources.append(group) 

2200 

2201 def get_command(self, ctx: Context, cmd_name: str) -> Command | None: 

2202 rv = super().get_command(ctx, cmd_name) 

2203 

2204 if rv is not None: 

2205 return rv 

2206 

2207 for source in self.sources: 

2208 rv = source.get_command(ctx, cmd_name) 

2209 

2210 if rv is not None: 

2211 if self.chain: 

2212 _check_nested_chain(self, cmd_name, rv) 

2213 

2214 return rv 

2215 

2216 return None 

2217 

2218 def list_commands(self, ctx: Context) -> list[str]: 

2219 rv: set[str] = set(super().list_commands(ctx)) 

2220 

2221 for source in self.sources: 

2222 rv.update(source.list_commands(ctx)) 

2223 

2224 return sorted(rv) 

2225 

2226 

2227def _check_iter(value: cabc.Iterable[V]) -> cabc.Iterator[V]: 

2228 """Check if the value is iterable but not a string. Raises a type 

2229 error, or return an iterator over the value. 

2230 """ 

2231 if isinstance(value, str): 

2232 raise TypeError 

2233 

2234 return iter(value) 

2235 

2236 

2237class Parameter(ABC): 

2238 r"""A parameter to a command comes in two versions: they are either 

2239 :class:`Option`\s or :class:`Argument`\s. Other subclasses are currently 

2240 not supported by design as some of the internals for parsing are 

2241 intentionally not finalized. 

2242 

2243 Some settings are supported by both options and arguments. 

2244 

2245 :param param_decls: the parameter declarations for this option or 

2246 argument. This is a list of flags or argument 

2247 names. 

2248 :param type: the type that should be used. Either a :class:`ParamType` 

2249 or a Python type. The latter is converted into the former 

2250 automatically if supported. 

2251 :param required: controls if this is optional or not. 

2252 :param default: the default value if omitted. This can also be a callable, 

2253 in which case it's invoked when the default is needed 

2254 without any arguments. 

2255 :param callback: A function to further process or validate the value 

2256 after type conversion. It is called as ``f(ctx, param, value)`` 

2257 and must return the value. It is called for all sources, 

2258 including prompts. 

2259 :param nargs: the number of arguments to match. If not ``1`` the return 

2260 value is a tuple instead of single value. The default for 

2261 nargs is ``1`` (except if the type is a tuple, then it's 

2262 the arity of the tuple). If ``nargs=-1``, all remaining 

2263 parameters are collected. 

2264 :param metavar: how the value is represented in the help page. 

2265 :param expose_value: if this is `True` then the value is passed onwards 

2266 to the command callback and stored on the context, 

2267 otherwise it's skipped. 

2268 :param is_eager: eager values are processed before non eager ones. This 

2269 should not be set for arguments or it will inverse the 

2270 order of processing. 

2271 :param envvar: environment variable(s) that are used to provide a default value for 

2272 this parameter. This can be a string or a sequence of strings. If a sequence is 

2273 given, only the first non-empty environment variable is used for the parameter. 

2274 :param shell_complete: A function that returns custom shell 

2275 completions. Used instead of the param's type completion if 

2276 given. Takes ``ctx, param, incomplete`` and must return a list 

2277 of :class:`~click.shell_completion.CompletionItem` or a list of 

2278 strings. 

2279 :param deprecated: If ``True`` or non-empty string, issues a message 

2280 indicating that the argument is deprecated and highlights 

2281 its deprecation in --help. The message can be customized 

2282 by using a string as the value. A deprecated parameter 

2283 cannot be required, a ValueError will be raised otherwise. 

2284 :param help: the help string. It is dedented and get a deprecated label if 

2285 appropriate. 

2286 

2287 .. versionchanged:: 8.5.1 

2288 New ``help`` parameter to replace the one from :class:`Option` and 

2289 :class:`Argument`. 

2290 

2291 .. versionchanged:: 8.2.0 

2292 Introduction of ``deprecated``. 

2293 

2294 .. versionchanged:: 8.2 

2295 Adding duplicate parameter names to a :class:`~click.core.Command` will 

2296 result in a ``UserWarning`` being shown. 

2297 

2298 .. versionchanged:: 8.2 

2299 Adding duplicate parameter names to a :class:`~click.core.Command` will 

2300 result in a ``UserWarning`` being shown. 

2301 

2302 .. versionchanged:: 8.0 

2303 ``process_value`` validates required parameters and bounded 

2304 ``nargs``, and invokes the parameter callback before returning 

2305 the value. This allows the callback to validate prompts. 

2306 ``full_process_value`` is removed. 

2307 

2308 .. versionchanged:: 8.0 

2309 ``autocompletion`` is renamed to ``shell_complete`` and has new 

2310 semantics described above. The old name is deprecated and will 

2311 be removed in 8.1, until then it will be wrapped to match the 

2312 new requirements. 

2313 

2314 .. versionchanged:: 8.0 

2315 For ``multiple=True, nargs>1``, the default must be a list of 

2316 tuples. 

2317 

2318 .. versionchanged:: 8.0 

2319 Setting a default is no longer required for ``nargs>1``, it will 

2320 default to ``None``. ``multiple=True`` or ``nargs=-1`` will 

2321 default to ``()``. 

2322 

2323 .. versionchanged:: 7.1 

2324 Empty environment variables are ignored rather than taking the 

2325 empty string value. This makes it possible for scripts to clear 

2326 variables if they can't unset them. 

2327 

2328 .. versionchanged:: 2.0 

2329 Changed signature for parameter callback to also be passed the 

2330 parameter. The old callback format will still work, but it will 

2331 raise a warning to give you a chance to migrate the code easier. 

2332 """ 

2333 

2334 param_type_name = "parameter" 

2335 

2336 name: str 

2337 opts: list[str] 

2338 secondary_opts: list[str] 

2339 # `Parameter.type` is annotated in `__init__` to avoid confusing mypy 

2340 required: bool 

2341 callback: t.Callable[[Context, Parameter, t.Any], t.Any] | None 

2342 nargs: int 

2343 multiple: bool 

2344 expose_value: bool 

2345 default: t.Any | t.Callable[[], t.Any] | None 

2346 _default_explicit: bool 

2347 is_eager: bool 

2348 metavar: str | None 

2349 envvar: str | cabc.Sequence[str] | None 

2350 _custom_shell_complete: ( 

2351 t.Callable[[Context, Parameter, str], list[CompletionItem] | list[str]] | None 

2352 ) 

2353 deprecated: bool | str 

2354 help: str | None 

2355 

2356 def __init__( 

2357 self, 

2358 param_decls: cabc.Sequence[str] | None = None, 

2359 type: types.ParamType[t.Any] | t.Any | None = None, 

2360 required: bool = False, 

2361 # XXX The default historically embed two concepts: 

2362 # - the declaration of a Parameter object carrying the default (handy to 

2363 # arbitrage the default value of coupled Parameters sharing the same 

2364 # self.name, like flag options), 

2365 # - and the actual value of the default. 

2366 # It is confusing and is the source of many issues discussed in: 

2367 # https://github.com/pallets/click/pull/3030 

2368 # In the future, we might think of splitting it in two, not unlike 

2369 # Option.is_flag and Option.flag_value: we could have something like 

2370 # Parameter.is_default and Parameter.default_value. 

2371 default: t.Any | t.Callable[[], t.Any] | None = UNSET, 

2372 callback: t.Callable[[Context, Parameter, t.Any], t.Any] | None = None, 

2373 nargs: int | None = None, 

2374 multiple: bool = False, 

2375 metavar: str | None = None, 

2376 expose_value: bool = True, 

2377 is_eager: bool = False, 

2378 envvar: str | cabc.Sequence[str] | None = None, 

2379 shell_complete: t.Callable[ 

2380 [Context, Parameter, str], list[CompletionItem] | list[str] 

2381 ] 

2382 | None = None, 

2383 deprecated: bool | str = False, 

2384 help: str | None = None, 

2385 ) -> None: 

2386 self.name, self.opts, self.secondary_opts = self._parse_decls( 

2387 param_decls or (), expose_value 

2388 ) 

2389 self.type: types.ParamType[t.Any] = types.convert_type(type, default) 

2390 

2391 # Default nargs to what the type tells us if we have that 

2392 # information available. 

2393 if nargs is None: 

2394 if self.type.is_composite: 

2395 nargs = self.type.arity 

2396 else: 

2397 nargs = 1 

2398 

2399 self.required = required 

2400 self.callback = callback 

2401 self.nargs = nargs 

2402 self.multiple = multiple 

2403 self.expose_value = expose_value 

2404 self.default = default 

2405 # Whether the user passed ``default`` explicitly to the constructor. 

2406 # Captured before any auto-derived default (like ``False`` for boolean 

2407 # flags in :class:`Option`) replaces the :data:`UNSET` sentinel, so it 

2408 # remains ``False`` when the default was inferred rather than chosen. 

2409 # Refs: https://github.com/pallets/click/issues/3403 

2410 self._default_explicit = default is not UNSET 

2411 self.is_eager = is_eager 

2412 self.metavar = metavar 

2413 self.envvar = envvar 

2414 self._custom_shell_complete = shell_complete 

2415 self.deprecated = deprecated 

2416 

2417 if help: 

2418 help = inspect.cleandoc(help) 

2419 

2420 if deprecated: 

2421 label = _format_deprecated_label(deprecated) 

2422 help = f"{help} {label}" if help else label 

2423 

2424 self.help = help 

2425 

2426 if __debug__: 

2427 if self.type.is_composite and nargs != self.type.arity: 

2428 raise ValueError( 

2429 f"'nargs' must be {self.type.arity} (or None) for" 

2430 f" type {self.type!r}, but it was {nargs}." 

2431 ) 

2432 

2433 if required and deprecated: 

2434 raise ValueError( 

2435 f"The {self.param_type_name} '{self.human_readable_name}' " 

2436 "is deprecated and still required. A deprecated " 

2437 f"{self.param_type_name} cannot be required." 

2438 ) 

2439 

2440 @staticmethod 

2441 def _hide_unset(value: t.Any) -> t.Any: 

2442 """Present the internal :data:`UNSET` sentinel as ``None`` at a boundary that 

2443 exposes a parameter's value (introspection, prompts), keeping the sentinel an 

2444 implementation detail. 

2445 """ 

2446 return None if value is UNSET else value 

2447 

2448 def to_info_dict(self) -> dict[str, t.Any]: 

2449 """Gather information that could be useful for a tool generating 

2450 user-facing documentation. 

2451 

2452 Use :meth:`click.Context.to_info_dict` to traverse the entire 

2453 CLI structure. 

2454 

2455 .. versionchanged:: 8.3.0 

2456 Returns ``None`` for the :attr:`default` if it was not set. 

2457 

2458 .. versionadded:: 8.0 

2459 """ 

2460 return { 

2461 "name": self.name, 

2462 "param_type_name": self.param_type_name, 

2463 "opts": self.opts, 

2464 "secondary_opts": self.secondary_opts, 

2465 "type": self.type.to_info_dict(), 

2466 "required": self.required, 

2467 "nargs": self.nargs, 

2468 "multiple": self.multiple, 

2469 "default": self._hide_unset(self.default), 

2470 "envvar": self.envvar, 

2471 "help": self.help, 

2472 } 

2473 

2474 def __repr__(self) -> str: 

2475 return f"<{self.__class__.__name__} {self.name}>" 

2476 

2477 @abstractmethod 

2478 def _parse_decls( 

2479 self, decls: cabc.Sequence[str], expose_value: bool 

2480 ) -> tuple[str, list[str], list[str]]: ... 

2481 

2482 def _check_name_is_usable(self, name: str, decls: cabc.Sequence[str]) -> None: 

2483 """Warn about a name Click 9.0 will refuse. 

2484 

2485 A name is refused for one of two reasons, and never for both: it is not 

2486 an identifier (``0-file``), or it is a keyword (``from``). 

2487 ``str.isidentifier`` accepts a keyword, so ``--from`` names a parameter 

2488 ``from`` today. No callback can declare that, which leaves the value 

2489 reachable through ``**kwargs`` alone. 

2490 

2491 Soft keywords such as ``match`` and ``type`` are contextual and name a 

2492 parameter fine, so :func:`keyword.iskeyword` passes them. 

2493 

2494 Both imports are local because neither :mod:`keyword` nor 

2495 :mod:`warnings` is on the allow-list ``tests/test_imports.py`` holds 

2496 Click's import footprint to. 

2497 

2498 .. versionadded:: 8.6.0 

2499 """ 

2500 import keyword 

2501 

2502 if keyword.iskeyword(name): 

2503 reason = "which is a Python keyword" 

2504 elif not name.isidentifier(): 

2505 reason = "which is not a valid Python identifier" 

2506 else: 

2507 return 

2508 

2509 import warnings 

2510 

2511 warnings.warn( 

2512 f"{self.param_type_name.capitalize()} {list(decls)!r} uses {name!r}" 

2513 f" as its name, {reason}. This is deprecated and will raise a" 

2514 " TypeError in Click 9.0.", 

2515 DeprecationWarning, 

2516 stacklevel=_outside_click_stacklevel(), 

2517 ) 

2518 

2519 @property 

2520 def human_readable_name(self) -> str: 

2521 """Returns the human readable name of this parameter. This is the 

2522 same as the name for options, but the metavar for arguments. 

2523 """ 

2524 return self.name 

2525 

2526 def make_metavar(self, ctx: Context) -> str: 

2527 if self.metavar is not None: 

2528 return self.metavar 

2529 

2530 metavar = self.type.get_metavar(param=self, ctx=ctx) 

2531 

2532 if metavar is None: 

2533 metavar = self.type.name.upper() 

2534 

2535 if self.nargs != 1: 

2536 metavar += "..." 

2537 

2538 return metavar 

2539 

2540 @t.overload 

2541 def get_default( 

2542 self, ctx: Context, call: t.Literal[True] = True 

2543 ) -> t.Any | None: ... 

2544 

2545 @t.overload 

2546 def get_default( 

2547 self, ctx: Context, call: bool = ... 

2548 ) -> t.Any | t.Callable[[], t.Any] | None: ... 

2549 

2550 def get_default( 

2551 self, ctx: Context, call: bool = True 

2552 ) -> t.Any | t.Callable[[], t.Any] | None: 

2553 """Get the default for the parameter. Tries 

2554 :meth:`Context.lookup_default` first, then the local default. 

2555 

2556 :param ctx: Current context. 

2557 :param call: If the default is a callable, call it. Disable to 

2558 return the callable instead. 

2559 

2560 .. versionchanged:: 8.0.2 

2561 Type casting is no longer performed when getting a default. 

2562 

2563 .. versionchanged:: 8.0.1 

2564 Type casting can fail in resilient parsing mode. Invalid 

2565 defaults will not prevent showing help text. 

2566 

2567 .. versionchanged:: 8.0 

2568 Looks at ``ctx.default_map`` first. 

2569 

2570 .. versionchanged:: 8.0 

2571 Added the ``call`` parameter. 

2572 """ 

2573 value = ctx.lookup_default(self.name, call=False) 

2574 

2575 if value is None and not ctx._default_map_has(self.name): 

2576 value = self.default 

2577 

2578 if call and callable(value): 

2579 value = value() 

2580 

2581 return value 

2582 

2583 @abstractmethod 

2584 def add_to_parser(self, parser: _OptionParser, ctx: Context) -> None: ... 

2585 

2586 def consume_value( 

2587 self, ctx: Context, opts: cabc.Mapping[str, t.Any] 

2588 ) -> tuple[t.Any, ParameterSource]: 

2589 """Returns the parameter value produced by the parser. 

2590 

2591 If the parser did not produce a value from user input, the value is either 

2592 sourced from the environment variable, the default map, or the parameter's 

2593 default value. In that order of precedence. 

2594 

2595 If no value is found, an internal sentinel value is returned. 

2596 

2597 :meta private: 

2598 """ 

2599 # Collect from the parse the value passed by the user to the CLI. 

2600 value = opts.get(self.name, UNSET) 

2601 # If the value is set, it means it was sourced from the command line by the 

2602 # parser, otherwise it left unset by default. 

2603 source = ( 

2604 ParameterSource.COMMANDLINE 

2605 if value is not UNSET 

2606 else ParameterSource.DEFAULT 

2607 ) 

2608 

2609 if value is UNSET: 

2610 envvar_value = self.value_from_envvar(ctx) 

2611 if envvar_value is not None: 

2612 value = envvar_value 

2613 source = ParameterSource.ENVIRONMENT 

2614 

2615 if value is UNSET: 

2616 default_map_value = ctx.lookup_default(self.name) 

2617 if default_map_value is not None or ctx._default_map_has(self.name): 

2618 value = default_map_value 

2619 source = ParameterSource.DEFAULT_MAP 

2620 

2621 # A string from default_map must be split for multi-value 

2622 # parameters, matching value_from_envvar behavior. 

2623 if isinstance(value, str) and self.nargs != 1: 

2624 value = self.type.split_envvar_value(value) 

2625 

2626 if value is UNSET: 

2627 default_value = self.get_default(ctx) 

2628 if default_value is not UNSET: 

2629 value = default_value 

2630 source = ParameterSource.DEFAULT 

2631 

2632 return value, source 

2633 

2634 def type_cast_value(self, ctx: Context, value: t.Any) -> t.Any: 

2635 """Convert and validate a value against the parameter's 

2636 :attr:`type`, :attr:`multiple`, and :attr:`nargs`. 

2637 """ 

2638 if value is None: 

2639 if self.multiple or self.nargs == -1: 

2640 return () 

2641 else: 

2642 return value 

2643 

2644 def check_iter(value: t.Any) -> cabc.Iterator[t.Any]: 

2645 try: 

2646 return _check_iter(value) 

2647 except TypeError: 

2648 # This should only happen when passing in args manually, 

2649 # the parser should construct an iterable when parsing 

2650 # the command line. 

2651 raise BadParameter( 

2652 _("Value must be an iterable."), ctx=ctx, param=self 

2653 ) from None 

2654 

2655 # Define the conversion function based on nargs and type. 

2656 

2657 if self.nargs == 1 or self.type.is_composite: 

2658 

2659 def convert(value: t.Any) -> t.Any: 

2660 return self.type(value, param=self, ctx=ctx) 

2661 

2662 elif self.nargs == -1: 

2663 

2664 def convert(value: t.Any) -> t.Any: # tuple[t.Any, ...] 

2665 return tuple(self.type(x, self, ctx) for x in check_iter(value)) 

2666 

2667 else: # nargs > 1 

2668 

2669 def convert(value: t.Any) -> t.Any: # tuple[t.Any, ...] 

2670 value = tuple(check_iter(value)) 

2671 

2672 if len(value) != self.nargs: 

2673 raise BadParameter( 

2674 ngettext( 

2675 "Takes {nargs} values but 1 was given.", 

2676 "Takes {nargs} values but {len} were given.", 

2677 len(value), 

2678 ).format(nargs=self.nargs, len=len(value)), 

2679 ctx=ctx, 

2680 param=self, 

2681 ) 

2682 

2683 return tuple(self.type(x, self, ctx) for x in value) 

2684 

2685 if self.multiple: 

2686 return tuple(convert(x) for x in check_iter(value)) 

2687 

2688 return convert(value) 

2689 

2690 def value_is_missing(self, value: t.Any) -> bool: 

2691 """A value is considered missing if: 

2692 

2693 - it is :attr:`UNSET`, 

2694 - or if it is an empty sequence while the parameter is suppose to have 

2695 non-single value (i.e. :attr:`nargs` is not ``1`` or :attr:`multiple` is 

2696 set). 

2697 

2698 :meta private: 

2699 """ 

2700 if value is UNSET: 

2701 return True 

2702 

2703 if (self.nargs != 1 or self.multiple) and value == (): 

2704 return True 

2705 

2706 return False 

2707 

2708 def process_value(self, ctx: Context, value: t.Any) -> t.Any: 

2709 """Process the value of this parameter: 

2710 

2711 1. Type cast the value using :meth:`type_cast_value`. 

2712 2. Check if the value is missing (see: :meth:`value_is_missing`), and raise 

2713 :exc:`MissingParameter` if it is required. 

2714 3. If a :attr:`callback` is set, call it to have the value replaced by the 

2715 result of the callback. If the value was not set, the callback receive 

2716 ``None``. This keep the legacy behavior as it was before the introduction of 

2717 the :attr:`UNSET` sentinel. 

2718 

2719 :meta private: 

2720 """ 

2721 # shelter `type_cast_value` from ever seeing an `UNSET` value by handling the 

2722 # cases in which `UNSET` gets special treatment explicitly at this layer 

2723 # 

2724 # Refs: 

2725 # https://github.com/pallets/click/issues/3069 

2726 if value is UNSET: 

2727 if self.multiple or self.nargs == -1: 

2728 value = () 

2729 else: 

2730 value = self.type_cast_value(ctx, value) 

2731 

2732 if self.required and self.value_is_missing(value): 

2733 raise MissingParameter(ctx=ctx, param=self) 

2734 

2735 if self.callback is not None: 

2736 # Legacy case: UNSET is not exposed directly to the callback, but converted 

2737 # to None. 

2738 if value is UNSET: 

2739 value = None 

2740 

2741 # Search for parameters with UNSET values in the context. 

2742 unset_keys = {k: None for k, v in ctx.params.items() if v is UNSET} 

2743 # No UNSET values, call the callback as usual. 

2744 if not unset_keys: 

2745 value = self.callback(ctx, self, value) 

2746 

2747 # Legacy case: provide a temporarily manipulated context to the callback 

2748 # to hide UNSET values as None. 

2749 # 

2750 # Refs: 

2751 # https://github.com/pallets/click/issues/3136 

2752 # https://github.com/pallets/click/pull/3137 

2753 else: 

2754 # Add another layer to the context stack to clearly hint that the 

2755 # context is temporarily modified. 

2756 with ctx: 

2757 # Update the context parameters to replace UNSET with None. 

2758 ctx.params.update(unset_keys) 

2759 # Feed these fake context parameters to the callback. 

2760 value = self.callback(ctx, self, value) 

2761 # Restore the UNSET values in the context parameters. 

2762 ctx.params.update( 

2763 { 

2764 k: UNSET 

2765 for k in unset_keys 

2766 # Only restore keys that are present and still None, in case 

2767 # the callback modified other parameters. 

2768 if k in ctx.params and ctx.params[k] is None 

2769 } 

2770 ) 

2771 

2772 return value 

2773 

2774 def resolve_envvar_value(self, ctx: Context) -> str | None: 

2775 """Returns the value found in the environment variable(s) attached to this 

2776 parameter. 

2777 

2778 Environment variables values are `always returned as strings 

2779 <https://docs.python.org/3/library/os.html#os.environ>`_. 

2780 

2781 This method returns ``None`` if: 

2782 

2783 - the :attr:`envvar` property is not set on the :class:`Parameter`, 

2784 - the environment variable is not found in the environment, 

2785 - the variable is found in the environment but its value is empty (i.e. the 

2786 environment variable is present but has an empty string). 

2787 

2788 If :attr:`envvar` is setup with multiple environment variables, 

2789 then only the first non-empty value is returned. 

2790 

2791 .. caution:: 

2792 

2793 The raw value extracted from the environment is not normalized and is 

2794 returned as-is. Any normalization or reconciliation is performed later by 

2795 the :class:`Parameter`'s :attr:`type`. 

2796 

2797 :meta private: 

2798 """ 

2799 if not self.envvar: 

2800 return None 

2801 

2802 if isinstance(self.envvar, str): 

2803 rv = os.environ.get(self.envvar) 

2804 

2805 if rv: 

2806 return rv 

2807 else: 

2808 for envvar in self.envvar: 

2809 rv = os.environ.get(envvar) 

2810 

2811 # Return the first non-empty value of the list of environment variables. 

2812 if rv: 

2813 return rv 

2814 # Else, absence of value is interpreted as an environment variable that 

2815 # is not set, so proceed to the next one. 

2816 

2817 return None 

2818 

2819 def value_from_envvar(self, ctx: Context) -> str | cabc.Sequence[str] | None: 

2820 """Process the raw environment variable string for this parameter. 

2821 

2822 Returns the string as-is or splits it into a sequence of strings if the 

2823 parameter is expecting multiple values (i.e. its :attr:`nargs` property is set 

2824 to a value other than ``1``). 

2825 

2826 :meta private: 

2827 """ 

2828 rv = self.resolve_envvar_value(ctx) 

2829 

2830 if rv is not None and self.nargs != 1: 

2831 return self.type.split_envvar_value(rv) 

2832 

2833 return rv 

2834 

2835 def handle_parse_result( 

2836 self, ctx: Context, opts: cabc.Mapping[str, t.Any], args: list[str] 

2837 ) -> tuple[t.Any, list[str]]: 

2838 """Process the value produced by the parser from user input. 

2839 

2840 Always process the value through the Parameter's :attr:`type`, wherever it 

2841 comes from. 

2842 

2843 If the parameter is deprecated, this method warn the user about it. But only if 

2844 the value has been explicitly set by the user (and as such, is not coming from 

2845 a default). 

2846 

2847 :meta private: 

2848 """ 

2849 # Capture the slot's existing state before we mutate 

2850 # ``_parameter_source`` so the write decision below can compare our 

2851 # incoming source against the source of the option that already wrote 

2852 # the slot (if any). 

2853 existing_value = ctx.params.get(self.name, UNSET) 

2854 existing_source = ctx.get_parameter_source(self.name) 

2855 existing_default_explicit = ctx._param_default_explicit.get(self.name, False) 

2856 

2857 with augment_usage_errors(ctx, param=self): 

2858 value, source = self.consume_value(ctx, opts) 

2859 

2860 # Record the source before processing so eager callbacks and type 

2861 # conversion can inspect it. Restored after arbitration if this 

2862 # option loses a feature-switch group. 

2863 ctx.set_parameter_source(self.name, source) 

2864 

2865 # Display a deprecation warning if necessary. 

2866 if ( 

2867 self.deprecated 

2868 and value is not UNSET 

2869 and source < ParameterSource.DEFAULT_MAP 

2870 ): 

2871 message = _( 

2872 "DeprecationWarning: The {param_type} {name!r} is deprecated." 

2873 "{extra_message}" 

2874 ).format( 

2875 param_type=self.param_type_name, 

2876 name=self.human_readable_name, 

2877 extra_message=_format_deprecated_suffix(self.deprecated), 

2878 ) 

2879 echo(style(message, fg="red"), err=True) 

2880 

2881 # Process the value through the parameter's type. 

2882 try: 

2883 value = self.process_value(ctx, value) 

2884 except Exception: 

2885 if not ctx.resilient_parsing: 

2886 raise 

2887 # In resilient parsing mode, we do not want to fail the command if the 

2888 # value is incompatible with the parameter type, so we reset the value 

2889 # to UNSET, which will be interpreted as a missing value. 

2890 value = UNSET 

2891 

2892 # Arbitrate the slot when several parameters target the same variable 

2893 # name (feature-switch groups). See: https://github.com/pallets/click/issues/3403 

2894 slot_empty = existing_value is UNSET 

2895 more_explicit = existing_source is not None and source < existing_source 

2896 same_source = existing_source is not None and source == existing_source 

2897 auto_would_downgrade_explicit = ( 

2898 same_source 

2899 and source == ParameterSource.DEFAULT 

2900 and existing_default_explicit 

2901 and not self._default_explicit 

2902 ) 

2903 is_winner = ( 

2904 slot_empty 

2905 or more_explicit 

2906 or (same_source and not auto_would_downgrade_explicit) 

2907 ) 

2908 

2909 if is_winner: 

2910 if self.expose_value: 

2911 ctx.params[self.name] = value 

2912 ctx._param_default_explicit[self.name] = self._default_explicit 

2913 elif existing_source is not None: 

2914 # Lost arbitration; restore the winning option's source. 

2915 ctx.set_parameter_source(self.name, existing_source) 

2916 # else: ctx.params[self.name] was populated by code that bypassed 

2917 # handle_parse_result (from another option's callback for example). Keep 

2918 # the provisional source recorded before process_value so downstream 

2919 # lookups don't return ``None``. 

2920 

2921 return value, args 

2922 

2923 def get_help_record(self, ctx: Context) -> tuple[str, str] | None: 

2924 return None 

2925 

2926 def get_usage_pieces(self, ctx: Context) -> list[str]: 

2927 return [] 

2928 

2929 def get_error_hint(self, ctx: Context | None) -> str: 

2930 """Get a stringified version of the param for use in error messages to 

2931 indicate which param caused the error. 

2932 

2933 .. versionchanged:: 8.4.0 

2934 ``ctx`` can be ``None``. 

2935 """ 

2936 hint_list = self.opts or [self.human_readable_name] 

2937 return " / ".join(f"'{x}'" for x in hint_list) 

2938 

2939 def shell_complete(self, ctx: Context, incomplete: str) -> list[CompletionItem]: 

2940 """Return a list of completions for the incomplete value. If a 

2941 ``shell_complete`` function was given during init, it is used. 

2942 Otherwise, the :attr:`type` 

2943 :meth:`~click.types.ParamType[t.Any].shell_complete` function is used. 

2944 

2945 :param ctx: Invocation context for this command. 

2946 :param incomplete: Value being completed. May be empty. 

2947 

2948 .. versionadded:: 8.0 

2949 """ 

2950 if self._custom_shell_complete is not None: 

2951 results = self._custom_shell_complete(ctx, self, incomplete) 

2952 

2953 if results and isinstance(results[0], str): 

2954 from click.shell_completion import CompletionItem 

2955 

2956 results = [CompletionItem(c) for c in results] 

2957 

2958 return t.cast("list[CompletionItem]", results) 

2959 

2960 return self.type.shell_complete(ctx, self, incomplete) 

2961 

2962 

2963class Option(Parameter): 

2964 """Options are usually optional values on the command line and 

2965 have some extra features that arguments don't have. 

2966 

2967 All other parameters are passed onwards to the parameter constructor. 

2968 

2969 :param show_default: Show the default value for this option in its 

2970 help text. Values are not shown by default, unless 

2971 :attr:`Context.show_default` is ``True``. If this value is a 

2972 string, it shows that string in parentheses instead of the 

2973 actual value. This is particularly useful for dynamic options. 

2974 For single option boolean flags, the default remains hidden if 

2975 its value is ``False``. 

2976 :param show_envvar: Controls if an environment variable should be 

2977 shown on the help page and error messages. 

2978 Normally, environment variables are not shown. 

2979 :param prompt: If set to ``True`` or a non empty string then the 

2980 user will be prompted for input. If set to ``True`` the prompt 

2981 will be the option name capitalized. A deprecated option cannot be 

2982 prompted. 

2983 :param confirmation_prompt: Prompt a second time to confirm the 

2984 value if it was prompted for. Can be set to a string instead of 

2985 ``True`` to customize the message. 

2986 :param prompt_required: If set to ``False``, the user will be 

2987 prompted for input only when the option was specified as a flag 

2988 without a value. 

2989 :param hide_input: If this is ``True`` then the input on the prompt 

2990 will be hidden from the user. This is useful for password input. 

2991 :param is_flag: forces this option to act as a flag. The default is 

2992 auto detection. 

2993 :param flag_value: which value should be used for this flag if it's 

2994 enabled. This is set to a boolean automatically if 

2995 the option string contains a slash to mark two options. 

2996 :param multiple: if this is set to `True` then the argument is accepted 

2997 multiple times and recorded. This is similar to ``nargs`` 

2998 in how it works but supports arbitrary number of 

2999 arguments. 

3000 :param count: this flag makes an option increment an integer. 

3001 :param allow_from_autoenv: if this is enabled then the value of this 

3002 parameter will be pulled from an environment 

3003 variable in case a prefix is defined on the 

3004 context. 

3005 :param help: the help string. 

3006 :param hidden: hide this option from help outputs. 

3007 :param attrs: Other command arguments described in :class:`Parameter`. 

3008 

3009 .. versionchanged:: 8.4.0 

3010 Non-basic ``flag_value`` types (not ``str``, ``int``, ``float``, or 

3011 ``bool``) are passed through unchanged instead of being stringified. 

3012 Previously, ``type=click.UNPROCESSED`` was required to preserve them. 

3013 

3014 .. versionchanged:: 8.2 

3015 ``envvar`` used with ``flag_value`` will always use the ``flag_value``, 

3016 previously it would use the value of the environment variable. 

3017 

3018 .. versionchanged:: 8.1 

3019 Help text indentation is cleaned here instead of only in the 

3020 ``@option`` decorator. 

3021 

3022 .. versionchanged:: 8.1 

3023 The ``show_default`` parameter overrides 

3024 ``Context.show_default``. 

3025 

3026 .. versionchanged:: 8.1 

3027 The default of a single option boolean flag is not shown if the 

3028 default value is ``False``. 

3029 

3030 .. versionchanged:: 8.0.1 

3031 ``type`` is detected from ``flag_value`` if given, for basic Python 

3032 types (``str``, ``int``, ``float``, ``bool``). 

3033 """ 

3034 

3035 param_type_name = "option" 

3036 

3037 prompt: str | None 

3038 confirmation_prompt: bool | str 

3039 prompt_required: bool 

3040 hide_input: bool 

3041 hidden: bool 

3042 

3043 _flag_needs_value: bool 

3044 is_flag: bool 

3045 flag_value: t.Any 

3046 type: types.ParamType[t.Any] 

3047 default: t.Any | t.Callable[[], t.Any] | None 

3048 

3049 count: bool 

3050 allow_from_autoenv: bool 

3051 show_default: bool | str | None 

3052 show_choices: bool 

3053 show_envvar: bool 

3054 

3055 def __init__( 

3056 self, 

3057 param_decls: cabc.Sequence[str] | None = None, 

3058 show_default: bool | str | None = None, 

3059 prompt: bool | str = False, 

3060 confirmation_prompt: bool | str = False, 

3061 prompt_required: bool = True, 

3062 hide_input: bool = False, 

3063 is_flag: bool | None = None, 

3064 flag_value: t.Any = UNSET, 

3065 multiple: bool = False, 

3066 count: bool = False, 

3067 allow_from_autoenv: bool = True, 

3068 type: types.ParamType[t.Any] | t.Any | None = None, 

3069 help: str | None = None, 

3070 hidden: bool = False, 

3071 show_choices: bool = True, 

3072 show_envvar: bool = False, 

3073 deprecated: bool | str = False, 

3074 **attrs: t.Any, 

3075 ) -> None: 

3076 super().__init__( 

3077 param_decls, 

3078 type=type, 

3079 multiple=multiple, 

3080 deprecated=deprecated, 

3081 help=help, 

3082 **attrs, 

3083 ) 

3084 

3085 # Phase 1: prompt-related attributes. ``_infer_flag_kind`` reads ``self.prompt`` 

3086 # and ``self.prompt_required`` so this must run first. 

3087 if prompt is True: 

3088 if not self.name: 

3089 raise TypeError("'name' is required with 'prompt=True'.") 

3090 

3091 prompt_text = self.name.replace("_", " ").capitalize() 

3092 elif prompt is False: 

3093 prompt_text = None 

3094 else: 

3095 prompt_text = prompt 

3096 

3097 self.prompt = prompt_text 

3098 self.confirmation_prompt = confirmation_prompt 

3099 self.prompt_required = prompt_required 

3100 self.hide_input = hide_input 

3101 self.hidden = hidden 

3102 

3103 # Phase 2: flag-kind inference. 

3104 self.is_flag, self._flag_needs_value = self._infer_flag_kind( 

3105 is_flag, flag_value 

3106 ) 

3107 

3108 # Phase 3: type inference. Override the type set by :meth:`Parameter.__init__` 

3109 # when this option is a flag or a count. 

3110 self.type = self._pick_type(type, flag_value, count, self.is_flag) 

3111 

3112 # Phase 4: store the raw ``flag_value`` and ``count`` settings. 

3113 # ``self.flag_value`` and ``self.default`` deliberately keep the :data:`UNSET` 

3114 # sentinel when the user didn't pass them. Auto-derived values are resolved 

3115 # lazily in :meth:`_resolve_lazy_default` and :attr:`flag_activation_value`. 

3116 # Keeping the raw values means ``is UNSET`` reliably answers "did the user pass 

3117 # this?": #3403 needs it for arbitration, and any future feature needing the 

3118 # same distinction can reuse it without reintroducing parallel "was it 

3119 # explicit?" tracking. 

3120 self.flag_value = flag_value 

3121 self.count = count 

3122 if count and self.default is UNSET: 

3123 self.default = 0 

3124 

3125 self.allow_from_autoenv = allow_from_autoenv 

3126 self.show_default = show_default 

3127 self.show_choices = show_choices 

3128 self.show_envvar = show_envvar 

3129 

3130 # Phase 5: validate. Raises on illegal kwarg combinations. 

3131 self._validate(prompt, deprecated) 

3132 

3133 @property 

3134 def is_bool_flag(self) -> bool: 

3135 """``True`` when this option is a flag with a boolean type. 

3136 

3137 Derived from :attr:`is_flag` and :attr:`type`; computed on access so it cannot 

3138 drift if a subclass replaces :attr:`type` after construction. 

3139 """ 

3140 return self.is_flag and isinstance(self.type, types.BoolParamType) 

3141 

3142 @property 

3143 def flag_activation_value(self) -> t.Any: 

3144 """Value the function receives when this flag is activated on the command line. 

3145 

3146 Resolves a missing :attr:`flag_value` to ``True`` for actual flag options and 

3147 ``None`` otherwise. Used by the parser bridge (:meth:`add_to_parser`) and the 

3148 runtime (:meth:`consume_value`) so :attr:`flag_value` can keep the :data:`UNSET` 

3149 sentinel for "did the user pass one?" introspection. 

3150 """ 

3151 if self.flag_value is UNSET: 

3152 return True if self.is_flag else None 

3153 return self.flag_value 

3154 

3155 def _infer_flag_kind( 

3156 self, is_flag: bool | None, flag_value: t.Any 

3157 ) -> tuple[bool, bool]: 

3158 """Resolve ``is_flag`` and the parser hint ``_flag_needs_value``. 

3159 

3160 Returns ``(is_flag, flag_needs_value)``, where ``_flag_needs_value`` tells the 

3161 parser this option is a flag that cannot be used standalone and needs a value. 

3162 The parser uses it to decide whether to treat the next CLI token as the flag's 

3163 value or as a new option. If ``prompt`` is enabled with 

3164 ``prompt_required=False``, it opens the door for an interactive value, hence the 

3165 initial condition. Ref: https://github.com/pallets/click/issues/3084 

3166 """ 

3167 needs_value = self.prompt is not None and not self.prompt_required 

3168 

3169 if is_flag is None: 

3170 # Implicitly a flag because flag_value was set. 

3171 if flag_value is not UNSET: 

3172 return True, needs_value 

3173 # Not a flag, but when used as a flag it shows a prompt. 

3174 if needs_value: 

3175 return False, needs_value 

3176 # Implicitly a flag because secondary options names were given. 

3177 if self.secondary_opts: 

3178 return True, needs_value 

3179 return False, needs_value 

3180 

3181 if is_flag is False and not needs_value: 

3182 # Explicit ``is_flag=False`` with a flag-like value/default still makes the 

3183 # option flag-shaped to the parser. 

3184 needs_value = flag_value is not UNSET or self.default is UNSET 

3185 

3186 return bool(is_flag), needs_value 

3187 

3188 def _pick_type( 

3189 self, 

3190 type_arg: t.Any, 

3191 flag_value: t.Any, 

3192 count: bool, 

3193 is_flag: bool, 

3194 ) -> types.ParamType[t.Any]: 

3195 """Pick the final :class:`ParamType` for this option. 

3196 

3197 :meth:`Parameter.__init__` already stored ``self.type`` from the explicit 

3198 ``type`` argument or from ``default``. This method either returns that as-is, or 

3199 overrides it for flag and count options (which are inferred from ``flag_value`` 

3200 rather than ``default``). 

3201 """ 

3202 if type_arg is not None: 

3203 return self.type 

3204 

3205 if count: 

3206 return types.IntRange(min=0) 

3207 

3208 if not is_flag: 

3209 return self.type 

3210 

3211 # A flag without a flag_value is a boolean flag. 

3212 if flag_value is UNSET or isinstance(flag_value, bool): 

3213 return types.BoolParamType() 

3214 

3215 guessed: types.ParamType[t.Any] = types.convert_type(None, flag_value) 

3216 if ( 

3217 isinstance(guessed, types.StringParamType) 

3218 and not isinstance(flag_value, str) 

3219 and flag_value is not None 

3220 ): 

3221 # The flag_value type couldn't be auto-detected (not str, int, float, or 

3222 # bool). Since flag_value is a programmer-provided Python object, not CLI 

3223 # input, pass it through unchanged instead of stringifying it. 

3224 return types.UNPROCESSED 

3225 return guessed 

3226 

3227 def _resolve_lazy_default(self, value: t.Any) -> t.Any: 

3228 """Apply lazy auto-derivations to a default-style value. 

3229 

3230 Shared between :meth:`get_default` (the runtime path) and :meth:`to_info_dict` 

3231 (the introspection path) so the two views cannot drift apart. Callables are 

3232 *not* invoked here: that is :meth:`get_default`'s responsibility. Rules: 

3233 

3234 * ``UNSET`` resolves to ``False`` for a non-required boolean flag, and to ``()`` 

3235 for a non-required, non-prompted multi flag. 

3236 * ``True`` resolves to :attr:`flag_value` for a non-boolean flag (the "activate 

3237 this flag by default" shorthand). Boolean flags keep ``True`` as a literal. 

3238 """ 

3239 if value is UNSET and self.is_flag: 

3240 if self.multiple and not self.required and not self.prompt: 

3241 return () 

3242 if self.is_bool_flag and not self.required: 

3243 return False 

3244 if value is True and self.is_flag and not self.is_bool_flag: 

3245 # Use ``flag_activation_value`` so an unset ``flag_value`` resolves to 

3246 # ``True`` (the bool-flag activation value) rather than leaking the 

3247 # :data:`UNSET` sentinel. 

3248 return self.flag_activation_value 

3249 return value 

3250 

3251 def _validate(self, prompt: bool | str, deprecated: bool | str) -> None: 

3252 """Raise :class:`TypeError` / :class:`ValueError` on illegal kwarg combinations. 

3253 

3254 Called once, after every other attribute has been assigned, so each check can 

3255 read the final state. 

3256 """ 

3257 if not __debug__: 

3258 return 

3259 if deprecated and prompt: 

3260 raise ValueError("`deprecated` options cannot use `prompt`.") 

3261 if self.nargs == -1: 

3262 raise TypeError("nargs=-1 is not supported for options.") 

3263 if not self.is_bool_flag and self.secondary_opts: 

3264 raise TypeError("Secondary flag is not valid for non-boolean flag.") 

3265 if self.is_bool_flag and self.hide_input and self.prompt is not None: 

3266 raise TypeError("'prompt' with 'hide_input' is not valid for boolean flag.") 

3267 if self.count: 

3268 if self.multiple: 

3269 raise TypeError("'count' is not valid with 'multiple'.") 

3270 if self.is_flag: 

3271 raise TypeError("'count' is not valid with 'is_flag'.") 

3272 

3273 def to_info_dict(self) -> dict[str, t.Any]: 

3274 """ 

3275 .. versionchanged:: 8.5.0 

3276 ``default`` and ``flag_value`` reflect the auto-derived values (``False`` 

3277 for unset boolean-flag defaults, ``True`` for unset boolean-flag activation 

3278 values, etc.) when no explicit value was passed, matching what the function 

3279 would receive at call time. 

3280 

3281 .. versionchanged:: 8.3.0 

3282 Returns ``None`` for the :attr:`flag_value` if it was not set. 

3283 """ 

3284 info_dict = super().to_info_dict() 

3285 info_dict.update( 

3286 default=self._hide_unset(self._resolve_lazy_default(self.default)), 

3287 prompt=self.prompt, 

3288 is_flag=self.is_flag, 

3289 flag_value=self.flag_activation_value, 

3290 count=self.count, 

3291 hidden=self.hidden, 

3292 ) 

3293 return info_dict 

3294 

3295 def get_default( 

3296 self, ctx: Context, call: bool = True 

3297 ) -> t.Any | t.Callable[[], t.Any] | None: 

3298 """Return the default value for this option. 

3299 

3300 Several auto-derived defaults are resolved lazily here rather than eagerly in 

3301 :meth:`__init__`. This keeps :attr:`default` raw at construction time, so 

3302 ``self.default is UNSET`` reliably answers "did the user pass a default?" for 

3303 feature-switch-group arbitration and for anything else that needs to distinguish 

3304 "absent" from a chosen value. The resolution rules live in 

3305 :meth:`_resolve_lazy_default`. 

3306 

3307 .. versionchanged:: 8.5.0 

3308 ``UNSET`` defaults for boolean and multi flags are now resolved here instead 

3309 of being coerced in :meth:`__init__`. Reading :attr:`default` directly 

3310 returns the user-supplied value (or ``UNSET`` if none was passed) rather 

3311 than the auto-derived one. 

3312 

3313 .. versionchanged:: 8.3.3 

3314 ``default=True`` is no longer substituted with ``flag_value`` for boolean 

3315 flags, fixing negative boolean flags like 

3316 ``flag_value=False, default=True``. 

3317 """ 

3318 raw = super().get_default(ctx, call=False) 

3319 value = self._resolve_lazy_default(raw) 

3320 # Only invoke the value as a callable when the lazy resolver passed it through 

3321 # unchanged. If the resolver substituted ``True`` -> :attr:`flag_value`, the 

3322 # result is the programmer-supplied ``flag_value`` (often a class or enum), 

3323 # which must NOT be instantiated here. See 

3324 # https://github.com/pallets/click/issues/3121. 

3325 if value is raw and call and callable(value): 

3326 value = value() 

3327 return value 

3328 

3329 def get_error_hint(self, ctx: Context | None) -> str: 

3330 result = super().get_error_hint(ctx) 

3331 if self.show_envvar and self.envvar is not None: 

3332 result += f" (env var: '{self.envvar}')" 

3333 return result 

3334 

3335 def _check_name_is_normalized(self, name: str, decls: cabc.Sequence[str]) -> None: 

3336 """Warn about an explicit name Click 9.0 will spell differently. 

3337 

3338 .. versionadded:: 8.6.0 

3339 """ 

3340 normalized = name.lower() 

3341 

3342 if normalized == name: 

3343 return 

3344 

3345 import warnings 

3346 

3347 warnings.warn( 

3348 f"Option {list(decls)!r} uses {name!r} as its name. Click 9.0" 

3349 f" lower cases an explicit name like any other declaration, naming" 

3350 f" {normalized!r} instead.", 

3351 DeprecationWarning, 

3352 stacklevel=_outside_click_stacklevel(), 

3353 ) 

3354 

3355 def _parse_decls( 

3356 self, decls: cabc.Sequence[str], expose_value: bool 

3357 ) -> tuple[str, list[str], list[str]]: 

3358 opts = [] 

3359 secondary_opts = [] 

3360 name = None 

3361 explicit_name = None 

3362 possible_names = [] 

3363 

3364 for decl in decls: 

3365 if decl.isidentifier(): 

3366 if name is not None: 

3367 raise TypeError(_("Name '{name}' defined twice").format(name=name)) 

3368 name = explicit_name = decl 

3369 else: 

3370 split_char = ";" if decl[:1] == "/" else "/" 

3371 if split_char in decl: 

3372 first, second = decl.split(split_char, 1) 

3373 first = first.rstrip() 

3374 if first: 

3375 possible_names.append(_split_opt(first)) 

3376 opts.append(first) 

3377 second = second.lstrip() 

3378 if second: 

3379 secondary_opts.append(second.lstrip()) 

3380 if first == second: 

3381 raise ValueError( 

3382 _( 

3383 "Boolean option {decl!r} cannot use the" 

3384 " same flag for true/false." 

3385 ).format(decl=decl) 

3386 ) 

3387 else: 

3388 possible_names.append(_split_opt(decl)) 

3389 opts.append(decl) 

3390 

3391 if name is None and possible_names: 

3392 possible_names.sort(key=lambda x: -len(x[0])) # group long options first 

3393 name = possible_names[0][1].replace("-", "_").lower() 

3394 

3395 if name is None or not name.isidentifier(): 

3396 if not expose_value: 

3397 self._check_name_is_usable(name or "", decls) 

3398 return "", opts, secondary_opts 

3399 

3400 raise TypeError( 

3401 _( 

3402 "Could not determine name for option with declarations {decls!r}" 

3403 ).format(decls=decls) 

3404 ) 

3405 

3406 if not opts and not secondary_opts: 

3407 raise TypeError( 

3408 _( 

3409 "No options defined but a name was passed ({name})." 

3410 " Did you mean to declare an argument instead? Did" 

3411 " you mean to pass '--{name}'?" 

3412 ).format(name=name) 

3413 ) 

3414 

3415 if explicit_name is not None: 

3416 self._check_name_is_normalized(explicit_name, decls) 

3417 

3418 self._check_name_is_usable(name, decls) 

3419 

3420 return name, opts, secondary_opts 

3421 

3422 def add_to_parser(self, parser: _OptionParser, ctx: Context) -> None: 

3423 if self.multiple: 

3424 action = "append" 

3425 elif self.count: 

3426 action = "count" 

3427 else: 

3428 action = "store" 

3429 

3430 if self.is_flag: 

3431 action = f"{action}_const" 

3432 

3433 if self.is_bool_flag and self.secondary_opts: 

3434 parser.add_option( 

3435 obj=self, opts=self.opts, dest=self.name, action=action, const=True 

3436 ) 

3437 parser.add_option( 

3438 obj=self, 

3439 opts=self.secondary_opts, 

3440 dest=self.name, 

3441 action=action, 

3442 const=False, 

3443 ) 

3444 else: 

3445 parser.add_option( 

3446 obj=self, 

3447 opts=self.opts, 

3448 dest=self.name, 

3449 action=action, 

3450 # ``flag_activation_value`` resolves UNSET to the right parser-store 

3451 # constant (``True`` for bool flags) so the raw :attr:`flag_value` 

3452 # can keep the sentinel. 

3453 const=self.flag_activation_value, 

3454 ) 

3455 else: 

3456 parser.add_option( 

3457 obj=self, 

3458 opts=self.opts, 

3459 dest=self.name, 

3460 action=action, 

3461 nargs=self.nargs, 

3462 ) 

3463 

3464 def get_help_spec(self, ctx: Context) -> str: 

3465 """Returns the left column of the option's help record: its spellings 

3466 and metavar, like ``-v, --verbose`` or ``-c, --config TEXT``. 

3467 

3468 Unlike :meth:`get_help_record`, the spec is produced even when the 

3469 option is :attr:`hidden`. 

3470 

3471 .. versionadded:: 8.5.1 

3472 """ 

3473 any_prefix_is_slash = False 

3474 

3475 def _write_opts(opts: cabc.Sequence[str]) -> str: 

3476 nonlocal any_prefix_is_slash 

3477 

3478 rv, any_slashes = join_options(opts) 

3479 

3480 if any_slashes: 

3481 any_prefix_is_slash = True 

3482 

3483 if not self.is_flag and not self.count: 

3484 rv += f" {self.make_metavar(ctx=ctx)}" 

3485 

3486 return rv 

3487 

3488 rv = [_write_opts(self.opts)] 

3489 

3490 if self.secondary_opts: 

3491 rv.append(_write_opts(self.secondary_opts)) 

3492 

3493 return ("; " if any_prefix_is_slash else " / ").join(rv) 

3494 

3495 def get_help_record(self, ctx: Context) -> tuple[str, str] | None: 

3496 if self.hidden: 

3497 return None 

3498 

3499 help = self.help or "" 

3500 

3501 extra = self.get_help_extra(ctx) 

3502 extra_items = [] 

3503 if "envvars" in extra: 

3504 extra_items.append( 

3505 _("env var: {var}").format(var=", ".join(extra["envvars"])) 

3506 ) 

3507 if "default" in extra: 

3508 extra_items.append(_("default: {default}").format(default=extra["default"])) 

3509 if "range" in extra: 

3510 extra_items.append(extra["range"]) 

3511 if "required" in extra: 

3512 extra_items.append(_(extra["required"])) 

3513 

3514 if extra_items: 

3515 extra_str = "; ".join(extra_items) 

3516 help = f"{help} [{extra_str}]" if help else f"[{extra_str}]" 

3517 

3518 return self.get_help_spec(ctx), help 

3519 

3520 def get_help_extra(self, ctx: Context) -> types.OptionHelpExtra: 

3521 extra: types.OptionHelpExtra = {} 

3522 

3523 if self.show_envvar: 

3524 envvar = self.envvar 

3525 

3526 if envvar is None: 

3527 if ( 

3528 self.allow_from_autoenv 

3529 and ctx.auto_envvar_prefix is not None 

3530 and self.name 

3531 ): 

3532 envvar = f"{ctx.auto_envvar_prefix}_{self.name.upper()}" 

3533 

3534 if envvar is not None: 

3535 if isinstance(envvar, str): 

3536 extra["envvars"] = (envvar,) 

3537 else: 

3538 extra["envvars"] = tuple(str(d) for d in envvar) 

3539 

3540 # Temporarily enable resilient parsing to avoid type casting 

3541 # failing for the default. Might be possible to extend this to 

3542 # help formatting in general. 

3543 resilient = ctx.resilient_parsing 

3544 ctx.resilient_parsing = True 

3545 

3546 try: 

3547 default_value = self.get_default(ctx, call=False) 

3548 finally: 

3549 ctx.resilient_parsing = resilient 

3550 

3551 show_default = False 

3552 show_default_is_str = False 

3553 

3554 if self.show_default is not None: 

3555 if isinstance(self.show_default, str): 

3556 show_default_is_str = show_default = True 

3557 else: 

3558 show_default = self.show_default 

3559 elif ctx.show_default is not None: 

3560 show_default = ctx.show_default 

3561 

3562 if show_default_is_str or ( 

3563 show_default and (default_value not in (None, UNSET)) 

3564 ): 

3565 if show_default_is_str: 

3566 default_string = f"({self.show_default})" 

3567 elif isinstance(default_value, (list, tuple)): 

3568 default_string = ", ".join(str(d) for d in default_value) 

3569 elif isinstance(default_value, enum.Enum): 

3570 default_string = default_value.name 

3571 elif inspect.isfunction(default_value): 

3572 default_string = _("(dynamic)") 

3573 elif self.is_bool_flag and self.secondary_opts: 

3574 # For boolean flags that have distinct True/False opts, 

3575 # use the opt without prefix instead of the value. 

3576 default_string = _split_opt( 

3577 (self.opts if default_value else self.secondary_opts)[0] 

3578 )[1] 

3579 elif self.is_bool_flag and not self.secondary_opts and not default_value: 

3580 default_string = "" 

3581 elif isinstance(default_value, str) and default_value == "": 

3582 default_string = '""' 

3583 else: 

3584 default_string = str(default_value) 

3585 

3586 if default_string: 

3587 extra["default"] = default_string 

3588 

3589 if ( 

3590 isinstance(self.type, types._NumberRangeBase) 

3591 # skip count with default range type 

3592 and not (self.count and self.type.min == 0 and self.type.max is None) 

3593 ): 

3594 range_str = self.type._describe_range() 

3595 

3596 if range_str: 

3597 extra["range"] = range_str 

3598 

3599 if self.required: 

3600 extra["required"] = "required" 

3601 

3602 return extra 

3603 

3604 def prompt_for_value(self, ctx: Context) -> t.Any: 

3605 """This is an alternative flow that can be activated in the full 

3606 value processing if a value does not exist. It will prompt the 

3607 user until a valid value exists and then returns the processed 

3608 value as result. 

3609 """ 

3610 assert self.prompt is not None 

3611 

3612 # Calculate the default before prompting anything to lock in the value before 

3613 # attempting any user interaction. 

3614 default = self.get_default(ctx) 

3615 

3616 # A boolean flag can use a simplified [y/n] confirmation prompt. 

3617 if self.is_bool_flag: 

3618 # If we have no boolean default, we force the user to explicitly provide 

3619 # one. 

3620 if default in (UNSET, None): 

3621 default = None 

3622 # Nothing prevent you to declare an option that is simultaneously: 

3623 # 1) auto-detected as a boolean flag, 

3624 # 2) allowed to prompt, and 

3625 # 3) still declare a non-boolean default. 

3626 # This forced casting into a boolean is necessary to align any non-boolean 

3627 # default to the prompt, which is going to be a [y/n]-style confirmation 

3628 # because the option is still a boolean flag. That way, instead of [y/n], 

3629 # we get [Y/n] or [y/N] depending on the truthy value of the default. 

3630 # Refs: https://github.com/pallets/click/pull/3030#discussion_r2289180249 

3631 else: 

3632 default = bool(default) 

3633 return confirm(self.prompt, default) 

3634 

3635 # If show_default is given, provide this to `prompt` as well, 

3636 # otherwise we use `prompt`'s default behavior 

3637 prompt_kwargs: t.Any = {} 

3638 if self.show_default is not None: 

3639 prompt_kwargs["show_default"] = self.show_default 

3640 

3641 return prompt( 

3642 self.prompt, 

3643 # Use ``None`` to inform the prompt() function to reiterate until a valid 

3644 # value is provided by the user if we have no default. 

3645 default=self._hide_unset(default), 

3646 type=self.type, 

3647 hide_input=self.hide_input, 

3648 show_choices=self.show_choices, 

3649 confirmation_prompt=self.confirmation_prompt, 

3650 value_proc=lambda x: self.process_value(ctx, x), 

3651 **prompt_kwargs, 

3652 ) 

3653 

3654 def resolve_envvar_value(self, ctx: Context) -> str | None: 

3655 """:class:`Option` resolves its environment variable the same way as 

3656 :func:`Parameter.resolve_envvar_value`, but it also supports 

3657 :attr:`Context.auto_envvar_prefix`. If we could not find an environment from 

3658 the :attr:`envvar` property, we fallback on :attr:`Context.auto_envvar_prefix` 

3659 to build dynamiccaly the environment variable name using the 

3660 :python:`{ctx.auto_envvar_prefix}_{self.name.upper()}` template. 

3661 

3662 :meta private: 

3663 """ 

3664 rv = super().resolve_envvar_value(ctx) 

3665 

3666 if rv is not None: 

3667 return rv 

3668 

3669 if self.allow_from_autoenv and ctx.auto_envvar_prefix is not None and self.name: 

3670 envvar = f"{ctx.auto_envvar_prefix}_{self.name.upper()}" 

3671 rv = os.environ.get(envvar) 

3672 

3673 if rv: 

3674 return rv 

3675 

3676 return None 

3677 

3678 def value_from_envvar(self, ctx: Context) -> t.Any: 

3679 """For :class:`Option`, this method processes the raw environment variable 

3680 string the same way as :func:`Parameter.value_from_envvar` does. 

3681 

3682 But in the case of non-boolean flags, the value is analyzed to determine if the 

3683 flag is activated or not, and returns a boolean of its activation, or the 

3684 :attr:`flag_value` if the latter is set. 

3685 

3686 This method also takes care of repeated options (i.e. options with 

3687 :attr:`multiple` set to ``True``). 

3688 

3689 :meta private: 

3690 """ 

3691 rv = self.resolve_envvar_value(ctx) 

3692 

3693 # Absent environment variable or an empty string is interpreted as unset. 

3694 if rv is None: 

3695 return None 

3696 

3697 # Non-boolean flags are more liberal in what they accept. But a flag being a 

3698 # flag, its envvar value still needs to be analyzed to determine if the flag is 

3699 # activated or not. 

3700 if self.is_flag and not self.is_bool_flag: 

3701 # An exact match against ``flag_value`` (a non-bool flag always has one 

3702 # explicitly set) returns it directly. Otherwise the value is analyzed as a 

3703 # boolean: a truthy reading activates the flag and the function receives 

3704 # ``flag_value``; a falsy reading produces ``False``; an unrecognized 

3705 # reading falls through as ``None``. Folding the substitution here means 

3706 # :meth:`consume_value` no longer has to repeat it in a source-checked 

3707 # branch. 

3708 if rv == self.flag_value: 

3709 return self.flag_value 

3710 parsed = types.BoolParamType.str_to_bool(rv) 

3711 if parsed is None: 

3712 return None 

3713 return self.flag_value if parsed else False 

3714 

3715 # Split the envvar value if it is allowed to be repeated. 

3716 value_depth = (self.nargs != 1) + bool(self.multiple) 

3717 if value_depth > 0: 

3718 multi_rv = self.type.split_envvar_value(rv) 

3719 if self.multiple and self.nargs != 1: 

3720 multi_rv = batch(multi_rv, self.nargs) # type: ignore[assignment] 

3721 

3722 return multi_rv 

3723 

3724 return rv 

3725 

3726 def consume_value( 

3727 self, ctx: Context, opts: cabc.Mapping[str, Parameter] 

3728 ) -> tuple[t.Any, ParameterSource]: 

3729 """For :class:`Option`, the value can be collected from an interactive prompt 

3730 if the option is a flag that needs a value (and the :attr:`prompt` property is 

3731 set). 

3732 

3733 Additionally, this method handles flag option that are activated without a 

3734 value, in which case the :attr:`flag_value` is returned. 

3735 

3736 :meta private: 

3737 """ 

3738 value, source = super().consume_value(ctx, opts) 

3739 

3740 # The parser emits a sentinel when a flag is allowed to be used without a value. 

3741 # Resolve it to a prompt or to the activation value depending on the option's 

3742 # configuration. 

3743 if value is FLAG_NEEDS_VALUE: 

3744 # If the option allows for a prompt, start an interaction with the user. 

3745 if self.prompt is not None and not ctx.resilient_parsing: 

3746 value = self.prompt_for_value(ctx) 

3747 source = ParameterSource.PROMPT 

3748 # Else the flag takes its activation value (resolves UNSET). 

3749 else: 

3750 value = self.flag_activation_value 

3751 source = ParameterSource.COMMANDLINE 

3752 

3753 # Re-interpret a multiple option that the parser sent through as a list still 

3754 # containing the FLAG_NEEDS_VALUE sentinel, replacing each occurrence with the 

3755 # activation value. 

3756 elif ( 

3757 self.multiple 

3758 and value is not UNSET 

3759 and isinstance(value, cabc.Iterable) 

3760 and source < ParameterSource.DEFAULT_MAP 

3761 and any(v is FLAG_NEEDS_VALUE for v in value) 

3762 ): 

3763 value = [ 

3764 self.flag_activation_value if v is FLAG_NEEDS_VALUE else v 

3765 for v in value 

3766 ] 

3767 source = ParameterSource.COMMANDLINE 

3768 

3769 # The value wasn't set, or used the param's default, prompt for one to the user 

3770 # if prompting is enabled. 

3771 elif ( 

3772 (value is UNSET or source >= ParameterSource.DEFAULT_MAP) 

3773 and self.prompt is not None 

3774 and (self.required or self.prompt_required) 

3775 and not ctx.resilient_parsing 

3776 ): 

3777 value = self.prompt_for_value(ctx) 

3778 source = ParameterSource.PROMPT 

3779 

3780 return value, source 

3781 

3782 def process_value(self, ctx: Context, value: t.Any) -> t.Any: 

3783 # process_value has to be overridden on Options in order to capture 

3784 # `value == UNSET` cases before `type_cast_value()` gets called. 

3785 # 

3786 # Refs: 

3787 # https://github.com/pallets/click/issues/3069 

3788 if self.is_flag and not self.required and self.is_bool_flag and value is UNSET: 

3789 value = False 

3790 

3791 if self.callback is not None: 

3792 value = self.callback(ctx, self, value) 

3793 

3794 return value 

3795 

3796 # in the normal case, rely on Parameter.process_value 

3797 return super().process_value(ctx, value) 

3798 

3799 

3800class Argument(Parameter): 

3801 """Arguments are positional parameters to a command. They generally 

3802 provide fewer features than options but can have infinite ``nargs`` 

3803 and are required by default. 

3804 

3805 All parameters are passed onwards to the constructor of :class:`Parameter`. 

3806 

3807 :param help: the help string. 

3808 

3809 .. versionchanged:: 8.5.0 

3810 Added the ``help`` parameter. 

3811 """ 

3812 

3813 param_type_name = "argument" 

3814 

3815 def __init__( 

3816 self, 

3817 param_decls: cabc.Sequence[str], 

3818 required: bool | None = None, 

3819 help: str | None = None, 

3820 **attrs: t.Any, 

3821 ) -> None: 

3822 # Auto-detect the requirement status of the argument if not explicitly set. 

3823 if required is None: 

3824 # The argument gets automatically required if it has no explicit default 

3825 # value set and is setup to match at least one value. 

3826 if attrs.get("default", UNSET) is UNSET: 

3827 required = attrs.get("nargs", 1) > 0 

3828 # If the argument has a default value, it is not required. 

3829 else: 

3830 required = False 

3831 

3832 if "multiple" in attrs: 

3833 raise TypeError("__init__() got an unexpected keyword argument 'multiple'.") 

3834 

3835 super().__init__(param_decls, required=required, help=help, **attrs) 

3836 

3837 @property 

3838 def human_readable_name(self) -> str: 

3839 if self.metavar is not None: 

3840 return self.metavar 

3841 return self.name.upper() 

3842 

3843 def make_metavar(self, ctx: Context) -> str: 

3844 if self.metavar is not None: 

3845 return self.metavar 

3846 var = self.type.get_metavar(param=self, ctx=ctx) 

3847 if not var: 

3848 var = self.name.upper() 

3849 # Types like ``Choice`` and ``DateTime`` already surround their metavar 

3850 # with square brackets to enumerate the allowed values. Reuse those 

3851 # outer brackets as the optional-argument indicator instead of wrapping 

3852 # the metavar in a second pair, which would produce ``[[a|b|c]]``. 

3853 already_bracketed = var.startswith("[") and var.endswith("]") 

3854 if self.deprecated: 

3855 var += "!" 

3856 if not self.required and not already_bracketed: 

3857 var = f"[{var}]" 

3858 if self.nargs != 1: 

3859 var += "..." 

3860 return var 

3861 

3862 def _parse_decls( 

3863 self, decls: cabc.Sequence[str], expose_value: bool 

3864 ) -> tuple[str, list[str], list[str]]: 

3865 if not decls: 

3866 if not expose_value: 

3867 self._check_name_is_usable("", decls) 

3868 return "", [], [] 

3869 raise TypeError("Argument is marked as exposed, but does not have a name.") 

3870 if len(decls) == 1: 

3871 name = arg = decls[0] 

3872 name = name.replace("-", "_").lower() 

3873 else: 

3874 raise TypeError( 

3875 _( 

3876 "Arguments take exactly one parameter declaration, got" 

3877 " {length}: {decls}." 

3878 ).format(length=len(decls), decls=decls) 

3879 ) 

3880 self._check_name_is_usable(name, decls) 

3881 return name, [arg], [] 

3882 

3883 def get_usage_pieces(self, ctx: Context) -> list[str]: 

3884 return [self.make_metavar(ctx)] 

3885 

3886 def get_help_record(self, ctx: Context) -> tuple[str, str]: 

3887 """Returns the argument's help row: its metavar and its help text. 

3888 

3889 Unlike :meth:`Option.get_help_record`, this never returns ``None``. An 

3890 argument cannot be hidden, so an undocumented one still gets a row, with 

3891 an empty description. 

3892 

3893 .. versionchanged:: 8.5.1 

3894 Always returns a tuple. It used to return ``None`` when ``help`` was 

3895 not set. 

3896 """ 

3897 return self.make_metavar(ctx), self.help or "" 

3898 

3899 def get_error_hint(self, ctx: Context | None) -> str: 

3900 if ctx is not None: 

3901 return f"'{self.make_metavar(ctx)}'" 

3902 return f"'{self.human_readable_name}'" 

3903 

3904 def add_to_parser(self, parser: _OptionParser, ctx: Context) -> None: 

3905 parser.add_argument(dest=self.name, nargs=self.nargs, obj=self) 

3906 

3907 

3908def __getattr__(name: str) -> object: 

3909 import warnings 

3910 

3911 if name == "BaseCommand": 

3912 warnings.warn( 

3913 "'BaseCommand' is deprecated and will be removed in Click 9.0. Use" 

3914 " 'Command' instead.", 

3915 DeprecationWarning, 

3916 stacklevel=2, 

3917 ) 

3918 return _BaseCommand 

3919 

3920 if name == "MultiCommand": 

3921 warnings.warn( 

3922 "'MultiCommand' is deprecated and will be removed in Click 9.0. Use" 

3923 " 'Group' instead.", 

3924 DeprecationWarning, 

3925 stacklevel=2, 

3926 ) 

3927 return _MultiCommand 

3928 

3929 raise AttributeError(name)