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

1436 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(skip: cabc.Container[str] = ()) -> int: 

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

110 

111 :param skip: Other module names to walk past. ``abc`` is one: it sits 

112 between ``__init_subclass__`` and the ``class`` statement that the 

113 warning must point at. 

114 

115 .. versionadded:: 8.6.0 

116 """ 

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

118 level = 1 

119 

120 while frame is not None: 

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

122 

123 if module != "click" and not module.startswith("click.") and module not in skip: 

124 return level 

125 

126 frame = frame.f_back 

127 level += 1 

128 

129 return level 

130 

131 

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

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

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

135 if isinstance(deprecated, str): 

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

137 return f"({label})" 

138 

139 

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

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

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

143 """ 

144 if isinstance(deprecated, str): 

145 return f" {deprecated}" 

146 return "" 

147 

148 

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

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

151 

152 

153@contextmanager 

154def augment_usage_errors( 

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

156) -> cabc.Generator[None]: 

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

158 try: 

159 yield 

160 except BadParameter as e: 

161 if e.ctx is None: 

162 e.ctx = ctx 

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

164 e.param = param 

165 raise 

166 except UsageError as e: 

167 if e.ctx is None: 

168 e.ctx = ctx 

169 raise 

170 

171 

172def iter_params_for_processing( 

173 invocation_order: cabc.Sequence[Parameter], 

174 declaration_order: cabc.Sequence[Parameter], 

175) -> list[Parameter]: 

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

177 

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

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

180 

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

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

183 

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

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

186 """ 

187 

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

189 try: 

190 idx: float = invocation_order.index(item) 

191 except ValueError: 

192 idx = float("inf") 

193 

194 return not item.is_eager, idx 

195 

196 return sorted(declaration_order, key=sort_key) 

197 

198 

199class ParameterSource(enum.IntEnum): 

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

201 parameter's value. 

202 

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

204 source for a parameter by name. 

205 

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

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

208 

209 .. code-block:: python 

210 

211 source = ctx.get_parameter_source("port") 

212 if source < click.ParameterSource.DEFAULT_MAP: 

213 ... # value was explicitly set 

214 

215 .. versionchanged:: 8.3.3 

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

217 least explicit. Supports comparison operators. 

218 

219 .. versionchanged:: 8.0 

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

221 

222 .. versionchanged:: 8.0 

223 Added the ``PROMPT`` value. 

224 """ 

225 

226 PROMPT = enum.auto() 

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

228 COMMANDLINE = enum.auto() 

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

230 ENVIRONMENT = enum.auto() 

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

232 DEFAULT_MAP = enum.auto() 

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

234 DEFAULT = enum.auto() 

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

236 

237 

238class Context: 

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

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

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

242 

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

244 control special execution features such as reading data from 

245 environment variables. 

246 

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

248 :meth:`close` on teardown. 

249 

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

251 :param parent: the parent context. 

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

253 is the most descriptive name for the script or 

254 command. For the toplevel script it is usually 

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

256 the name of the script. 

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

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

259 variables. If this is `None` then reading 

260 from environment variables is disabled. This 

261 does not affect manually set environment 

262 variables which are always read. 

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

264 for parameters. 

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

266 inherit from parent context. If no context 

267 defines the terminal width then auto 

268 detection will be applied. 

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

270 Click (this currently only affects help 

271 pages). This defaults to 80 characters if 

272 not overridden. In other words: even if the 

273 terminal is larger than that, Click will not 

274 format things wider than 80 characters by 

275 default. In addition to that, formatters might 

276 add some safety mapping on the right. 

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

278 parse without any interactivity or callback 

279 invocation. Default values will also be 

280 ignored. This is useful for implementing 

281 things such as completion support. 

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

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

284 kept on the context. The default is to inherit 

285 from the command. 

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

287 and arguments cannot be mixed. The 

288 default is to inherit from the command. 

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

290 not know and keeps them for later 

291 processing. 

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

293 the default help parameter is named. The 

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

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

296 normalize tokens (options, choices, 

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

298 implement case insensitive behavior. 

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

300 default is autodetection. This is only needed if ANSI 

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

302 default not the case. This for instance would affect 

303 help output. 

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

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

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

307 specific command. 

308 

309 .. versionchanged:: 8.2 

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

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

312 

313 .. versionchanged:: 8.1 

314 The ``show_default`` parameter is overridden by 

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

316 

317 .. versionchanged:: 8.0 

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

319 parent context. 

320 

321 .. versionchanged:: 7.1 

322 Added the ``show_default`` parameter. 

323 

324 .. versionchanged:: 4.0 

325 Added the ``color``, ``ignore_unknown_options``, and 

326 ``max_content_width`` parameters. 

327 

328 .. versionchanged:: 3.0 

329 Added the ``allow_extra_args`` and ``allow_interspersed_args`` 

330 parameters. 

331 

332 .. versionchanged:: 2.0 

333 Added the ``resilient_parsing``, ``help_option_names``, and 

334 ``token_normalize_func`` parameters. 

335 """ 

336 

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

338 #: 

339 #: .. versionadded:: 8.0 

340 formatter_class: type[HelpFormatter] = HelpFormatter 

341 

342 parent: Context | None 

343 command: Command 

344 info_name: str | None 

345 params: dict[str, t.Any] 

346 args: list[str] 

347 _protected_args: list[str] 

348 _opt_prefixes: set[str] 

349 obj: t.Any 

350 _meta: dict[str, t.Any] 

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

352 invoked_subcommand: str | None 

353 terminal_width: int | None 

354 max_content_width: int | None 

355 allow_extra_args: bool 

356 allow_interspersed_args: bool 

357 ignore_unknown_options: bool 

358 help_option_names: list[str] 

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

360 resilient_parsing: bool 

361 auto_envvar_prefix: str | None 

362 color: bool | None 

363 show_default: bool | None 

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

365 _depth: int 

366 _parameter_source: dict[str, ParameterSource] 

367 _param_default_explicit: dict[str, bool] 

368 _exit_stack: ExitStack 

369 

370 def __init__( 

371 self, 

372 command: Command, 

373 parent: Context | None = None, 

374 info_name: str | None = None, 

375 obj: t.Any | None = None, 

376 auto_envvar_prefix: str | None = None, 

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

378 terminal_width: int | None = None, 

379 max_content_width: int | None = None, 

380 resilient_parsing: bool = False, 

381 allow_extra_args: bool | None = None, 

382 allow_interspersed_args: bool | None = None, 

383 ignore_unknown_options: bool | None = None, 

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

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

386 color: bool | None = None, 

387 show_default: bool | None = None, 

388 ) -> None: 

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

390 self.parent = parent 

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

392 self.command = command 

393 #: the descriptive information name 

394 self.info_name = info_name 

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

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

397 self.params = {} 

398 #: the leftover arguments. 

399 self.args = [] 

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

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

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

403 #: to implement nested parsing. 

404 self._protected_args = [] 

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

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

407 

408 if obj is None and parent is not None: 

409 obj = parent.obj 

410 

411 #: the user object stored. 

412 self.obj = obj 

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

414 

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

416 if ( 

417 default_map is None 

418 and info_name is not None 

419 and parent is not None 

420 and parent.default_map is not None 

421 ): 

422 default_map = parent.default_map.get(info_name) 

423 

424 self.default_map = default_map 

425 

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

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

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

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

430 #: the name of the subcommand to execute. 

431 #: 

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

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

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

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

436 self.invoked_subcommand = None 

437 

438 if terminal_width is None and parent is not None: 

439 terminal_width = parent.terminal_width 

440 

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

442 self.terminal_width = terminal_width 

443 

444 if max_content_width is None and parent is not None: 

445 max_content_width = parent.max_content_width 

446 

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

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

449 self.max_content_width = max_content_width 

450 

451 if allow_extra_args is None: 

452 allow_extra_args = command.allow_extra_args 

453 

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

455 #: fail on parsing. 

456 #: 

457 #: .. versionadded:: 3.0 

458 self.allow_extra_args = allow_extra_args 

459 

460 if allow_interspersed_args is None: 

461 allow_interspersed_args = command.allow_interspersed_args 

462 

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

464 #: options or not. 

465 #: 

466 #: .. versionadded:: 3.0 

467 self.allow_interspersed_args = allow_interspersed_args 

468 

469 if ignore_unknown_options is None: 

470 ignore_unknown_options = command.ignore_unknown_options 

471 

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

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

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

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

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

477 #: forward all arguments. 

478 #: 

479 #: .. versionadded:: 4.0 

480 self.ignore_unknown_options = ignore_unknown_options 

481 

482 if help_option_names is None: 

483 if parent is not None: 

484 help_option_names = parent.help_option_names 

485 else: 

486 help_option_names = ["--help"] 

487 

488 #: The names for the help options. 

489 self.help_option_names = help_option_names 

490 

491 if token_normalize_func is None and parent is not None: 

492 token_normalize_func = parent.token_normalize_func 

493 

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

495 #: options, choices, commands etc. 

496 self.token_normalize_func = token_normalize_func 

497 

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

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

500 #: will be ignored. Useful for completion. 

501 self.resilient_parsing = resilient_parsing 

502 

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

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

505 # prefix automatically. 

506 if auto_envvar_prefix is None: 

507 if ( 

508 parent is not None 

509 and parent.auto_envvar_prefix is not None 

510 and self.info_name is not None 

511 ): 

512 auto_envvar_prefix = ( 

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

514 ) 

515 else: 

516 auto_envvar_prefix = auto_envvar_prefix.upper() 

517 

518 if auto_envvar_prefix is not None: 

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

520 

521 self.auto_envvar_prefix = auto_envvar_prefix 

522 

523 if color is None and parent is not None: 

524 color = parent.color 

525 

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

527 self.color = color 

528 

529 if show_default is None and parent is not None: 

530 show_default = parent.show_default 

531 

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

533 self.show_default = show_default 

534 

535 self._close_callbacks = [] 

536 self._depth = 0 

537 self._parameter_source = {} 

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

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

540 # tie-break feature-switch groups where multiple options share a parameter name 

541 # and both fall back to their default value. 

542 self._param_default_explicit = {} 

543 self._exit_stack = ExitStack() 

544 

545 @property 

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

547 import warnings 

548 

549 warnings.warn( 

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

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

552 DeprecationWarning, 

553 stacklevel=2, 

554 ) 

555 return self._protected_args 

556 

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

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

559 user-facing documentation. This traverses the entire CLI 

560 structure. 

561 

562 .. code-block:: python 

563 

564 with Context(cli) as ctx: 

565 info = ctx.to_info_dict() 

566 

567 .. versionadded:: 8.0 

568 """ 

569 return { 

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

571 "info_name": self.info_name, 

572 "allow_extra_args": self.allow_extra_args, 

573 "allow_interspersed_args": self.allow_interspersed_args, 

574 "ignore_unknown_options": self.ignore_unknown_options, 

575 "auto_envvar_prefix": self.auto_envvar_prefix, 

576 } 

577 

578 def __enter__(self) -> Self: 

579 self._depth += 1 

580 push_context(self) 

581 return self 

582 

583 def __exit__( 

584 self, 

585 exc_type: type[BaseException] | None, 

586 exc_value: BaseException | None, 

587 tb: TracebackType | None, 

588 ) -> bool | None: 

589 self._depth -= 1 

590 exit_result: bool | None = None 

591 if self._depth == 0: 

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

593 pop_context() 

594 

595 return exit_result 

596 

597 @contextmanager 

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

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

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

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

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

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

604 

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

606 used as a context manager. 

607 

608 Example usage:: 

609 

610 with ctx.scope(): 

611 assert get_current_context() is ctx 

612 

613 This is equivalent:: 

614 

615 with ctx: 

616 assert get_current_context() is ctx 

617 

618 .. versionadded:: 5.0 

619 

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

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

622 some situations the context only wants to be 

623 temporarily pushed in which case this can be disabled. 

624 Nested pushes automatically defer the cleanup. 

625 """ 

626 if not cleanup: 

627 self._depth += 1 

628 try: 

629 with self as rv: 

630 yield rv 

631 finally: 

632 if not cleanup: 

633 self._depth -= 1 

634 

635 @property 

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

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

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

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

640 that code to manage this dictionary well. 

641 

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

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

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

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

646 the system. 

647 

648 Example usage:: 

649 

650 LANG_KEY = f'{__name__}.lang' 

651 

652 def set_language(value): 

653 ctx = get_current_context() 

654 ctx.meta[LANG_KEY] = value 

655 

656 def get_language(): 

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

658 

659 .. versionadded:: 5.0 

660 """ 

661 return self._meta 

662 

663 def make_formatter(self) -> HelpFormatter: 

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

665 usage output. 

666 

667 To quickly customize the formatter class used without overriding 

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

669 

670 .. versionchanged:: 8.0 

671 Added the :attr:`formatter_class` attribute. 

672 """ 

673 return self.formatter_class( 

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

675 ) 

676 

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

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

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

680 popped. 

681 

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

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

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

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

686 

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

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

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

690 

691 .. code-block:: python 

692 

693 @click.group() 

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

695 @click.pass_context 

696 def cli(ctx): 

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

698 

699 :param context_manager: The context manager to enter. 

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

701 

702 .. versionadded:: 8.0 

703 """ 

704 return self._exit_stack.enter_context(context_manager) 

705 

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

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

708 

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

710 execution. Resources that support Python's context manager 

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

712 registered with :meth:`with_resource` instead. 

713 

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

715 """ 

716 return self._exit_stack.callback(f) 

717 

718 def close(self) -> None: 

719 """Invoke all close callbacks registered with 

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

721 with :meth:`with_resource`. 

722 """ 

723 self._close_with_exception_info(None, None, None) 

724 

725 def _close_with_exception_info( 

726 self, 

727 exc_type: type[BaseException] | None, 

728 exc_value: BaseException | None, 

729 tb: TracebackType | None, 

730 ) -> bool | None: 

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

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

733 using :meth;`with_resource` 

734 

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

736 """ 

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

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

739 self._exit_stack = ExitStack() 

740 

741 return exit_result 

742 

743 @property 

744 def command_path(self) -> str: 

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

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

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

748 """ 

749 rv = "" 

750 if self.info_name is not None: 

751 rv = self.info_name 

752 if self.parent is not None: 

753 parent_command_path = [self.parent.command_path] 

754 

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

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

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

758 

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

760 return rv.lstrip() 

761 

762 def find_root(self) -> Context: 

763 """Finds the outermost context.""" 

764 node = self 

765 while node.parent is not None: 

766 node = node.parent 

767 return node 

768 

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

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

771 node: Context | None = self 

772 

773 while node is not None: 

774 if isinstance(node.obj, object_type): 

775 return node.obj 

776 

777 node = node.parent 

778 

779 return None 

780 

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

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

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

784 """ 

785 rv = self.find_object(object_type) 

786 if rv is None: 

787 self.obj = rv = object_type() 

788 return rv 

789 

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

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

792 

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

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

795 :data:`UNSET` sentinel. 

796 """ 

797 return ( 

798 name is not None 

799 and self.default_map is not None 

800 and name in self.default_map 

801 and self.default_map[name] is not UNSET 

802 ) 

803 

804 @t.overload 

805 def lookup_default( 

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

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

808 

809 @t.overload 

810 def lookup_default( 

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

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

813 

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

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

816 

817 :param name: Name of the parameter. 

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

819 return the callable instead. 

820 

821 .. versionchanged:: 8.0 

822 Added the ``call`` parameter. 

823 """ 

824 if not self._default_map_has(name): 

825 return None 

826 

827 # Assert to make the type checker happy. 

828 assert self.default_map is not None 

829 value = self.default_map[name] 

830 

831 if call and callable(value): 

832 return value() 

833 

834 return value 

835 

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

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

838 message. 

839 

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

841 """ 

842 raise UsageError(message, self) 

843 

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

845 """Aborts the script.""" 

846 raise Abort() 

847 

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

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

850 

851 .. versionchanged:: 8.2 

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

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

854 """ 

855 self.close() 

856 raise Exit(code) 

857 

858 def get_usage(self) -> str: 

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

860 context and command. 

861 """ 

862 return self.command.get_usage(self) 

863 

864 def get_help(self) -> str: 

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

866 context and command. 

867 """ 

868 return self.command.get_help(self) 

869 

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

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

872 for a new command. 

873 

874 :meta private: 

875 """ 

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

877 

878 @t.overload 

879 def invoke( 

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

881 ) -> V: ... 

882 

883 @t.overload 

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

885 

886 def invoke( 

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

888 ) -> t.Any | V: 

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

890 are two ways to invoke this method: 

891 

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

893 keyword arguments are forwarded directly to the function. 

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

895 arguments are forwarded as well but proper click parameters 

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

897 will fill in defaults. 

898 

899 .. versionchanged:: 8.0 

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

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

902 

903 .. versionchanged:: 3.2 

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

905 """ 

906 if isinstance(callback, Command): 

907 other_cmd = callback 

908 

909 if other_cmd.callback is None: 

910 raise TypeError( 

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

912 ) 

913 else: 

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

915 

916 ctx = self._make_sub_context(other_cmd) 

917 

918 for param in other_cmd.params: 

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

920 default_value = param.get_default(ctx) 

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

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

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

924 # instead. 

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 for name, value in ctx.params.items(): 

1409 if value is UNSET: 

1410 ctx.params[name] = None 

1411 

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

1413 ctx.fail( 

1414 ngettext( 

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

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

1417 len(args), 

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

1419 ) 

1420 

1421 ctx.args = args 

1422 ctx._opt_prefixes.update(parser._opt_prefixes) 

1423 return args 

1424 

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

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

1427 in the right way. 

1428 """ 

1429 if self.deprecated: 

1430 message = _( 

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

1432 ).format( 

1433 name=self.name, 

1434 extra_message=_format_deprecated_suffix(self.deprecated), 

1435 ) 

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

1437 

1438 if self.callback is not None: 

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

1440 

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

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

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

1444 

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

1446 commands are valid at any point during command completion. 

1447 

1448 :param ctx: Invocation context for this command. 

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

1450 

1451 .. versionadded:: 8.0 

1452 """ 

1453 from click.shell_completion import CompletionItem 

1454 

1455 results: list[CompletionItem] = [] 

1456 

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

1458 for param in self.get_params(ctx): 

1459 if ( 

1460 not isinstance(param, Option) 

1461 or param.hidden 

1462 or ( 

1463 not param.multiple 

1464 and ctx.get_parameter_source(param.name) 

1465 is ParameterSource.COMMANDLINE 

1466 ) 

1467 ): 

1468 continue 

1469 

1470 results.extend( 

1471 CompletionItem(name, help=param.help) 

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

1473 if name.startswith(incomplete) 

1474 ) 

1475 

1476 while ctx.parent is not None: 

1477 ctx = ctx.parent 

1478 

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

1480 results.extend( 

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

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

1483 if name not in ctx._protected_args 

1484 ) 

1485 

1486 return results 

1487 

1488 @t.overload 

1489 def main( 

1490 self, 

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

1492 prog_name: str | None = None, 

1493 complete_var: str | None = None, 

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

1495 **extra: t.Any, 

1496 ) -> t.NoReturn: ... 

1497 

1498 @t.overload 

1499 def main( 

1500 self, 

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

1502 prog_name: str | None = None, 

1503 complete_var: str | None = None, 

1504 standalone_mode: bool = ..., 

1505 **extra: t.Any, 

1506 ) -> t.Any: ... 

1507 

1508 def main( 

1509 self, 

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

1511 prog_name: str | None = None, 

1512 complete_var: str | None = None, 

1513 standalone_mode: bool = True, 

1514 windows_expand_args: bool = True, 

1515 **extra: t.Any, 

1516 ) -> t.Any: 

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

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

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

1520 needs to be caught. 

1521 

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

1523 a :class:`Command`. 

1524 

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

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

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

1528 the program name is constructed by taking the file 

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

1530 :param complete_var: the environment variable that controls the 

1531 bash completion support. The default is 

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

1533 uppercase. 

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

1535 in standalone mode. Click will then 

1536 handle exceptions and convert them into 

1537 error messages and the function will never 

1538 return but shut down the interpreter. If 

1539 this is set to `False` they will be 

1540 propagated to the caller and the return 

1541 value of this function is the return value 

1542 of :meth:`invoke`. 

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

1544 env vars in command line args on Windows. 

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

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

1547 

1548 .. versionchanged:: 8.0.1 

1549 Added the ``windows_expand_args`` parameter to allow 

1550 disabling command line arg expansion on Windows. 

1551 

1552 .. versionchanged:: 8.0 

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

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

1555 

1556 .. versionchanged:: 3.0 

1557 Added the ``standalone_mode`` parameter. 

1558 """ 

1559 if args is None: 

1560 args = sys.argv[1:] 

1561 

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

1563 args = _expand_args(args) 

1564 else: 

1565 args = list(args) 

1566 

1567 if prog_name is None: 

1568 prog_name = _detect_program_name() 

1569 

1570 # Process shell completion requests and exit early. 

1571 self._main_shell_completion(extra, prog_name, complete_var) 

1572 

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

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

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

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

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

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

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

1580 exit_code = 1 

1581 

1582 try: 

1583 try: 

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

1585 rv = self.invoke(ctx) 

1586 if not standalone_mode: 

1587 return rv 

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

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

1590 # has obvious effects 

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

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

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

1594 # by its truthiness/falsiness 

1595 ctx.exit() 

1596 except Exit as e: 

1597 if not standalone_mode: 

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

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

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

1601 # would return its result 

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

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

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

1605 # tell the difference between the two 

1606 return e.exit_code 

1607 

1608 exit_code = e.exit_code 

1609 except Abort: 

1610 if not standalone_mode: 

1611 raise 

1612 

1613 report = _echo_aborted 

1614 except (EOFError, KeyboardInterrupt) as e: 

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

1616 echo(file=sys.stderr) 

1617 

1618 if not standalone_mode: 

1619 raise Abort() from e 

1620 

1621 report = _echo_aborted 

1622 except ClickException as e: 

1623 if not standalone_mode: 

1624 raise 

1625 

1626 report, exit_code = e.show, e.exit_code 

1627 except OSError as e: 

1628 if e.errno != errno.EPIPE: 

1629 raise 

1630 

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

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

1633 

1634 if report is not None: 

1635 report() 

1636 

1637 sys.exit(exit_code) 

1638 except (EOFError, KeyboardInterrupt): 

1639 if not standalone_mode: 

1640 raise 

1641 

1642 sys.exit(exit_code) 

1643 

1644 def _main_shell_completion( 

1645 self, 

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

1647 prog_name: str, 

1648 complete_var: str | None = None, 

1649 ) -> None: 

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

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

1652 program is invoked. 

1653 

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

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

1656 the completion instruction. Defaults to 

1657 ``_{PROG_NAME}_COMPLETE``. 

1658 

1659 .. versionchanged:: 8.2.0 

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

1661 """ 

1662 if complete_var is None: 

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

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

1665 

1666 instruction = os.environ.get(complete_var) 

1667 

1668 if not instruction: 

1669 return 

1670 

1671 from .shell_completion import shell_complete 

1672 

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

1674 sys.exit(rv) 

1675 

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

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

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

1679 

1680 

1681class _FakeSubclassCheck(type): 

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

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

1684 

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

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

1687 

1688 

1689class _BaseCommand(Command, metaclass=_FakeSubclassCheck): 

1690 """ 

1691 .. deprecated:: 8.2 

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

1693 """ 

1694 

1695 

1696class Group(Command): 

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

1698 

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

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

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

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

1703 subcommand is not given. 

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

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

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

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

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

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

1710 matched, and so on. 

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

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

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

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

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

1716 ``chain`` is enabled. 

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

1718 

1719 .. versionchanged:: 8.0 

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

1721 

1722 .. versionchanged:: 8.2 

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

1724 """ 

1725 

1726 allow_extra_args = True 

1727 allow_interspersed_args = False 

1728 

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

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

1731 #: subcommands use a custom command class. 

1732 #: 

1733 #: .. versionadded:: 8.0 

1734 command_class: type[Command] | None = None 

1735 

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

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

1738 #: subgroups use a custom group class. 

1739 #: 

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

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

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

1743 #: custom groups. 

1744 #: 

1745 #: .. versionadded:: 8.0 

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

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

1748 

1749 commands: cabc.MutableMapping[str, Command] 

1750 invoke_without_command: bool 

1751 subcommand_metavar: str 

1752 chain: bool 

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

1754 

1755 def __init__( 

1756 self, 

1757 name: str | None = None, 

1758 commands: cabc.MutableMapping[str, Command] 

1759 | cabc.Sequence[Command] 

1760 | None = None, 

1761 invoke_without_command: bool = False, 

1762 no_args_is_help: bool | None = None, 

1763 subcommand_metavar: str | None = None, 

1764 chain: bool = False, 

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

1766 **kwargs: t.Any, 

1767 ) -> None: 

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

1769 

1770 if commands is None: 

1771 commands = {} 

1772 elif isinstance(commands, abc.Sequence): 

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

1774 

1775 #: The registered subcommands by their exported names. 

1776 self.commands = commands 

1777 

1778 if no_args_is_help is None: 

1779 no_args_is_help = not invoke_without_command 

1780 

1781 self.no_args_is_help = no_args_is_help 

1782 self.invoke_without_command = invoke_without_command 

1783 

1784 if subcommand_metavar is None: 

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

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

1787 if chain: 

1788 if invoke_without_command: 

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

1790 else: 

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

1792 elif invoke_without_command: 

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

1794 else: 

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

1796 

1797 self.subcommand_metavar = subcommand_metavar 

1798 self.chain = chain 

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

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

1801 self._result_callback = result_callback 

1802 

1803 if self.chain: 

1804 for param in self.params: 

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

1806 raise RuntimeError( 

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

1808 ) 

1809 

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

1811 info_dict = super().to_info_dict(ctx) 

1812 commands = {} 

1813 

1814 for name in self.list_commands(ctx): 

1815 command = self.get_command(ctx, name) 

1816 

1817 if command is None: 

1818 continue 

1819 

1820 sub_ctx = ctx._make_sub_context(command) 

1821 

1822 with sub_ctx.scope(cleanup=False): 

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

1824 

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

1826 return info_dict 

1827 

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

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

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

1831 """ 

1832 name = name or cmd.name 

1833 if name is None: 

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

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

1836 self.commands[name] = cmd 

1837 

1838 @t.overload 

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

1840 

1841 @t.overload 

1842 def command( 

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

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

1845 

1846 def command( 

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

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

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

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

1851 immediately registers the created command with this group by 

1852 calling :meth:`add_command`. 

1853 

1854 To customize the command class used, set the 

1855 :attr:`command_class` attribute. 

1856 

1857 .. versionchanged:: 8.1 

1858 This decorator can be applied without parentheses. 

1859 

1860 .. versionchanged:: 8.0 

1861 Added the :attr:`command_class` attribute. 

1862 """ 

1863 from .decorators import command 

1864 

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

1866 

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

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

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

1870 ) 

1871 (func,) = args 

1872 args = () 

1873 

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

1875 kwargs["cls"] = self.command_class 

1876 

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

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

1879 self.add_command(cmd) 

1880 return cmd 

1881 

1882 if func is not None: 

1883 return decorator(func) 

1884 

1885 return decorator 

1886 

1887 @t.overload 

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

1889 

1890 @t.overload 

1891 def group( 

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

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

1894 

1895 def group( 

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

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

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

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

1900 immediately registers the created group with this group by 

1901 calling :meth:`add_command`. 

1902 

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

1904 attribute. 

1905 

1906 .. versionchanged:: 8.1 

1907 This decorator can be applied without parentheses. 

1908 

1909 .. versionchanged:: 8.0 

1910 Added the :attr:`group_class` attribute. 

1911 """ 

1912 from .decorators import group 

1913 

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

1915 

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

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

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

1919 ) 

1920 (func,) = args 

1921 args = () 

1922 

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

1924 if self.group_class is type: 

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

1926 else: 

1927 kwargs["cls"] = self.group_class 

1928 

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

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

1931 self.add_command(cmd) 

1932 return cmd 

1933 

1934 if func is not None: 

1935 return decorator(func) 

1936 

1937 return decorator 

1938 

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

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

1941 result callback is already registered this will chain them but 

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

1943 callback is invoked with the return value of the subcommand 

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

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

1946 to the main callback. 

1947 

1948 Example:: 

1949 

1950 @click.group() 

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

1952 def cli(input): 

1953 return 42 

1954 

1955 @cli.result_callback() 

1956 def process_result(result, input): 

1957 return result + input 

1958 

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

1960 callback will be removed. 

1961 

1962 .. versionchanged:: 8.0 

1963 Renamed from ``resultcallback``. 

1964 

1965 .. versionadded:: 3.0 

1966 """ 

1967 

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

1969 old_callback = self._result_callback 

1970 

1971 if old_callback is None or replace: 

1972 self._result_callback = f 

1973 return f 

1974 

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

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

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

1978 

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

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

1981 

1982 return decorator 

1983 

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

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

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

1987 """ 

1988 return self.commands.get(cmd_name) 

1989 

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

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

1992 return sorted(self.commands) 

1993 

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

1995 rv = super().collect_usage_pieces(ctx) 

1996 rv.append(self.subcommand_metavar) 

1997 return rv 

1998 

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

2000 super().format_options(ctx, formatter) 

2001 self.format_commands(ctx, formatter) 

2002 

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

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

2005 after the options. 

2006 """ 

2007 commands = [] 

2008 for subcommand in self.list_commands(ctx): 

2009 cmd = self.get_command(ctx, subcommand) 

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

2011 if cmd is None: 

2012 continue 

2013 if cmd.hidden: 

2014 continue 

2015 

2016 commands.append((subcommand, cmd)) 

2017 

2018 # allow for 3 times the default spacing 

2019 if len(commands): 

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

2021 

2022 rows = [] 

2023 for subcommand, cmd in commands: 

2024 help = cmd.get_short_help_str(limit) 

2025 rows.append((subcommand, help)) 

2026 

2027 if rows: 

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

2029 formatter.write_dl(rows) 

2030 

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

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

2033 raise NoArgsIsHelpError(ctx) 

2034 

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

2036 

2037 if self.chain: 

2038 ctx._protected_args = rest 

2039 ctx.args = [] 

2040 elif rest: 

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

2042 

2043 return ctx.args 

2044 

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

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

2047 if self._result_callback is not None: 

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

2049 return value 

2050 

2051 if not ctx._protected_args: 

2052 if self.invoke_without_command: 

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

2054 # invoked with the group return value for regular 

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

2056 with ctx: 

2057 rv = super().invoke(ctx) 

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

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

2060 

2061 # Fetch args back out 

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

2063 ctx.args = [] 

2064 ctx._protected_args = [] 

2065 

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

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

2068 # name of the command to invoke. 

2069 if not self.chain: 

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

2071 # resources until the result processor has worked. 

2072 with ctx: 

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

2074 assert cmd is not None 

2075 ctx.invoked_subcommand = cmd_name 

2076 super().invoke(ctx) 

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

2078 with sub_ctx: 

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

2080 

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

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

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

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

2085 # but nothing else. 

2086 with ctx: 

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

2088 super().invoke(ctx) 

2089 

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

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

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

2093 contexts = [] 

2094 while args: 

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

2096 assert cmd is not None 

2097 sub_ctx = cmd.make_context( 

2098 cmd_name, 

2099 args, 

2100 parent=ctx, 

2101 allow_extra_args=True, 

2102 allow_interspersed_args=False, 

2103 ) 

2104 contexts.append(sub_ctx) 

2105 args, sub_ctx.args = sub_ctx.args, [] 

2106 

2107 rv = [] 

2108 for sub_ctx in contexts: 

2109 with sub_ctx: 

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

2111 return _process_result(rv) 

2112 

2113 def resolve_command( 

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

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

2116 cmd_name = make_str(args[0]) 

2117 

2118 # Get the command 

2119 cmd = self.get_command(ctx, cmd_name) 

2120 

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

2122 # function available, we try with that one. 

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

2124 cmd_name = ctx.token_normalize_func(cmd_name) 

2125 cmd = self.get_command(ctx, cmd_name) 

2126 

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

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

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

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

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

2132 # place. 

2133 if cmd is None and not ctx.resilient_parsing: 

2134 if _split_opt(cmd_name)[0]: 

2135 self.parse_args(ctx, args) 

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

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

2138 

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

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

2141 at the names of options, subcommands, and chained 

2142 multi-commands. 

2143 

2144 :param ctx: Invocation context for this command. 

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

2146 

2147 .. versionadded:: 8.0 

2148 """ 

2149 from click.shell_completion import CompletionItem 

2150 

2151 results = [ 

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

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

2154 ] 

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

2156 return results 

2157 

2158 

2159class _MultiCommand(Group, metaclass=_FakeSubclassCheck): 

2160 """ 

2161 .. deprecated:: 8.2 

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

2163 """ 

2164 

2165 

2166class CommandCollection(Group): 

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

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

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

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

2171 commands in many groups into this one group. 

2172 

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

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

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

2176 

2177 .. versionchanged:: 8.2 

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

2179 group, then each of its sources. 

2180 """ 

2181 

2182 sources: list[Group] 

2183 

2184 def __init__( 

2185 self, 

2186 name: str | None = None, 

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

2188 **kwargs: t.Any, 

2189 ) -> None: 

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

2191 #: The list of registered groups. 

2192 self.sources = sources or [] 

2193 

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

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

2196 self.sources.append(group) 

2197 

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

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

2200 

2201 if rv is not None: 

2202 return rv 

2203 

2204 for source in self.sources: 

2205 rv = source.get_command(ctx, cmd_name) 

2206 

2207 if rv is not None: 

2208 if self.chain: 

2209 _check_nested_chain(self, cmd_name, rv) 

2210 

2211 return rv 

2212 

2213 return None 

2214 

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

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

2217 

2218 for source in self.sources: 

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

2220 

2221 return sorted(rv) 

2222 

2223 

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

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

2226 error, or return an iterator over the value. 

2227 """ 

2228 if isinstance(value, str): 

2229 raise TypeError 

2230 

2231 return iter(value) 

2232 

2233 

2234class Parameter(ABC): 

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

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

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

2238 intentionally not finalized. 

2239 

2240 Some settings are supported by both options and arguments. 

2241 

2242 Three distinct strings designate a parameter, each with its own audience: 

2243 

2244 ``decls`` 

2245 What the developer passes to the constructor as ``param_decls``. 

2246 ``spec`` 

2247 What the user reads in ``--help`` and types on the command line. See 

2248 :attr:`spec` and :meth:`get_help_spec`. 

2249 ``name`` 

2250 What Click uses internally to identify the parameter and to pass its 

2251 value to the command callback. See :attr:`name`. 

2252 

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

2254 argument. This is a list of flags or argument 

2255 names. 

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

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

2258 automatically if supported. 

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

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

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

2262 without any arguments. 

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

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

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

2266 including prompts. 

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

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

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

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

2271 parameters are collected. 

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

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

2274 to the command callback and stored on the context, 

2275 otherwise it's skipped. 

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

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

2278 order of processing. 

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

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

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

2282 :param shell_complete: A function that returns custom shell 

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

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

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

2286 strings. 

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

2288 indicating that the argument is deprecated and highlights 

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

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

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

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

2293 appropriate. 

2294 

2295 .. versionchanged:: 8.5.1 

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

2297 :class:`Argument`. 

2298 

2299 .. versionchanged:: 8.2.0 

2300 Introduction of ``deprecated``. 

2301 

2302 .. versionchanged:: 8.2 

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

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

2305 

2306 .. versionchanged:: 8.2 

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

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

2309 

2310 .. versionchanged:: 8.0 

2311 ``process_value`` validates required parameters and bounded 

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

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

2314 ``full_process_value`` is removed. 

2315 

2316 .. versionchanged:: 8.0 

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

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

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

2320 new requirements. 

2321 

2322 .. versionchanged:: 8.0 

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

2324 tuples. 

2325 

2326 .. versionchanged:: 8.0 

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

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

2329 default to ``()``. 

2330 

2331 .. versionchanged:: 7.1 

2332 Empty environment variables are ignored rather than taking the 

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

2334 variables if they can't unset them. 

2335 

2336 .. versionchanged:: 2.0 

2337 Changed signature for parameter callback to also be passed the 

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

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

2340 """ 

2341 

2342 param_type_name = "parameter" 

2343 

2344 name: str 

2345 """What Click uses internally to identify the parameter, and the Python 

2346 argument name it passes to the command callback. Click derives it from the 

2347 declarations, lower cased and with dashes replaced by underscores. An 

2348 :class:`Option` takes the declaration with the longest prefix, so 

2349 ``"-t", "--times"`` names ``times``, while an :class:`Argument` takes its 

2350 single declaration. 

2351 """ 

2352 opts: list[str] 

2353 """Every command-line spelling that designates this parameter. 

2354 

2355 For an :class:`Option` these are the prefixed declarations the parser 

2356 matches, in declaration order: ``["-t", "--times"]``. :attr:`spec` is the 

2357 canonical one. 

2358 

2359 For an :class:`Argument` this holds the single declaration the developer 

2360 wrote, ``["filename"]``. The parser never reads it: it binds the value by 

2361 :attr:`name`. The string the user reads is :attr:`spec`, ``FILENAME``. 

2362 """ 

2363 secondary_opts: list[str] 

2364 """The spellings that set a boolean :class:`Option` to ``False``, taken from 

2365 the right side of a ``--color/--no-color`` declaration. Always empty for an 

2366 :class:`Argument`. 

2367 """ 

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

2369 required: bool 

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

2371 nargs: int 

2372 multiple: bool 

2373 expose_value: bool 

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

2375 _default_explicit: bool 

2376 is_eager: bool 

2377 metavar: str | None 

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

2379 _custom_shell_complete: ( 

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

2381 ) 

2382 deprecated: bool | str 

2383 help: str | None 

2384 

2385 def __init_subclass__(cls, **kwargs: t.Any) -> None: 

2386 super().__init_subclass__(**kwargs) 

2387 

2388 if "human_readable_name" in cls.__dict__: 

2389 import warnings 

2390 

2391 warnings.warn( 

2392 f"{cls.__name__} overrides 'human_readable_name'. Click no" 

2393 " longer reads that property. Override 'spec' instead. Click" 

2394 " will remove 'human_readable_name' in 9.0.", 

2395 DeprecationWarning, 

2396 stacklevel=_outside_click_stacklevel(skip=("abc",)), 

2397 ) 

2398 

2399 def __init__( 

2400 self, 

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

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

2403 required: bool = False, 

2404 # XXX The default historically embed two concepts: 

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

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

2407 # self.name, like flag options), 

2408 # - and the actual value of the default. 

2409 # It is confusing and is the source of many issues. In the future, we might 

2410 # think of splitting it in two, not unlike Option.is_flag and Option.flag_value: 

2411 # we could have something like Parameter.is_default and Parameter.default_value. 

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

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

2414 nargs: int | None = None, 

2415 multiple: bool = False, 

2416 metavar: str | None = None, 

2417 expose_value: bool = True, 

2418 is_eager: bool = False, 

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

2420 shell_complete: t.Callable[ 

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

2422 ] 

2423 | None = None, 

2424 deprecated: bool | str = False, 

2425 help: str | None = None, 

2426 ) -> None: 

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

2428 param_decls or (), expose_value 

2429 ) 

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

2431 

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

2433 # information available. 

2434 if nargs is None: 

2435 if self.type.is_composite: 

2436 nargs = self.type.arity 

2437 else: 

2438 nargs = 1 

2439 

2440 self.required = required 

2441 self.callback = callback 

2442 self.nargs = nargs 

2443 self.multiple = multiple 

2444 self.expose_value = expose_value 

2445 self.default = default 

2446 # Whether the user passed ``default`` explicitly to the constructor. Captured 

2447 # before any auto-derived default (like ``0`` for a ``count`` :class:`Option`) 

2448 # replaces the :data:`UNSET` sentinel, so it remains ``False`` when the default 

2449 # was inferred rather than chosen. 

2450 self._default_explicit = default is not UNSET 

2451 self.is_eager = is_eager 

2452 self.metavar = metavar 

2453 self.envvar = envvar 

2454 self._custom_shell_complete = shell_complete 

2455 self.deprecated = deprecated 

2456 

2457 if help: 

2458 help = inspect.cleandoc(help) 

2459 

2460 if deprecated: 

2461 label = _format_deprecated_label(deprecated) 

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

2463 

2464 self.help = help 

2465 

2466 if __debug__: 

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

2468 raise ValueError( 

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

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

2471 ) 

2472 

2473 if required and deprecated: 

2474 raise ValueError( 

2475 f"The {self.param_type_name} '{self.spec}' " 

2476 "is deprecated and still required. A deprecated " 

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

2478 ) 

2479 

2480 @staticmethod 

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

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

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

2484 implementation detail. 

2485 """ 

2486 return None if value is UNSET else value 

2487 

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

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

2490 user-facing documentation. 

2491 

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

2493 CLI structure. 

2494 

2495 .. versionchanged:: 8.3.0 

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

2497 

2498 .. versionadded:: 8.0 

2499 """ 

2500 return { 

2501 "name": self.name, 

2502 "param_type_name": self.param_type_name, 

2503 "opts": self.opts, 

2504 "secondary_opts": self.secondary_opts, 

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

2506 "required": self.required, 

2507 "nargs": self.nargs, 

2508 "multiple": self.multiple, 

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

2510 "envvar": self.envvar, 

2511 "help": self.help, 

2512 } 

2513 

2514 def __repr__(self) -> str: 

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

2516 

2517 @abstractmethod 

2518 def _parse_decls( 

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

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

2521 

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

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

2524 

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

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

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

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

2529 reachable through ``**kwargs`` alone. 

2530 

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

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

2533 

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

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

2536 Click's import footprint to. 

2537 

2538 .. versionadded:: 8.6.0 

2539 """ 

2540 import keyword 

2541 

2542 if keyword.iskeyword(name): 

2543 reason = "which is a Python keyword" 

2544 elif not name.isidentifier(): 

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

2546 else: 

2547 return 

2548 

2549 import warnings 

2550 

2551 warnings.warn( 

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

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

2554 " TypeError in Click 9.0.", 

2555 DeprecationWarning, 

2556 stacklevel=_outside_click_stacklevel(), 

2557 ) 

2558 

2559 @property 

2560 def spec(self) -> str: 

2561 """Returns how the user spells this parameter on the command line. 

2562 

2563 This is the declaration with the longest prefix, so an option declared 

2564 as ``"-t", "--times"`` returns ``--times``. Click derives :attr:`name` 

2565 from that same declaration, unless the developer passed an explicit 

2566 name. A parameter without declarations returns its :attr:`name`. 

2567 

2568 .. versionadded:: 8.6.0 

2569 """ 

2570 if not self.opts: 

2571 return self.name 

2572 

2573 return max(self.opts, key=lambda opt: len(_split_opt(opt)[0])) 

2574 

2575 @property 

2576 def human_readable_name(self) -> str: 

2577 """Returns how the user spells this parameter on the command line. 

2578 

2579 .. deprecated:: 8.6.0 

2580 Will be removed in Click 9.0. Use :attr:`spec` instead. For an 

2581 option this returned the internal :attr:`name`, so the value 

2582 changes from ``times`` to ``--times``. Click no longer reads this 

2583 property, so an override in a subclass has no effect. 

2584 """ 

2585 import warnings 

2586 

2587 warnings.warn( 

2588 "'human_readable_name' is deprecated and will be removed in Click" 

2589 " 9.0. Use 'spec' instead.", 

2590 DeprecationWarning, 

2591 stacklevel=2, 

2592 ) 

2593 return self.spec 

2594 

2595 def get_help_spec(self, ctx: Context) -> str: 

2596 """Returns the left column of this parameter's help record. 

2597 

2598 This implementation returns :attr:`spec`. :class:`Option` returns every 

2599 spelling, plus the metavar when the option takes a value. 

2600 :class:`Argument` returns its metavar, which already carries the markers 

2601 for an optional, repeated or deprecated value. 

2602 

2603 Unlike ``get_help_record()``, the spec is produced even when the 

2604 parameter is left out of the help page, like a hidden option. 

2605 

2606 .. versionadded:: 8.6.0 

2607 """ 

2608 return self.spec 

2609 

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

2611 if self.metavar is not None: 

2612 return self.metavar 

2613 

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

2615 

2616 if metavar is None: 

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

2618 

2619 if self.nargs != 1: 

2620 metavar += "..." 

2621 

2622 return metavar 

2623 

2624 @t.overload 

2625 def get_default( 

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

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

2628 

2629 @t.overload 

2630 def get_default( 

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

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

2633 

2634 def get_default( 

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

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

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

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

2639 

2640 :param ctx: Current context. 

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

2642 return the callable instead. 

2643 

2644 .. versionchanged:: 8.0.2 

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

2646 

2647 .. versionchanged:: 8.0.1 

2648 Type casting can fail in resilient parsing mode. Invalid 

2649 defaults will not prevent showing help text. 

2650 

2651 .. versionchanged:: 8.0 

2652 Looks at ``ctx.default_map`` first. 

2653 

2654 .. versionchanged:: 8.0 

2655 Added the ``call`` parameter. 

2656 """ 

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

2658 

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

2660 value = self.default 

2661 

2662 if call and callable(value): 

2663 value = value() 

2664 

2665 return value 

2666 

2667 @abstractmethod 

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

2669 

2670 def consume_value( 

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

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

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

2674 

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

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

2677 default value. In that order of precedence. 

2678 

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

2680 

2681 :meta private: 

2682 """ 

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

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

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

2686 # parser, otherwise it left unset by default. 

2687 source = ( 

2688 ParameterSource.COMMANDLINE 

2689 if value is not UNSET 

2690 else ParameterSource.DEFAULT 

2691 ) 

2692 

2693 if value is UNSET: 

2694 envvar_value = self.value_from_envvar(ctx) 

2695 if envvar_value is not None: 

2696 value = envvar_value 

2697 source = ParameterSource.ENVIRONMENT 

2698 

2699 if value is UNSET: 

2700 default_map_value = ctx.lookup_default(self.name) 

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

2702 value = default_map_value 

2703 source = ParameterSource.DEFAULT_MAP 

2704 

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

2706 # parameters, matching value_from_envvar behavior. 

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

2708 value = self.type.split_envvar_value(value) 

2709 

2710 if value is UNSET: 

2711 default_value = self.get_default(ctx) 

2712 if default_value is not UNSET: 

2713 value = default_value 

2714 source = ParameterSource.DEFAULT 

2715 

2716 return value, source 

2717 

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

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

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

2721 """ 

2722 if value is None: 

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

2724 return () 

2725 else: 

2726 return value 

2727 

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

2729 try: 

2730 return _check_iter(value) 

2731 except TypeError: 

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

2733 # the parser should construct an iterable when parsing 

2734 # the command line. 

2735 raise BadParameter( 

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

2737 ) from None 

2738 

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

2740 

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

2742 

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

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

2745 

2746 elif self.nargs == -1: 

2747 

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

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

2750 

2751 else: # nargs > 1 

2752 

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

2754 value = tuple(check_iter(value)) 

2755 

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

2757 raise BadParameter( 

2758 ngettext( 

2759 "Takes {nargs} values but 1 was given.", 

2760 "Takes {nargs} values but {len} were given.", 

2761 len(value), 

2762 ).format(nargs=self.nargs, len=len(value)), 

2763 ctx=ctx, 

2764 param=self, 

2765 ) 

2766 

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

2768 

2769 if self.multiple: 

2770 return tuple(convert(x) for x in check_iter(value)) 

2771 

2772 return convert(value) 

2773 

2774 def value_is_missing(self, value: t.Any) -> bool: 

2775 """A value is considered missing if: 

2776 

2777 - it is :attr:`UNSET`, 

2778 - or if it is an empty sequence while the parameter is suppose to have 

2779 non-single value (i.e. :attr:`nargs` is not ``1`` or :attr:`multiple` is 

2780 set). 

2781 

2782 :meta private: 

2783 """ 

2784 if value is UNSET: 

2785 return True 

2786 

2787 if (self.nargs != 1 or self.multiple) and value == (): 

2788 return True 

2789 

2790 return False 

2791 

2792 def process_value(self, ctx: Context, value: t.Any) -> t.Any: 

2793 """Process the value of this parameter: 

2794 

2795 1. Type cast the value using :meth:`type_cast_value`. 

2796 2. Check if the value is missing (see: :meth:`value_is_missing`), and raise 

2797 :exc:`MissingParameter` if it is required. 

2798 3. If a :attr:`callback` is set, call it to have the value replaced by the 

2799 result of the callback. If the value was not set, the callback receive 

2800 ``None``. This keep the legacy behavior as it was before the introduction of 

2801 the :attr:`UNSET` sentinel. 

2802 

2803 :meta private: 

2804 """ 

2805 # shelter `type_cast_value` from ever seeing an `UNSET` value by handling the 

2806 # cases in which `UNSET` gets special treatment explicitly at this layer. 

2807 # Subclasses can override the public `type_cast_value`, so the internal sentinel 

2808 # must not reach it. A missing value skips the call rather than passing `None`, 

2809 # which `value_is_missing` would not detect. 

2810 if value is UNSET: 

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

2812 value = () 

2813 else: 

2814 value = self.type_cast_value(ctx, value) 

2815 

2816 if self.required and self.value_is_missing(value): 

2817 raise MissingParameter(ctx=ctx, param=self) 

2818 

2819 if self.callback is not None: 

2820 # Legacy case: UNSET is not exposed directly to the callback, but converted 

2821 # to None. 

2822 if value is UNSET: 

2823 value = None 

2824 

2825 # Search for parameters with UNSET values in the context. 

2826 unset_keys = {k: None for k, v in ctx.params.items() if v is UNSET} 

2827 # No UNSET values, call the callback as usual. 

2828 if not unset_keys: 

2829 value = self.callback(ctx, self, value) 

2830 

2831 # Legacy case: provide a temporarily manipulated context to the callback to 

2832 # hide UNSET values as None. 

2833 else: 

2834 # Add another layer to the context stack to clearly hint that the 

2835 # context is temporarily modified. 

2836 with ctx: 

2837 # Update the context parameters to replace UNSET with None. 

2838 ctx.params.update(unset_keys) 

2839 # Feed these fake context parameters to the callback. 

2840 value = self.callback(ctx, self, value) 

2841 # Restore the UNSET values in the context parameters. 

2842 ctx.params.update( 

2843 { 

2844 k: UNSET 

2845 for k in unset_keys 

2846 # Only restore keys that are present and still None, in case 

2847 # the callback modified other parameters. 

2848 if k in ctx.params and ctx.params[k] is None 

2849 } 

2850 ) 

2851 

2852 return value 

2853 

2854 def resolve_envvar_value(self, ctx: Context) -> str | None: 

2855 """Returns the value found in the environment variable(s) attached to this 

2856 parameter. 

2857 

2858 Environment variables values are `always returned as strings 

2859 <https://docs.python.org/3/library/os.html#os.environ>`_. 

2860 

2861 This method returns ``None`` if: 

2862 

2863 - the :attr:`envvar` property is not set on the :class:`Parameter`, 

2864 - the environment variable is not found in the environment, 

2865 - the variable is found in the environment but its value is empty (i.e. the 

2866 environment variable is present but has an empty string). 

2867 

2868 If :attr:`envvar` is setup with multiple environment variables, 

2869 then only the first non-empty value is returned. 

2870 

2871 .. caution:: 

2872 

2873 The raw value extracted from the environment is not normalized and is 

2874 returned as-is. Any normalization or reconciliation is performed later by 

2875 the :class:`Parameter`'s :attr:`type`. 

2876 

2877 :meta private: 

2878 """ 

2879 if not self.envvar: 

2880 return None 

2881 

2882 if isinstance(self.envvar, str): 

2883 rv = os.environ.get(self.envvar) 

2884 

2885 if rv: 

2886 return rv 

2887 else: 

2888 for envvar in self.envvar: 

2889 rv = os.environ.get(envvar) 

2890 

2891 # Return the first non-empty value of the list of environment variables. 

2892 if rv: 

2893 return rv 

2894 # Else, absence of value is interpreted as an environment variable that 

2895 # is not set, so proceed to the next one. 

2896 

2897 return None 

2898 

2899 def value_from_envvar(self, ctx: Context) -> str | cabc.Sequence[str] | None: 

2900 """Process the raw environment variable string for this parameter. 

2901 

2902 Returns the string as-is or splits it into a sequence of strings if the 

2903 parameter is expecting multiple values (i.e. its :attr:`nargs` property is set 

2904 to a value other than ``1``). 

2905 

2906 :meta private: 

2907 """ 

2908 rv = self.resolve_envvar_value(ctx) 

2909 

2910 if rv is not None and self.nargs != 1: 

2911 return self.type.split_envvar_value(rv) 

2912 

2913 return rv 

2914 

2915 def handle_parse_result( 

2916 self, ctx: Context, opts: cabc.Mapping[str, t.Any], args: list[str] 

2917 ) -> tuple[t.Any, list[str]]: 

2918 """Process the value produced by the parser from user input. 

2919 

2920 Always process the value through the Parameter's :attr:`type`, wherever it 

2921 comes from. 

2922 

2923 If the parameter is deprecated, this method warn the user about it. But only if 

2924 the value has been explicitly set by the user (and as such, is not coming from 

2925 a default). 

2926 

2927 :meta private: 

2928 """ 

2929 # Capture the slot's existing state before we mutate 

2930 # ``_parameter_source`` so the write decision below can compare our 

2931 # incoming source against the source of the option that already wrote 

2932 # the slot (if any). 

2933 existing_value = ctx.params.get(self.name, UNSET) 

2934 existing_source = ctx.get_parameter_source(self.name) 

2935 existing_default_explicit = ctx._param_default_explicit.get(self.name, False) 

2936 

2937 with augment_usage_errors(ctx, param=self): 

2938 value, source = self.consume_value(ctx, opts) 

2939 

2940 # Record the source before processing so eager callbacks and type 

2941 # conversion can inspect it. Restored after arbitration if this 

2942 # option loses a feature-switch group. 

2943 ctx.set_parameter_source(self.name, source) 

2944 

2945 # Display a deprecation warning if necessary. 

2946 if ( 

2947 self.deprecated 

2948 and value is not UNSET 

2949 and source < ParameterSource.DEFAULT_MAP 

2950 ): 

2951 message = _( 

2952 "DeprecationWarning: The {param_type} {name!r} is deprecated." 

2953 "{extra_message}" 

2954 ).format( 

2955 param_type=self.param_type_name, 

2956 name=self.spec, 

2957 extra_message=_format_deprecated_suffix(self.deprecated), 

2958 ) 

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

2960 

2961 # Process the value through the parameter's type. 

2962 try: 

2963 value = self.process_value(ctx, value) 

2964 except Exception: 

2965 if not ctx.resilient_parsing: 

2966 raise 

2967 # In resilient parsing mode, we do not want to fail the command if the 

2968 # value is incompatible with the parameter type, so we reset the value 

2969 # to UNSET, which will be interpreted as a missing value. 

2970 value = UNSET 

2971 

2972 # Arbitrate the slot when several parameters target the same variable name 

2973 # (feature-switch groups). 

2974 slot_empty = existing_value is UNSET 

2975 more_explicit = existing_source is not None and source < existing_source 

2976 same_source = existing_source is not None and source == existing_source 

2977 auto_would_downgrade_explicit = ( 

2978 same_source 

2979 and source == ParameterSource.DEFAULT 

2980 and existing_default_explicit 

2981 and not self._default_explicit 

2982 ) 

2983 is_winner = ( 

2984 slot_empty 

2985 or more_explicit 

2986 or (same_source and not auto_would_downgrade_explicit) 

2987 ) 

2988 

2989 if is_winner: 

2990 if self.expose_value: 

2991 ctx.params[self.name] = value 

2992 ctx._param_default_explicit[self.name] = self._default_explicit 

2993 elif existing_source is not None: 

2994 # Lost arbitration; restore the winning option's source. 

2995 ctx.set_parameter_source(self.name, existing_source) 

2996 # else: ctx.params[self.name] was populated by code that bypassed 

2997 # handle_parse_result (from another option's callback for example). Keep 

2998 # the provisional source recorded before process_value so downstream 

2999 # lookups don't return ``None``. 

3000 

3001 return value, args 

3002 

3003 def get_help_record(self, ctx: Context) -> tuple[str, str] | None: 

3004 return None 

3005 

3006 def get_usage_pieces(self, ctx: Context) -> list[str]: 

3007 return [] 

3008 

3009 def get_error_hint(self, ctx: Context | None) -> str: 

3010 """Get a stringified version of the param for use in error messages to 

3011 indicate which param caused the error. 

3012 

3013 .. versionchanged:: 8.4.0 

3014 ``ctx`` can be ``None``. 

3015 """ 

3016 hint_list = self.opts or [self.spec] 

3017 return " / ".join(f"'{x}'" for x in hint_list) 

3018 

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

3020 """Return a list of completions for the incomplete value. If a 

3021 ``shell_complete`` function was given during init, it is used. 

3022 Otherwise, the :attr:`type` 

3023 :meth:`~click.types.ParamType[t.Any].shell_complete` function is used. 

3024 

3025 :param ctx: Invocation context for this command. 

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

3027 

3028 .. versionadded:: 8.0 

3029 """ 

3030 if self._custom_shell_complete is not None: 

3031 results = self._custom_shell_complete(ctx, self, incomplete) 

3032 

3033 if results and isinstance(results[0], str): 

3034 from click.shell_completion import CompletionItem 

3035 

3036 results = [CompletionItem(c) for c in results] 

3037 

3038 return t.cast("list[CompletionItem]", results) 

3039 

3040 return self.type.shell_complete(ctx, self, incomplete) 

3041 

3042 

3043class Option(Parameter): 

3044 """Options are usually optional values on the command line and 

3045 have some extra features that arguments don't have. 

3046 

3047 All other parameters are passed onwards to the parameter constructor. 

3048 

3049 :param show_default: Show the default value for this option in its 

3050 help text. Values are not shown by default, unless 

3051 :attr:`Context.show_default` is ``True``. If this value is a 

3052 string, it shows that string in parentheses instead of the 

3053 actual value. This is particularly useful for dynamic options. 

3054 For single option boolean flags, the default remains hidden if 

3055 its value is ``False``. 

3056 :param show_envvar: Controls if an environment variable should be 

3057 shown on the help page and error messages. 

3058 Normally, environment variables are not shown. 

3059 :param prompt: If set to ``True`` or a non empty string then the 

3060 user will be prompted for input. If set to ``True`` the prompt 

3061 will be the option name capitalized. A deprecated option cannot be 

3062 prompted. 

3063 :param confirmation_prompt: Prompt a second time to confirm the 

3064 value if it was prompted for. Can be set to a string instead of 

3065 ``True`` to customize the message. 

3066 :param prompt_required: If set to ``False``, the user will be 

3067 prompted for input only when the option was specified as a flag 

3068 without a value. 

3069 :param hide_input: If this is ``True`` then the input on the prompt 

3070 will be hidden from the user. This is useful for password input. 

3071 :param is_flag: forces this option to act as a flag. The default is 

3072 auto detection. 

3073 :param flag_value: which value should be used for this flag if it's 

3074 enabled. This is set to a boolean automatically if 

3075 the option string contains a slash to mark two options. 

3076 :param multiple: if this is set to `True` then the argument is accepted 

3077 multiple times and recorded. This is similar to ``nargs`` 

3078 in how it works but supports arbitrary number of 

3079 arguments. 

3080 :param count: this flag makes an option increment an integer. 

3081 :param allow_from_autoenv: if this is enabled then the value of this 

3082 parameter will be pulled from an environment 

3083 variable in case a prefix is defined on the 

3084 context. 

3085 :param help: the help string. 

3086 :param hidden: hide this option from help outputs. 

3087 :param attrs: Other command arguments described in :class:`Parameter`. 

3088 

3089 .. versionchanged:: 8.4.0 

3090 Non-basic ``flag_value`` types (not ``str``, ``int``, ``float``, or 

3091 ``bool``) are passed through unchanged instead of being stringified. 

3092 Previously, ``type=click.UNPROCESSED`` was required to preserve them. 

3093 

3094 .. versionchanged:: 8.2 

3095 ``envvar`` used with ``flag_value`` will always use the ``flag_value``, 

3096 previously it would use the value of the environment variable. 

3097 

3098 .. versionchanged:: 8.1 

3099 Help text indentation is cleaned here instead of only in the 

3100 ``@option`` decorator. 

3101 

3102 .. versionchanged:: 8.1 

3103 The ``show_default`` parameter overrides 

3104 ``Context.show_default``. 

3105 

3106 .. versionchanged:: 8.1 

3107 The default of a single option boolean flag is not shown if the 

3108 default value is ``False``. 

3109 

3110 .. versionchanged:: 8.0.1 

3111 ``type`` is detected from ``flag_value`` if given, for basic Python 

3112 types (``str``, ``int``, ``float``, ``bool``). 

3113 """ 

3114 

3115 param_type_name = "option" 

3116 

3117 prompt: str | None 

3118 confirmation_prompt: bool | str 

3119 prompt_required: bool 

3120 hide_input: bool 

3121 hidden: bool 

3122 

3123 _flag_needs_value: bool 

3124 is_flag: bool 

3125 flag_value: t.Any 

3126 type: types.ParamType[t.Any] 

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

3128 

3129 count: bool 

3130 allow_from_autoenv: bool 

3131 show_default: bool | str | None 

3132 show_choices: bool 

3133 show_envvar: bool 

3134 

3135 def __init__( 

3136 self, 

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

3138 show_default: bool | str | None = None, 

3139 prompt: bool | str = False, 

3140 confirmation_prompt: bool | str = False, 

3141 prompt_required: bool = True, 

3142 hide_input: bool = False, 

3143 is_flag: bool | None = None, 

3144 flag_value: t.Any = UNSET, 

3145 multiple: bool = False, 

3146 count: bool = False, 

3147 allow_from_autoenv: bool = True, 

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

3149 help: str | None = None, 

3150 hidden: bool = False, 

3151 show_choices: bool = True, 

3152 show_envvar: bool = False, 

3153 deprecated: bool | str = False, 

3154 **attrs: t.Any, 

3155 ) -> None: 

3156 super().__init__( 

3157 param_decls, 

3158 type=type, 

3159 multiple=multiple, 

3160 deprecated=deprecated, 

3161 help=help, 

3162 **attrs, 

3163 ) 

3164 

3165 # Phase 1: prompt-related attributes. ``_infer_flag_kind`` reads ``self.prompt`` 

3166 # and ``self.prompt_required`` so this must run first. 

3167 if prompt is True: 

3168 if not self.name: 

3169 raise TypeError("'name' is required with 'prompt=True'.") 

3170 

3171 prompt_text = self.name.replace("_", " ").capitalize() 

3172 elif prompt is False: 

3173 prompt_text = None 

3174 else: 

3175 prompt_text = prompt 

3176 

3177 self.prompt = prompt_text 

3178 self.confirmation_prompt = confirmation_prompt 

3179 self.prompt_required = prompt_required 

3180 self.hide_input = hide_input 

3181 self.hidden = hidden 

3182 

3183 # Phase 2: flag-kind inference. 

3184 self.is_flag, self._flag_needs_value = self._infer_flag_kind( 

3185 is_flag, flag_value 

3186 ) 

3187 

3188 # Phase 3: type inference. Override the type set by :meth:`Parameter.__init__` 

3189 # when this option is a flag or a count. 

3190 self.type = self._pick_type(type, flag_value, count, self.is_flag) 

3191 

3192 # Phase 4: store the raw ``flag_value`` and ``count`` settings. 

3193 # ``self.flag_value`` and ``self.default`` deliberately keep the :data:`UNSET` 

3194 # sentinel when the user didn't pass them. Auto-derived values are resolved 

3195 # lazily in :meth:`_resolve_lazy_default` and :attr:`flag_activation_value`. 

3196 # Keeping the raw values means ``is UNSET`` reliably answers "did the user pass 

3197 # this?", and any future feature needing the same distinction can reuse it 

3198 # without reintroducing parallel "was it explicit?" tracking. 

3199 self.flag_value = flag_value 

3200 self.count = count 

3201 if count and self.default is UNSET: 

3202 self.default = 0 

3203 

3204 self.allow_from_autoenv = allow_from_autoenv 

3205 self.show_default = show_default 

3206 self.show_choices = show_choices 

3207 self.show_envvar = show_envvar 

3208 

3209 # Phase 5: validate. Raises on illegal kwarg combinations. 

3210 self._validate(prompt, deprecated) 

3211 

3212 @property 

3213 def is_bool_flag(self) -> bool: 

3214 """``True`` when this option is a flag with a boolean type. 

3215 

3216 Derived from :attr:`is_flag` and :attr:`type`; computed on access so it cannot 

3217 drift if a subclass replaces :attr:`type` after construction. 

3218 """ 

3219 return self.is_flag and isinstance(self.type, types.BoolParamType) 

3220 

3221 @property 

3222 def flag_activation_value(self) -> t.Any: 

3223 """Value the function receives when this flag is activated on the command line. 

3224 

3225 Resolves a missing :attr:`flag_value` to ``True`` for actual flag options and 

3226 ``None`` otherwise. Used by the parser bridge (:meth:`add_to_parser`) and the 

3227 runtime (:meth:`consume_value`) so :attr:`flag_value` can keep the :data:`UNSET` 

3228 sentinel for "did the user pass one?" introspection. 

3229 """ 

3230 if self.flag_value is UNSET: 

3231 return True if self.is_flag else None 

3232 return self.flag_value 

3233 

3234 def _infer_flag_kind( 

3235 self, is_flag: bool | None, flag_value: t.Any 

3236 ) -> tuple[bool, bool]: 

3237 """Resolve ``is_flag`` and the parser hint ``_flag_needs_value``. 

3238 

3239 Returns ``(is_flag, flag_needs_value)``, where ``_flag_needs_value`` tells the 

3240 parser that the value of this option can be omitted: the option then prompts for 

3241 a value if ``prompt`` is set, and otherwise uses its flag value. The parser uses 

3242 it to decide whether to treat the next CLI token as the option's value or as a 

3243 new option. If ``prompt`` is enabled with ``prompt_required=False``, it opens 

3244 the door for an interactive value, hence the initial condition. 

3245 """ 

3246 needs_value = self.prompt is not None and not self.prompt_required 

3247 

3248 if is_flag is None: 

3249 # Implicitly a flag because flag_value was set. 

3250 if flag_value is not UNSET: 

3251 return True, needs_value 

3252 # Not a flag, but when used as a flag it shows a prompt. 

3253 if needs_value: 

3254 return False, needs_value 

3255 # Implicitly a flag because secondary options names were given. 

3256 if self.secondary_opts: 

3257 return True, needs_value 

3258 return False, needs_value 

3259 

3260 if is_flag is False and not needs_value: 

3261 # Explicit ``is_flag=False`` with a flag-like value/default still makes the 

3262 # option flag-shaped to the parser. 

3263 needs_value = flag_value is not UNSET or self.default is UNSET 

3264 

3265 return bool(is_flag), needs_value 

3266 

3267 def _pick_type( 

3268 self, 

3269 type_arg: t.Any, 

3270 flag_value: t.Any, 

3271 count: bool, 

3272 is_flag: bool, 

3273 ) -> types.ParamType[t.Any]: 

3274 """Pick the final :class:`ParamType` for this option. 

3275 

3276 :meth:`Parameter.__init__` already stored ``self.type`` from the explicit 

3277 ``type`` argument or from ``default``. This method either returns that as-is, or 

3278 overrides it for flag and count options (which are inferred from ``flag_value`` 

3279 rather than ``default``). 

3280 """ 

3281 if type_arg is not None: 

3282 return self.type 

3283 

3284 if count: 

3285 return types.IntRange(min=0) 

3286 

3287 if not is_flag: 

3288 return self.type 

3289 

3290 # A flag without a flag_value is a boolean flag. 

3291 if flag_value is UNSET or isinstance(flag_value, bool): 

3292 return types.BoolParamType() 

3293 

3294 guessed: types.ParamType[t.Any] = types.convert_type(None, flag_value) 

3295 if ( 

3296 isinstance(guessed, types.StringParamType) 

3297 and not isinstance(flag_value, str) 

3298 and flag_value is not None 

3299 ): 

3300 # The flag_value type couldn't be auto-detected (not str, int, float, or 

3301 # bool). Since flag_value is a programmer-provided Python object, not CLI 

3302 # input, pass it through unchanged instead of stringifying it. 

3303 return types.UNPROCESSED 

3304 return guessed 

3305 

3306 def _resolve_lazy_default(self, value: t.Any) -> t.Any: 

3307 """Apply lazy auto-derivations to a default-style value. 

3308 

3309 Shared between :meth:`get_default` (the runtime path) and :meth:`to_info_dict` 

3310 (the introspection path) so the two views cannot drift apart. Callables are 

3311 *not* invoked here: that is :meth:`get_default`'s responsibility. Rules: 

3312 

3313 * ``UNSET`` resolves to ``False`` for a non-required boolean flag, and to ``()`` 

3314 for a non-required, non-prompted multi flag. 

3315 * ``True`` resolves to :attr:`flag_value` for a non-boolean flag (the "activate 

3316 this flag by default" shorthand). Boolean flags keep ``True`` as a literal. 

3317 """ 

3318 if value is UNSET and self.is_flag: 

3319 if self.multiple and not self.required and not self.prompt: 

3320 return () 

3321 if self.is_bool_flag and not self.required: 

3322 return False 

3323 if value is True and self.is_flag and not self.is_bool_flag: 

3324 # Use ``flag_activation_value`` so an unset ``flag_value`` resolves to 

3325 # ``True`` (the bool-flag activation value) rather than leaking the 

3326 # :data:`UNSET` sentinel. 

3327 return self.flag_activation_value 

3328 return value 

3329 

3330 def _validate(self, prompt: bool | str, deprecated: bool | str) -> None: 

3331 """Raise :class:`TypeError` / :class:`ValueError` on illegal kwarg combinations. 

3332 

3333 Called once, after every other attribute has been assigned, so each check can 

3334 read the final state. 

3335 """ 

3336 if not __debug__: 

3337 return 

3338 if deprecated and prompt: 

3339 raise ValueError("`deprecated` options cannot use `prompt`.") 

3340 if self.nargs == -1: 

3341 raise TypeError("nargs=-1 is not supported for options.") 

3342 if not self.is_bool_flag and self.secondary_opts: 

3343 raise TypeError("Secondary flag is not valid for non-boolean flag.") 

3344 if self.is_bool_flag and self.hide_input and self.prompt is not None: 

3345 raise TypeError("'prompt' with 'hide_input' is not valid for boolean flag.") 

3346 if self.count: 

3347 if self.multiple: 

3348 raise TypeError("'count' is not valid with 'multiple'.") 

3349 if self.is_flag: 

3350 raise TypeError("'count' is not valid with 'is_flag'.") 

3351 

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

3353 """ 

3354 .. versionchanged:: 8.5.0 

3355 ``default`` and ``flag_value`` reflect the auto-derived values (``False`` 

3356 for unset boolean-flag defaults, ``True`` for unset boolean-flag activation 

3357 values, etc.) when no explicit value was passed, matching what the function 

3358 would receive at call time. 

3359 

3360 .. versionchanged:: 8.3.0 

3361 Returns ``None`` for the :attr:`flag_value` if it was not set. 

3362 """ 

3363 info_dict = super().to_info_dict() 

3364 info_dict.update( 

3365 default=self._hide_unset(self._resolve_lazy_default(self.default)), 

3366 prompt=self.prompt, 

3367 is_flag=self.is_flag, 

3368 flag_value=self.flag_activation_value, 

3369 count=self.count, 

3370 hidden=self.hidden, 

3371 ) 

3372 return info_dict 

3373 

3374 def get_default( 

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

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

3377 """Return the default value for this option. 

3378 

3379 Several auto-derived defaults are resolved lazily here rather than eagerly in 

3380 :meth:`__init__`. This keeps :attr:`default` raw at construction time, so 

3381 ``self.default is UNSET`` reliably answers "did the user pass a default?" for 

3382 anything that needs to distinguish "absent" from a chosen value. The resolution 

3383 rules live in :meth:`_resolve_lazy_default`. 

3384 

3385 .. versionchanged:: 8.5.0 

3386 ``UNSET`` defaults for boolean and multi flags are now resolved here instead 

3387 of being coerced in :meth:`__init__`. Reading :attr:`default` directly 

3388 returns the user-supplied value (or ``UNSET`` if none was passed) rather 

3389 than the auto-derived one. 

3390 

3391 .. versionchanged:: 8.3.3 

3392 ``default=True`` is no longer substituted with ``flag_value`` for boolean 

3393 flags, fixing negative boolean flags like 

3394 ``flag_value=False, default=True``. 

3395 """ 

3396 raw = super().get_default(ctx, call=False) 

3397 value = self._resolve_lazy_default(raw) 

3398 # Only invoke the value as a callable when the lazy resolver passed it through 

3399 # unchanged. If the resolver substituted ``True`` -> :attr:`flag_value`, the 

3400 # result is the programmer-supplied ``flag_value`` (often a class or enum), 

3401 # which must NOT be instantiated here. 

3402 if value is raw and call and callable(value): 

3403 value = value() 

3404 return value 

3405 

3406 def get_error_hint(self, ctx: Context | None) -> str: 

3407 result = super().get_error_hint(ctx) 

3408 if self.show_envvar and self.envvar: 

3409 envvars = [self.envvar] if isinstance(self.envvar, str) else self.envvar 

3410 # An environment variable is allowed to feature a space or a comma on all 

3411 # platforms, hence the quotes around each. 

3412 var_str = ", ".join(f"'{var}'" for var in envvars) 

3413 result += f" (env var: {var_str})" 

3414 return result 

3415 

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

3417 """Warn about an explicit name Click 9.0 will spell differently. 

3418 

3419 .. versionadded:: 8.6.0 

3420 """ 

3421 normalized = name.lower() 

3422 

3423 if normalized == name: 

3424 return 

3425 

3426 import warnings 

3427 

3428 warnings.warn( 

3429 f"Option {list(decls)!r} uses {name!r} as its name. Click 9.0" 

3430 f" lower cases an explicit name like any other declaration, naming" 

3431 f" {normalized!r} instead.", 

3432 DeprecationWarning, 

3433 stacklevel=_outside_click_stacklevel(), 

3434 ) 

3435 

3436 def _parse_decls( 

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

3438 ) -> tuple[str, list[str], list[str]]: 

3439 opts = [] 

3440 secondary_opts = [] 

3441 name = None 

3442 explicit_name = None 

3443 possible_names = [] 

3444 

3445 for decl in decls: 

3446 if decl.isidentifier(): 

3447 if name is not None: 

3448 raise TypeError(_("Name '{name}' defined twice").format(name=name)) 

3449 name = explicit_name = decl 

3450 else: 

3451 split_char = ";" if decl[:1] == "/" else "/" 

3452 if split_char in decl: 

3453 first, second = decl.split(split_char, 1) 

3454 first = first.rstrip() 

3455 if first: 

3456 possible_names.append(_split_opt(first)) 

3457 opts.append(first) 

3458 second = second.lstrip() 

3459 if second: 

3460 secondary_opts.append(second.lstrip()) 

3461 if first == second: 

3462 raise ValueError( 

3463 _( 

3464 "Boolean option {decl!r} cannot use the" 

3465 " same flag for true/false." 

3466 ).format(decl=decl) 

3467 ) 

3468 else: 

3469 possible_names.append(_split_opt(decl)) 

3470 opts.append(decl) 

3471 

3472 if name is None and possible_names: 

3473 possible_names.sort(key=lambda x: -len(x[0])) # group long options first 

3474 name = possible_names[0][1].replace("-", "_").lower() 

3475 

3476 if name is None or not name.isidentifier(): 

3477 if not expose_value: 

3478 self._check_name_is_usable(name or "", decls) 

3479 return "", opts, secondary_opts 

3480 

3481 raise TypeError( 

3482 _( 

3483 "Could not determine name for option with declarations {decls!r}" 

3484 ).format(decls=decls) 

3485 ) 

3486 

3487 if not opts and not secondary_opts: 

3488 raise TypeError( 

3489 _( 

3490 "No options defined but a name was passed ({name})." 

3491 " Did you mean to declare an argument instead? Did" 

3492 " you mean to pass '--{name}'?" 

3493 ).format(name=name) 

3494 ) 

3495 

3496 if explicit_name is not None: 

3497 self._check_name_is_normalized(explicit_name, decls) 

3498 

3499 self._check_name_is_usable(name, decls) 

3500 

3501 return name, opts, secondary_opts 

3502 

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

3504 if self.multiple: 

3505 action = "append" 

3506 elif self.count: 

3507 action = "count" 

3508 else: 

3509 action = "store" 

3510 

3511 if self.is_flag: 

3512 action = f"{action}_const" 

3513 

3514 if self.is_bool_flag and self.secondary_opts: 

3515 parser.add_option( 

3516 obj=self, opts=self.opts, dest=self.name, action=action, const=True 

3517 ) 

3518 parser.add_option( 

3519 obj=self, 

3520 opts=self.secondary_opts, 

3521 dest=self.name, 

3522 action=action, 

3523 const=False, 

3524 ) 

3525 else: 

3526 parser.add_option( 

3527 obj=self, 

3528 opts=self.opts, 

3529 dest=self.name, 

3530 action=action, 

3531 # ``flag_activation_value`` resolves UNSET to the right parser-store 

3532 # constant (``True`` for bool flags) so the raw :attr:`flag_value` 

3533 # can keep the sentinel. 

3534 const=self.flag_activation_value, 

3535 ) 

3536 else: 

3537 parser.add_option( 

3538 obj=self, 

3539 opts=self.opts, 

3540 dest=self.name, 

3541 action=action, 

3542 nargs=self.nargs, 

3543 ) 

3544 

3545 def get_help_spec(self, ctx: Context) -> str: 

3546 """Returns the left column of the option's help record: its spellings 

3547 and metavar, like ``-v, --verbose`` or ``-c, --config TEXT``. 

3548 

3549 Unlike :meth:`get_help_record`, the spec is produced even when the 

3550 option is :attr:`hidden`. 

3551 

3552 .. versionadded:: 8.5.1 

3553 """ 

3554 any_prefix_is_slash = False 

3555 

3556 def _write_opts(opts: cabc.Sequence[str]) -> str: 

3557 nonlocal any_prefix_is_slash 

3558 

3559 rv, any_slashes = join_options(opts) 

3560 

3561 if any_slashes: 

3562 any_prefix_is_slash = True 

3563 

3564 if not self.is_flag and not self.count: 

3565 rv += f" {self.make_metavar(ctx=ctx)}" 

3566 

3567 return rv 

3568 

3569 rv = [_write_opts(self.opts)] 

3570 

3571 if self.secondary_opts: 

3572 rv.append(_write_opts(self.secondary_opts)) 

3573 

3574 return ("; " if any_prefix_is_slash else " / ").join(rv) 

3575 

3576 def get_help_record(self, ctx: Context) -> tuple[str, str] | None: 

3577 if self.hidden: 

3578 return None 

3579 

3580 help = self.help or "" 

3581 

3582 extra = self.get_help_extra(ctx) 

3583 extra_items = [] 

3584 if "envvars" in extra: 

3585 extra_items.append( 

3586 _("env var: {var}").format(var=", ".join(extra["envvars"])) 

3587 ) 

3588 if "default" in extra: 

3589 extra_items.append(_("default: {default}").format(default=extra["default"])) 

3590 if "range" in extra: 

3591 extra_items.append(extra["range"]) 

3592 if "required" in extra: 

3593 extra_items.append(_(extra["required"])) 

3594 

3595 if extra_items: 

3596 extra_str = "; ".join(extra_items) 

3597 help = f"{help} [{extra_str}]" if help else f"[{extra_str}]" 

3598 

3599 return self.get_help_spec(ctx), help 

3600 

3601 def get_help_extra(self, ctx: Context) -> types.OptionHelpExtra: 

3602 extra: types.OptionHelpExtra = {} 

3603 

3604 if self.show_envvar: 

3605 envvar = self.envvar 

3606 

3607 if not envvar and ( 

3608 self.allow_from_autoenv 

3609 and ctx.auto_envvar_prefix is not None 

3610 and self.name 

3611 ): 

3612 envvar = f"{ctx.auto_envvar_prefix}_{self.name.upper()}" 

3613 

3614 if envvar: 

3615 if isinstance(envvar, str): 

3616 extra["envvars"] = (envvar,) 

3617 else: 

3618 extra["envvars"] = tuple(str(d) for d in envvar) 

3619 

3620 # Temporarily enable resilient parsing to avoid type casting 

3621 # failing for the default. Might be possible to extend this to 

3622 # help formatting in general. 

3623 resilient = ctx.resilient_parsing 

3624 ctx.resilient_parsing = True 

3625 

3626 try: 

3627 default_value = self.get_default(ctx, call=False) 

3628 finally: 

3629 ctx.resilient_parsing = resilient 

3630 

3631 show_default = False 

3632 show_default_is_str = False 

3633 

3634 if self.show_default is not None: 

3635 if isinstance(self.show_default, str): 

3636 show_default_is_str = show_default = True 

3637 else: 

3638 show_default = self.show_default 

3639 elif ctx.show_default is not None: 

3640 show_default = ctx.show_default 

3641 

3642 if show_default_is_str or ( 

3643 show_default and (default_value not in (None, UNSET)) 

3644 ): 

3645 if show_default_is_str: 

3646 default_string = f"({self.show_default})" 

3647 elif isinstance(default_value, (list, tuple)): 

3648 default_string = ", ".join(str(d) for d in default_value) 

3649 elif isinstance(default_value, enum.Enum): 

3650 default_string = default_value.name 

3651 elif inspect.isfunction(default_value): 

3652 default_string = _("(dynamic)") 

3653 elif self.is_bool_flag and self.secondary_opts: 

3654 # For boolean flags that have distinct True/False opts, 

3655 # use the opt without prefix instead of the value. 

3656 default_string = _split_opt( 

3657 (self.opts if default_value else self.secondary_opts)[0] 

3658 )[1] 

3659 elif self.is_bool_flag and not self.secondary_opts and not default_value: 

3660 default_string = "" 

3661 elif isinstance(default_value, str) and default_value == "": 

3662 default_string = '""' 

3663 else: 

3664 default_string = str(default_value) 

3665 

3666 if default_string: 

3667 extra["default"] = default_string 

3668 

3669 if ( 

3670 isinstance(self.type, types._NumberRangeBase) 

3671 # skip count with default range type 

3672 and not (self.count and self.type.min == 0 and self.type.max is None) 

3673 ): 

3674 range_str = self.type._describe_range() 

3675 

3676 if range_str: 

3677 extra["range"] = range_str 

3678 

3679 if self.required: 

3680 extra["required"] = "required" 

3681 

3682 return extra 

3683 

3684 def prompt_for_value(self, ctx: Context) -> t.Any: 

3685 """This is an alternative flow that can be activated in the full 

3686 value processing if a value does not exist. It will prompt the 

3687 user until a valid value exists and then returns the processed 

3688 value as result. 

3689 """ 

3690 assert self.prompt is not None 

3691 

3692 # Calculate the default before prompting anything to lock in the value before 

3693 # attempting any user interaction. 

3694 default = self.get_default(ctx) 

3695 

3696 # A boolean flag can use a simplified [y/n] confirmation prompt. 

3697 if self.is_bool_flag: 

3698 # If we have no boolean default, we force the user to explicitly provide 

3699 # one. 

3700 if default in (UNSET, None): 

3701 default = None 

3702 # Nothing prevent you to declare an option that is simultaneously: 

3703 # 1) auto-detected as a boolean flag, 

3704 # 2) allowed to prompt, and 

3705 # 3) still declare a non-boolean default. 

3706 # This forced casting into a boolean is necessary to align any non-boolean 

3707 # default to the prompt, which is going to be a [y/n]-style confirmation 

3708 # because the option is still a boolean flag. That way, instead of [y/n], we 

3709 # get [Y/n] or [y/N] depending on the truthy value of the default. 

3710 else: 

3711 default = bool(default) 

3712 return confirm(self.prompt, default) 

3713 

3714 # If show_default is given, provide this to `prompt` as well, 

3715 # otherwise we use `prompt`'s default behavior 

3716 prompt_kwargs: t.Any = {} 

3717 if self.show_default is not None: 

3718 prompt_kwargs["show_default"] = self.show_default 

3719 

3720 return prompt( 

3721 self.prompt, 

3722 # Use ``None`` to inform the prompt() function to reiterate until a valid 

3723 # value is provided by the user if we have no default. 

3724 default=self._hide_unset(default), 

3725 type=self.type, 

3726 hide_input=self.hide_input, 

3727 show_choices=self.show_choices, 

3728 confirmation_prompt=self.confirmation_prompt, 

3729 value_proc=lambda x: self.process_value(ctx, x), 

3730 **prompt_kwargs, 

3731 ) 

3732 

3733 def resolve_envvar_value(self, ctx: Context) -> str | None: 

3734 """:class:`Option` resolves its environment variable the same way as 

3735 :func:`Parameter.resolve_envvar_value`, but it also supports 

3736 :attr:`Context.auto_envvar_prefix`. If we could not find an environment from 

3737 the :attr:`envvar` property, we fallback on :attr:`Context.auto_envvar_prefix` 

3738 to build dynamiccaly the environment variable name using the 

3739 :python:`{ctx.auto_envvar_prefix}_{self.name.upper()}` template. 

3740 

3741 :meta private: 

3742 """ 

3743 rv = super().resolve_envvar_value(ctx) 

3744 

3745 if rv is not None: 

3746 return rv 

3747 

3748 if self.allow_from_autoenv and ctx.auto_envvar_prefix is not None and self.name: 

3749 envvar = f"{ctx.auto_envvar_prefix}_{self.name.upper()}" 

3750 rv = os.environ.get(envvar) 

3751 

3752 if rv: 

3753 return rv 

3754 

3755 return None 

3756 

3757 def value_from_envvar(self, ctx: Context) -> t.Any: 

3758 """For :class:`Option`, this method processes the raw environment variable 

3759 string the same way as :func:`Parameter.value_from_envvar` does. 

3760 

3761 But in the case of non-boolean flags, the value is analyzed to determine if the 

3762 flag is activated or not, and returns a boolean of its activation, or the 

3763 :attr:`flag_value` if the latter is set. 

3764 

3765 This method also takes care of repeated options (i.e. options with 

3766 :attr:`multiple` set to ``True``). 

3767 

3768 :meta private: 

3769 """ 

3770 rv = self.resolve_envvar_value(ctx) 

3771 

3772 # Absent environment variable or an empty string is interpreted as unset. 

3773 if rv is None: 

3774 return None 

3775 

3776 # Non-boolean flags are more liberal in what they accept. But a flag being a 

3777 # flag, its envvar value still needs to be analyzed to determine if the flag is 

3778 # activated or not. 

3779 if self.is_flag and not self.is_bool_flag: 

3780 # An exact match against ``flag_value`` (a non-bool flag always has one 

3781 # explicitly set) returns it directly. Otherwise the value is analyzed as a 

3782 # boolean: a truthy reading activates the flag and the function receives 

3783 # ``flag_value``; a falsy reading produces ``False``; an unrecognized 

3784 # reading falls through as ``None``. Folding the substitution here means 

3785 # :meth:`consume_value` no longer has to repeat it in a source-checked 

3786 # branch. 

3787 if rv == self.flag_value: 

3788 return self.flag_value 

3789 parsed = types.BoolParamType.str_to_bool(rv) 

3790 if parsed is None: 

3791 return None 

3792 return self.flag_value if parsed else False 

3793 

3794 # Split the envvar value if it is allowed to be repeated. 

3795 value_depth = (self.nargs != 1) + bool(self.multiple) 

3796 if value_depth > 0: 

3797 multi_rv = self.type.split_envvar_value(rv) 

3798 if self.multiple and self.nargs != 1: 

3799 multi_rv = batch(multi_rv, self.nargs) # type: ignore[assignment] 

3800 

3801 return multi_rv 

3802 

3803 return rv 

3804 

3805 def consume_value( 

3806 self, ctx: Context, opts: cabc.Mapping[str, Parameter] 

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

3808 """For :class:`Option`, the value can be collected from an interactive prompt 

3809 if the option is a flag that needs a value (and the :attr:`prompt` property is 

3810 set). 

3811 

3812 Additionally, this method handles flag option that are activated without a 

3813 value, in which case the :attr:`flag_value` is returned. 

3814 

3815 :meta private: 

3816 """ 

3817 value, source = super().consume_value(ctx, opts) 

3818 

3819 # The parser emits a sentinel when a flag is allowed to be used without a value. 

3820 # Resolve it to a prompt or to the activation value depending on the option's 

3821 # configuration. 

3822 if value is FLAG_NEEDS_VALUE: 

3823 # If the option allows for a prompt, start an interaction with the user. 

3824 if self.prompt is not None and not ctx.resilient_parsing: 

3825 value = self.prompt_for_value(ctx) 

3826 source = ParameterSource.PROMPT 

3827 # Else the flag takes its activation value (resolves UNSET). 

3828 else: 

3829 value = self.flag_activation_value 

3830 source = ParameterSource.COMMANDLINE 

3831 

3832 # Re-interpret a multiple option that the parser sent through as a list still 

3833 # containing the FLAG_NEEDS_VALUE sentinel, replacing each occurrence with the 

3834 # activation value. 

3835 elif ( 

3836 self.multiple 

3837 and value is not UNSET 

3838 and isinstance(value, cabc.Iterable) 

3839 and source < ParameterSource.DEFAULT_MAP 

3840 and any(v is FLAG_NEEDS_VALUE for v in value) 

3841 ): 

3842 value = [ 

3843 self.flag_activation_value if v is FLAG_NEEDS_VALUE else v 

3844 for v in value 

3845 ] 

3846 source = ParameterSource.COMMANDLINE 

3847 

3848 # The value wasn't set, or used the param's default, prompt for one to the user 

3849 # if prompting is enabled. 

3850 elif ( 

3851 (value is UNSET or source >= ParameterSource.DEFAULT_MAP) 

3852 and self.prompt is not None 

3853 and (self.required or self.prompt_required) 

3854 and not ctx.resilient_parsing 

3855 ): 

3856 value = self.prompt_for_value(ctx) 

3857 source = ParameterSource.PROMPT 

3858 

3859 return value, source 

3860 

3861 def process_value(self, ctx: Context, value: t.Any) -> t.Any: 

3862 # process_value has to be overridden on Options in order to capture 

3863 # `value == UNSET` cases before `type_cast_value()` gets called. 

3864 if self.is_flag and not self.required and self.is_bool_flag and value is UNSET: 

3865 value = False 

3866 

3867 if self.callback is not None: 

3868 value = self.callback(ctx, self, value) 

3869 

3870 return value 

3871 

3872 # in the normal case, rely on Parameter.process_value 

3873 return super().process_value(ctx, value) 

3874 

3875 

3876class Argument(Parameter): 

3877 """Arguments are positional parameters to a command. They generally 

3878 provide fewer features than options but can have infinite ``nargs`` 

3879 and are required by default. 

3880 

3881 All parameters are passed onwards to the constructor of :class:`Parameter`. 

3882 

3883 :param help: the help string. 

3884 

3885 .. versionchanged:: 8.5.0 

3886 Added the ``help`` parameter. 

3887 """ 

3888 

3889 param_type_name = "argument" 

3890 

3891 def __init__( 

3892 self, 

3893 param_decls: cabc.Sequence[str], 

3894 required: bool | None = None, 

3895 help: str | None = None, 

3896 **attrs: t.Any, 

3897 ) -> None: 

3898 # Auto-detect the requirement status of the argument if not explicitly set. 

3899 if required is None: 

3900 # The argument gets automatically required if it has no explicit default 

3901 # value set and is setup to match at least one value. 

3902 if attrs.get("default", UNSET) is UNSET: 

3903 required = attrs.get("nargs", 1) > 0 

3904 # If the argument has a default value, it is not required. 

3905 else: 

3906 required = False 

3907 

3908 if "multiple" in attrs: 

3909 raise TypeError("__init__() got an unexpected keyword argument 'multiple'.") 

3910 

3911 super().__init__(param_decls, required=required, help=help, **attrs) 

3912 

3913 @property 

3914 def spec(self) -> str: 

3915 """Returns the argument's metavar, which is how the user reads it in 

3916 ``--help``. An argument has no flag to spell, so this is the 

3917 :attr:`metavar` if one was given, and the uppercased :attr:`name` 

3918 otherwise. 

3919 

3920 .. versionadded:: 8.6.0 

3921 """ 

3922 if self.metavar is not None: 

3923 return self.metavar 

3924 return self.name.upper() 

3925 

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

3927 if self.metavar is not None: 

3928 return self.metavar 

3929 var = self.type.get_metavar(param=self, ctx=ctx) 

3930 if not var: 

3931 var = self.name.upper() 

3932 # Types like ``Choice`` and ``DateTime`` already surround their metavar 

3933 # with square brackets to enumerate the allowed values. Reuse those 

3934 # outer brackets as the optional-argument indicator instead of wrapping 

3935 # the metavar in a second pair, which would produce ``[[a|b|c]]``. 

3936 already_bracketed = var.startswith("[") and var.endswith("]") 

3937 if self.deprecated: 

3938 var += "!" 

3939 if not self.required and not already_bracketed: 

3940 var = f"[{var}]" 

3941 if self.nargs != 1: 

3942 var += "..." 

3943 return var 

3944 

3945 def _parse_decls( 

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

3947 ) -> tuple[str, list[str], list[str]]: 

3948 if not decls: 

3949 if not expose_value: 

3950 self._check_name_is_usable("", decls) 

3951 return "", [], [] 

3952 raise TypeError("Argument is marked as exposed, but does not have a name.") 

3953 if len(decls) == 1: 

3954 name = arg = decls[0] 

3955 name = name.replace("-", "_").lower() 

3956 else: 

3957 raise TypeError( 

3958 _( 

3959 "Arguments take exactly one parameter declaration, got" 

3960 " {length}: {decls}." 

3961 ).format(length=len(decls), decls=decls) 

3962 ) 

3963 self._check_name_is_usable(name, decls) 

3964 return name, [arg], [] 

3965 

3966 def get_usage_pieces(self, ctx: Context) -> list[str]: 

3967 return [self.make_metavar(ctx)] 

3968 

3969 def get_help_spec(self, ctx: Context) -> str: 

3970 """Returns the left column of the argument's help record: its metavar, 

3971 like ``FILENAME`` or ``[FILENAME]``. 

3972 

3973 .. versionadded:: 8.6.0 

3974 """ 

3975 return self.make_metavar(ctx) 

3976 

3977 def get_help_record(self, ctx: Context) -> tuple[str, str]: 

3978 """Returns the argument's help row: its metavar and its help text. 

3979 

3980 Unlike :meth:`Option.get_help_record`, this never returns ``None``. An 

3981 argument cannot be hidden, so an undocumented one still gets a row, with 

3982 an empty description. 

3983 

3984 .. versionchanged:: 8.5.1 

3985 Always returns a tuple. It used to return ``None`` when ``help`` was 

3986 not set. 

3987 """ 

3988 return self.get_help_spec(ctx), self.help or "" 

3989 

3990 def get_error_hint(self, ctx: Context | None) -> str: 

3991 if ctx is not None: 

3992 return f"'{self.get_help_spec(ctx)}'" 

3993 return f"'{self.spec}'" 

3994 

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

3996 parser.add_argument(dest=self.name, nargs=self.nargs, obj=self) 

3997 

3998 

3999def __getattr__(name: str) -> object: 

4000 import warnings 

4001 

4002 if name == "BaseCommand": 

4003 warnings.warn( 

4004 "'BaseCommand' is deprecated and will be removed in Click 9.0. Use" 

4005 " 'Command' instead.", 

4006 DeprecationWarning, 

4007 stacklevel=2, 

4008 ) 

4009 return _BaseCommand 

4010 

4011 if name == "MultiCommand": 

4012 warnings.warn( 

4013 "'MultiCommand' is deprecated and will be removed in Click 9.0. Use" 

4014 " 'Group' instead.", 

4015 DeprecationWarning, 

4016 stacklevel=2, 

4017 ) 

4018 return _MultiCommand 

4019 

4020 raise AttributeError(name)