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

1390 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 TracebackType 

22 

23from . import types 

24from ._utils import FLAG_NEEDS_VALUE 

25from ._utils import UNSET 

26from .exceptions import Abort 

27from .exceptions import BadParameter 

28from .exceptions import ClickException 

29from .exceptions import Exit 

30from .exceptions import MissingParameter 

31from .exceptions import NoArgsIsHelpError 

32from .exceptions import NoSuchCommand 

33from .exceptions import UsageError 

34from .formatting import HelpFormatter 

35from .formatting import join_options 

36from .globals import pop_context 

37from .globals import push_context 

38from .parser import _OptionParser 

39from .parser import _split_opt 

40from .termui import confirm 

41from .termui import prompt 

42from .termui import style 

43from .utils import _detect_program_name 

44from .utils import _expand_args 

45from .utils import _make_default_short_help 

46from .utils import _PacifyFlushWrapper 

47from .utils import echo 

48from .utils import make_str 

49 

50if t.TYPE_CHECKING: 

51 from typing_extensions import Self 

52 

53 from .shell_completion import CompletionItem 

54 

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

56V = t.TypeVar("V") 

57 

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

59# expected to claim it. 

60_HELP_OPTION_STORAGE_NAME = "_click_default_help" 

61 

62 

63def _complete_visible_commands( 

64 ctx: Context, incomplete: str 

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

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

67 incomplete value and aren't hidden. 

68 

69 :param ctx: Invocation context for the group. 

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

71 """ 

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

73 

74 for name in multi.list_commands(ctx): 

75 if name.startswith(incomplete): 

76 command = multi.get_command(ctx, name) 

77 

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

79 yield name, command 

80 

81 

82def _check_nested_chain( 

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

84) -> None: 

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

86 return 

87 

88 if register: 

89 message = ( 

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

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

92 ) 

93 else: 

94 message = ( 

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

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

97 ) 

98 

99 raise RuntimeError(message) 

100 

101 

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

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

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

105 if isinstance(deprecated, str): 

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

107 return f"({label})" 

108 

109 

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

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

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

113 """ 

114 if isinstance(deprecated, str): 

115 return f" {deprecated}" 

116 return "" 

117 

118 

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

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

121 

122 

123@contextmanager 

124def augment_usage_errors( 

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

126) -> cabc.Generator[None]: 

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

128 try: 

129 yield 

130 except BadParameter as e: 

131 if e.ctx is None: 

132 e.ctx = ctx 

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

134 e.param = param 

135 raise 

136 except UsageError as e: 

137 if e.ctx is None: 

138 e.ctx = ctx 

139 raise 

140 

141 

142def iter_params_for_processing( 

143 invocation_order: cabc.Sequence[Parameter], 

144 declaration_order: cabc.Sequence[Parameter], 

145) -> list[Parameter]: 

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

147 

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

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

150 

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

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

153 

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

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

156 """ 

157 

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

159 try: 

160 idx: float = invocation_order.index(item) 

161 except ValueError: 

162 idx = float("inf") 

163 

164 return not item.is_eager, idx 

165 

166 return sorted(declaration_order, key=sort_key) 

167 

168 

169class ParameterSource(enum.IntEnum): 

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

171 parameter's value. 

172 

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

174 source for a parameter by name. 

175 

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

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

178 

179 .. code-block:: python 

180 

181 source = ctx.get_parameter_source("port") 

182 if source < click.ParameterSource.DEFAULT_MAP: 

183 ... # value was explicitly set 

184 

185 .. versionchanged:: 8.3.3 

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

187 least explicit. Supports comparison operators. 

188 

189 .. versionchanged:: 8.0 

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

191 

192 .. versionchanged:: 8.0 

193 Added the ``PROMPT`` value. 

194 """ 

195 

196 PROMPT = enum.auto() 

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

198 COMMANDLINE = enum.auto() 

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

200 ENVIRONMENT = enum.auto() 

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

202 DEFAULT_MAP = enum.auto() 

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

204 DEFAULT = enum.auto() 

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

206 

207 

208class Context: 

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

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

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

212 

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

214 control special execution features such as reading data from 

215 environment variables. 

216 

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

218 :meth:`close` on teardown. 

219 

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

221 :param parent: the parent context. 

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

223 is the most descriptive name for the script or 

224 command. For the toplevel script it is usually 

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

226 the name of the script. 

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

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

229 variables. If this is `None` then reading 

230 from environment variables is disabled. This 

231 does not affect manually set environment 

232 variables which are always read. 

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

234 for parameters. 

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

236 inherit from parent context. If no context 

237 defines the terminal width then auto 

238 detection will be applied. 

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

240 Click (this currently only affects help 

241 pages). This defaults to 80 characters if 

242 not overridden. In other words: even if the 

243 terminal is larger than that, Click will not 

244 format things wider than 80 characters by 

245 default. In addition to that, formatters might 

246 add some safety mapping on the right. 

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

248 parse without any interactivity or callback 

249 invocation. Default values will also be 

250 ignored. This is useful for implementing 

251 things such as completion support. 

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

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

254 kept on the context. The default is to inherit 

255 from the command. 

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

257 and arguments cannot be mixed. The 

258 default is to inherit from the command. 

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

260 not know and keeps them for later 

261 processing. 

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

263 the default help parameter is named. The 

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

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

266 normalize tokens (options, choices, 

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

268 implement case insensitive behavior. 

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

270 default is autodetection. This is only needed if ANSI 

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

272 default not the case. This for instance would affect 

273 help output. 

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

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

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

277 specific command. 

278 

279 .. versionchanged:: 8.2 

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

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

282 

283 .. versionchanged:: 8.1 

284 The ``show_default`` parameter is overridden by 

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

286 

287 .. versionchanged:: 8.0 

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

289 parent context. 

290 

291 .. versionchanged:: 7.1 

292 Added the ``show_default`` parameter. 

293 

294 .. versionchanged:: 4.0 

295 Added the ``color``, ``ignore_unknown_options``, and 

296 ``max_content_width`` parameters. 

297 

298 .. versionchanged:: 3.0 

299 Added the ``allow_extra_args`` and ``allow_interspersed_args`` 

300 parameters. 

301 

302 .. versionchanged:: 2.0 

303 Added the ``resilient_parsing``, ``help_option_names``, and 

304 ``token_normalize_func`` parameters. 

305 """ 

306 

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

308 #: 

309 #: .. versionadded:: 8.0 

310 formatter_class: type[HelpFormatter] = HelpFormatter 

311 

312 parent: Context | None 

313 command: Command 

314 info_name: str | None 

315 params: dict[str, t.Any] 

316 args: list[str] 

317 _protected_args: list[str] 

318 _opt_prefixes: set[str] 

319 obj: t.Any 

320 _meta: dict[str, t.Any] 

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

322 invoked_subcommand: str | None 

323 terminal_width: int | None 

324 max_content_width: int | None 

325 allow_extra_args: bool 

326 allow_interspersed_args: bool 

327 ignore_unknown_options: bool 

328 help_option_names: list[str] 

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

330 resilient_parsing: bool 

331 auto_envvar_prefix: str | None 

332 color: bool | None 

333 show_default: bool | None 

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

335 _depth: int 

336 _parameter_source: dict[str, ParameterSource] 

337 _param_default_explicit: dict[str, bool] 

338 _exit_stack: ExitStack 

339 

340 def __init__( 

341 self, 

342 command: Command, 

343 parent: Context | None = None, 

344 info_name: str | None = None, 

345 obj: t.Any | None = None, 

346 auto_envvar_prefix: str | None = None, 

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

348 terminal_width: int | None = None, 

349 max_content_width: int | None = None, 

350 resilient_parsing: bool = False, 

351 allow_extra_args: bool | None = None, 

352 allow_interspersed_args: bool | None = None, 

353 ignore_unknown_options: bool | None = None, 

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

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

356 color: bool | None = None, 

357 show_default: bool | None = None, 

358 ) -> None: 

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

360 self.parent = parent 

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

362 self.command = command 

363 #: the descriptive information name 

364 self.info_name = info_name 

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

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

367 self.params = {} 

368 #: the leftover arguments. 

369 self.args = [] 

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

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

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

373 #: to implement nested parsing. 

374 self._protected_args = [] 

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

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

377 

378 if obj is None and parent is not None: 

379 obj = parent.obj 

380 

381 #: the user object stored. 

382 self.obj = obj 

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

384 

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

386 if ( 

387 default_map is None 

388 and info_name is not None 

389 and parent is not None 

390 and parent.default_map is not None 

391 ): 

392 default_map = parent.default_map.get(info_name) 

393 

394 self.default_map = default_map 

395 

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

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

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

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

400 #: the name of the subcommand to execute. 

401 #: 

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

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

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

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

406 self.invoked_subcommand = None 

407 

408 if terminal_width is None and parent is not None: 

409 terminal_width = parent.terminal_width 

410 

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

412 self.terminal_width = terminal_width 

413 

414 if max_content_width is None and parent is not None: 

415 max_content_width = parent.max_content_width 

416 

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

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

419 self.max_content_width = max_content_width 

420 

421 if allow_extra_args is None: 

422 allow_extra_args = command.allow_extra_args 

423 

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

425 #: fail on parsing. 

426 #: 

427 #: .. versionadded:: 3.0 

428 self.allow_extra_args = allow_extra_args 

429 

430 if allow_interspersed_args is None: 

431 allow_interspersed_args = command.allow_interspersed_args 

432 

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

434 #: options or not. 

435 #: 

436 #: .. versionadded:: 3.0 

437 self.allow_interspersed_args = allow_interspersed_args 

438 

439 if ignore_unknown_options is None: 

440 ignore_unknown_options = command.ignore_unknown_options 

441 

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

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

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

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

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

447 #: forward all arguments. 

448 #: 

449 #: .. versionadded:: 4.0 

450 self.ignore_unknown_options = ignore_unknown_options 

451 

452 if help_option_names is None: 

453 if parent is not None: 

454 help_option_names = parent.help_option_names 

455 else: 

456 help_option_names = ["--help"] 

457 

458 #: The names for the help options. 

459 self.help_option_names = help_option_names 

460 

461 if token_normalize_func is None and parent is not None: 

462 token_normalize_func = parent.token_normalize_func 

463 

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

465 #: options, choices, commands etc. 

466 self.token_normalize_func = token_normalize_func 

467 

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

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

470 #: will be ignored. Useful for completion. 

471 self.resilient_parsing = resilient_parsing 

472 

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

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

475 # prefix automatically. 

476 if auto_envvar_prefix is None: 

477 if ( 

478 parent is not None 

479 and parent.auto_envvar_prefix is not None 

480 and self.info_name is not None 

481 ): 

482 auto_envvar_prefix = ( 

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

484 ) 

485 else: 

486 auto_envvar_prefix = auto_envvar_prefix.upper() 

487 

488 if auto_envvar_prefix is not None: 

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

490 

491 self.auto_envvar_prefix = auto_envvar_prefix 

492 

493 if color is None and parent is not None: 

494 color = parent.color 

495 

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

497 self.color = color 

498 

499 if show_default is None and parent is not None: 

500 show_default = parent.show_default 

501 

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

503 self.show_default = show_default 

504 

505 self._close_callbacks = [] 

506 self._depth = 0 

507 self._parameter_source = {} 

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

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

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

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

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

513 self._param_default_explicit = {} 

514 self._exit_stack = ExitStack() 

515 

516 @property 

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

518 import warnings 

519 

520 warnings.warn( 

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

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

523 DeprecationWarning, 

524 stacklevel=2, 

525 ) 

526 return self._protected_args 

527 

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

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

530 user-facing documentation. This traverses the entire CLI 

531 structure. 

532 

533 .. code-block:: python 

534 

535 with Context(cli) as ctx: 

536 info = ctx.to_info_dict() 

537 

538 .. versionadded:: 8.0 

539 """ 

540 return { 

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

542 "info_name": self.info_name, 

543 "allow_extra_args": self.allow_extra_args, 

544 "allow_interspersed_args": self.allow_interspersed_args, 

545 "ignore_unknown_options": self.ignore_unknown_options, 

546 "auto_envvar_prefix": self.auto_envvar_prefix, 

547 } 

548 

549 def __enter__(self) -> Self: 

550 self._depth += 1 

551 push_context(self) 

552 return self 

553 

554 def __exit__( 

555 self, 

556 exc_type: type[BaseException] | None, 

557 exc_value: BaseException | None, 

558 tb: TracebackType | None, 

559 ) -> bool | None: 

560 self._depth -= 1 

561 exit_result: bool | None = None 

562 if self._depth == 0: 

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

564 pop_context() 

565 

566 return exit_result 

567 

568 @contextmanager 

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

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

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

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

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

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

575 

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

577 used as a context manager. 

578 

579 Example usage:: 

580 

581 with ctx.scope(): 

582 assert get_current_context() is ctx 

583 

584 This is equivalent:: 

585 

586 with ctx: 

587 assert get_current_context() is ctx 

588 

589 .. versionadded:: 5.0 

590 

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

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

593 some situations the context only wants to be 

594 temporarily pushed in which case this can be disabled. 

595 Nested pushes automatically defer the cleanup. 

596 """ 

597 if not cleanup: 

598 self._depth += 1 

599 try: 

600 with self as rv: 

601 yield rv 

602 finally: 

603 if not cleanup: 

604 self._depth -= 1 

605 

606 @property 

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

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

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

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

611 that code to manage this dictionary well. 

612 

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

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

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

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

617 the system. 

618 

619 Example usage:: 

620 

621 LANG_KEY = f'{__name__}.lang' 

622 

623 def set_language(value): 

624 ctx = get_current_context() 

625 ctx.meta[LANG_KEY] = value 

626 

627 def get_language(): 

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

629 

630 .. versionadded:: 5.0 

631 """ 

632 return self._meta 

633 

634 def make_formatter(self) -> HelpFormatter: 

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

636 usage output. 

637 

638 To quickly customize the formatter class used without overriding 

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

640 

641 .. versionchanged:: 8.0 

642 Added the :attr:`formatter_class` attribute. 

643 """ 

644 return self.formatter_class( 

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

646 ) 

647 

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

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

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

651 popped. 

652 

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

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

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

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

657 

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

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

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

661 

662 .. code-block:: python 

663 

664 @click.group() 

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

666 @click.pass_context 

667 def cli(ctx): 

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

669 

670 :param context_manager: The context manager to enter. 

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

672 

673 .. versionadded:: 8.0 

674 """ 

675 return self._exit_stack.enter_context(context_manager) 

676 

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

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

679 

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

681 execution. Resources that support Python's context manager 

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

683 registered with :meth:`with_resource` instead. 

684 

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

686 """ 

687 return self._exit_stack.callback(f) 

688 

689 def close(self) -> None: 

690 """Invoke all close callbacks registered with 

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

692 with :meth:`with_resource`. 

693 """ 

694 self._close_with_exception_info(None, None, None) 

695 

696 def _close_with_exception_info( 

697 self, 

698 exc_type: type[BaseException] | None, 

699 exc_value: BaseException | None, 

700 tb: TracebackType | None, 

701 ) -> bool | None: 

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

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

704 using :meth;`with_resource` 

705 

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

707 """ 

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

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

710 self._exit_stack = ExitStack() 

711 

712 return exit_result 

713 

714 @property 

715 def command_path(self) -> str: 

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

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

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

719 """ 

720 rv = "" 

721 if self.info_name is not None: 

722 rv = self.info_name 

723 if self.parent is not None: 

724 parent_command_path = [self.parent.command_path] 

725 

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

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

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

729 

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

731 return rv.lstrip() 

732 

733 def find_root(self) -> Context: 

734 """Finds the outermost context.""" 

735 node = self 

736 while node.parent is not None: 

737 node = node.parent 

738 return node 

739 

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

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

742 node: Context | None = self 

743 

744 while node is not None: 

745 if isinstance(node.obj, object_type): 

746 return node.obj 

747 

748 node = node.parent 

749 

750 return None 

751 

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

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

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

755 """ 

756 rv = self.find_object(object_type) 

757 if rv is None: 

758 self.obj = rv = object_type() 

759 return rv 

760 

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

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

763 

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

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

766 :data:`UNSET` sentinel. 

767 """ 

768 return ( 

769 name is not None 

770 and self.default_map is not None 

771 and name in self.default_map 

772 and self.default_map[name] is not UNSET 

773 ) 

774 

775 @t.overload 

776 def lookup_default( 

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

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

779 

780 @t.overload 

781 def lookup_default( 

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

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

784 

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

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

787 

788 :param name: Name of the parameter. 

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

790 return the callable instead. 

791 

792 .. versionchanged:: 8.0 

793 Added the ``call`` parameter. 

794 """ 

795 if not self._default_map_has(name): 

796 return None 

797 

798 # Assert to make the type checker happy. 

799 assert self.default_map is not None 

800 value = self.default_map[name] 

801 

802 if call and callable(value): 

803 return value() 

804 

805 return value 

806 

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

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

809 message. 

810 

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

812 """ 

813 raise UsageError(message, self) 

814 

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

816 """Aborts the script.""" 

817 raise Abort() 

818 

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

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

821 

822 .. versionchanged:: 8.2 

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

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

825 """ 

826 self.close() 

827 raise Exit(code) 

828 

829 def get_usage(self) -> str: 

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

831 context and command. 

832 """ 

833 return self.command.get_usage(self) 

834 

835 def get_help(self) -> str: 

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

837 context and command. 

838 """ 

839 return self.command.get_help(self) 

840 

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

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

843 for a new command. 

844 

845 :meta private: 

846 """ 

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

848 

849 @t.overload 

850 def invoke( 

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

852 ) -> V: ... 

853 

854 @t.overload 

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

856 

857 def invoke( 

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

859 ) -> t.Any | V: 

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

861 are two ways to invoke this method: 

862 

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

864 keyword arguments are forwarded directly to the function. 

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

866 arguments are forwarded as well but proper click parameters 

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

868 will fill in defaults. 

869 

870 .. versionchanged:: 8.0 

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

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

873 

874 .. versionchanged:: 3.2 

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

876 """ 

877 if isinstance(callback, Command): 

878 other_cmd = callback 

879 

880 if other_cmd.callback is None: 

881 raise TypeError( 

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

883 ) 

884 else: 

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

886 

887 ctx = self._make_sub_context(other_cmd) 

888 

889 for param in other_cmd.params: 

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

891 default_value = param.get_default(ctx) 

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

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

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

895 # instead. Refs: 

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

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

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

899 if default_value is UNSET: 

900 default_value = None 

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

902 

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

904 # them on in subsequent calls. 

905 ctx.params.update(kwargs) 

906 else: 

907 ctx = self 

908 

909 with augment_usage_errors(self), ctx: 

910 return callback(*args, **kwargs) 

911 

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

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

914 arguments from the current context if the other command expects 

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

916 

917 .. versionchanged:: 8.0 

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

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

920 """ 

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

922 if not isinstance(cmd, Command): 

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

924 

925 for param in self.params: 

926 if param not in kwargs: 

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

928 

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

930 

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

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

933 from which the value of the parameter was obtained. 

934 

935 :param name: The name of the parameter. 

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

937 """ 

938 self._parameter_source[name] = source 

939 

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

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

942 from which the value of the parameter was obtained. 

943 

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

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

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

947 value was actually taken from the default. 

948 

949 :param name: The name of the parameter. 

950 :rtype: ParameterSource 

951 

952 .. versionchanged:: 8.0 

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

954 source. 

955 """ 

956 return self._parameter_source.get(name) 

957 

958 

959class Command: 

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

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

962 more parsing to commands nested below it. 

963 

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

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

966 passed to the context object. 

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

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

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

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

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

972 help page after everything else. 

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

974 shown on the command listing of the parent command. 

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

976 option. This can be disabled by this parameter. 

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

978 provided. This option is disabled by default. 

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

980 if no arguments are passed 

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

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

983 indicating that the command is deprecated and highlights 

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

985 by using a string as the value. 

986 

987 .. versionchanged:: 8.2 

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

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

990 deprecation message. 

991 

992 .. versionchanged:: 8.1 

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

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

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

996 

997 .. versionchanged:: 8.0 

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

999 

1000 .. versionchanged:: 7.1 

1001 Added the ``no_args_is_help`` parameter. 

1002 

1003 .. versionchanged:: 2.0 

1004 Added the ``context_settings`` parameter. 

1005 """ 

1006 

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

1008 #: 

1009 #: .. versionadded:: 8.0 

1010 context_class: type[Context] = Context 

1011 

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

1013 allow_extra_args = False 

1014 

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

1016 allow_interspersed_args = True 

1017 

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

1019 ignore_unknown_options = False 

1020 

1021 name: str | None 

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

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

1024 params: list[Parameter] 

1025 help: str | None 

1026 epilog: str | None 

1027 options_metavar: str | None 

1028 short_help: str | None 

1029 add_help_option: bool 

1030 _help_option: Option | None 

1031 no_args_is_help: bool 

1032 hidden: bool 

1033 deprecated: bool | str 

1034 

1035 def __init__( 

1036 self, 

1037 name: str | None, 

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

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

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

1041 help: str | None = None, 

1042 epilog: str | None = None, 

1043 short_help: str | None = None, 

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

1045 add_help_option: bool = True, 

1046 no_args_is_help: bool = False, 

1047 hidden: bool = False, 

1048 deprecated: bool | str = False, 

1049 ) -> None: 

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

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

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

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

1054 self.name = name 

1055 

1056 if context_settings is None: 

1057 context_settings = {} 

1058 

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

1060 self.context_settings = context_settings 

1061 

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

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

1064 self.callback = callback 

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

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

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

1068 self.params = params or [] 

1069 self.help = help 

1070 self.epilog = epilog 

1071 self.options_metavar = options_metavar 

1072 self.short_help = short_help 

1073 self.add_help_option = add_help_option 

1074 self._help_option = None 

1075 self.no_args_is_help = no_args_is_help 

1076 self.hidden = hidden 

1077 self.deprecated = deprecated 

1078 

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

1080 return { 

1081 "name": self.name, 

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

1083 "help": self.help, 

1084 "epilog": self.epilog, 

1085 "short_help": self.short_help, 

1086 "hidden": self.hidden, 

1087 "deprecated": self.deprecated, 

1088 } 

1089 

1090 def __repr__(self) -> str: 

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

1092 

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

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

1095 

1096 Calls :meth:`format_usage` internally. 

1097 """ 

1098 formatter = ctx.make_formatter() 

1099 self.format_usage(ctx, formatter) 

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

1101 

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

1103 params = self.params 

1104 help_option = self.get_help_option(ctx) 

1105 

1106 if help_option is not None: 

1107 params = [*params, help_option] 

1108 

1109 if __debug__: 

1110 import warnings 

1111 

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

1113 opts_counter = Counter(opts) 

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

1115 

1116 for duplicate_opt in duplicate_opts: 

1117 warnings.warn( 

1118 ( 

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

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

1121 ), 

1122 stacklevel=3, 

1123 ) 

1124 

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

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

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

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

1129 duplicate_names = ( 

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

1131 ) 

1132 

1133 for duplicate_name in duplicate_names: 

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

1135 

1136 if help_option in sharers: 

1137 warnings.warn( 

1138 ( 

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

1140 "automatic help option. Give the parameter a " 

1141 "different name." 

1142 ), 

1143 stacklevel=3, 

1144 ) 

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

1146 warnings.warn( 

1147 ( 

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

1149 "and another parameter. They will overwrite each " 

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

1151 "a unique name." 

1152 ), 

1153 stacklevel=3, 

1154 ) 

1155 

1156 return params 

1157 

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

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

1160 

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

1162 """ 

1163 pieces = self.collect_usage_pieces(ctx) 

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

1165 

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

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

1168 it as a list of strings. 

1169 """ 

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

1171 

1172 for param in self.get_params(ctx): 

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

1174 

1175 return rv 

1176 

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

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

1179 

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

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

1182 

1183 .. versionchanged:: 8.5.0 

1184 Names keep their declaration order. 

1185 """ 

1186 all_names = dict.fromkeys(ctx.help_option_names) 

1187 for param in self.params: 

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

1189 all_names.pop(name, None) 

1190 return list(all_names) 

1191 

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

1193 """Returns the help option object. 

1194 

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

1196 

1197 .. versionchanged:: 8.5.0 

1198 The help option stores its value under the reserved name 

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

1200 longer breaks parsing. 

1201 

1202 .. versionchanged:: 8.1.8 

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

1204 """ 

1205 help_option_names = self.get_help_option_names(ctx) 

1206 

1207 if not help_option_names or not self.add_help_option: 

1208 return None 

1209 

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

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

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

1213 # object comparison. 

1214 if self._help_option is None: 

1215 # Avoid circular import. 

1216 from .decorators import help_option 

1217 

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

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

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

1221 help_option(*help_option_names, _HELP_OPTION_STORAGE_NAME)(self) 

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

1223 

1224 return self._help_option 

1225 

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

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

1228 parser = _OptionParser(ctx) 

1229 for param in self.get_params(ctx): 

1230 param.add_to_parser(parser, ctx) 

1231 return parser 

1232 

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

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

1235 

1236 Calls :meth:`format_help` internally. 

1237 """ 

1238 formatter = ctx.make_formatter() 

1239 self.format_help(ctx, formatter) 

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

1241 

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

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

1244 long help string. 

1245 """ 

1246 if self.short_help: 

1247 text = inspect.cleandoc(self.short_help) 

1248 elif self.help: 

1249 text = _make_default_short_help(self.help, limit) 

1250 else: 

1251 text = "" 

1252 

1253 if self.deprecated: 

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

1255 

1256 return text.strip() 

1257 

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

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

1260 

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

1262 

1263 This calls the following methods: 

1264 

1265 - :meth:`format_usage` 

1266 - :meth:`format_help_text` 

1267 - :meth:`format_arguments` 

1268 - :meth:`format_options` 

1269 - :meth:`format_epilog` 

1270 """ 

1271 self.format_usage(ctx, formatter) 

1272 self.format_help_text(ctx, formatter) 

1273 self.format_arguments(ctx, formatter) 

1274 self.format_options(ctx, formatter) 

1275 self.format_epilog(ctx, formatter) 

1276 

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

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

1279 if self.help is not None: 

1280 # truncate the help text to the first form feed 

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

1282 else: 

1283 text = "" 

1284 

1285 if self.deprecated: 

1286 label = _format_deprecated_label(self.deprecated) 

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

1288 

1289 if text: 

1290 formatter.write_paragraph() 

1291 

1292 with formatter.indentation(): 

1293 formatter.write_text(text) 

1294 

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

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

1297 opts = [] 

1298 for param in self.get_params(ctx): 

1299 rv = param.get_help_record(ctx) 

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

1301 opts.append(rv) 

1302 

1303 if opts: 

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

1305 formatter.write_dl(opts) 

1306 

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

1308 """Writes the arguments that have a help record into the formatter.""" 

1309 args = [] 

1310 for param in self.get_params(ctx): 

1311 rv = param.get_help_record(ctx) 

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

1313 args.append(rv) 

1314 

1315 if args: 

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

1317 formatter.write_dl(args) 

1318 

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

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

1321 if self.epilog: 

1322 epilog = inspect.cleandoc(self.epilog) 

1323 formatter.write_paragraph() 

1324 

1325 with formatter.indentation(): 

1326 formatter.write_text(epilog) 

1327 

1328 def make_context( 

1329 self, 

1330 info_name: str | None, 

1331 args: list[str], 

1332 parent: Context | None = None, 

1333 **extra: t.Any, 

1334 ) -> Context: 

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

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

1337 invoke the actual command callback though. 

1338 

1339 To quickly customize the context class used without overriding 

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

1341 

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

1343 is the most descriptive name for the script or 

1344 command. For the toplevel script it's usually 

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

1346 the name of the command. 

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

1348 :param parent: the parent context if available. 

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

1350 constructor. 

1351 

1352 .. versionchanged:: 8.0 

1353 Added the :attr:`context_class` attribute. 

1354 """ 

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

1356 if key not in extra: 

1357 extra[key] = value 

1358 

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

1360 

1361 with ctx.scope(cleanup=False): 

1362 self.parse_args(ctx, args) 

1363 return ctx 

1364 

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

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

1367 raise NoArgsIsHelpError(ctx) 

1368 

1369 parser = self.make_parser(ctx) 

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

1371 

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

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

1374 

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

1376 # the `UNSET` sentinel. 

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

1378 # 

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

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

1381 # Refs: 

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

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

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

1385 if value is UNSET: 

1386 ctx.params[name] = None 

1387 

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

1389 ctx.fail( 

1390 ngettext( 

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

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

1393 len(args), 

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

1395 ) 

1396 

1397 ctx.args = args 

1398 ctx._opt_prefixes.update(parser._opt_prefixes) 

1399 return args 

1400 

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

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

1403 in the right way. 

1404 """ 

1405 if self.deprecated: 

1406 message = _( 

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

1408 ).format( 

1409 name=self.name, 

1410 extra_message=_format_deprecated_suffix(self.deprecated), 

1411 ) 

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

1413 

1414 if self.callback is not None: 

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

1416 

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

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

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

1420 

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

1422 commands are valid at any point during command completion. 

1423 

1424 :param ctx: Invocation context for this command. 

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

1426 

1427 .. versionadded:: 8.0 

1428 """ 

1429 from click.shell_completion import CompletionItem 

1430 

1431 results: list[CompletionItem] = [] 

1432 

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

1434 for param in self.get_params(ctx): 

1435 if ( 

1436 not isinstance(param, Option) 

1437 or param.hidden 

1438 or ( 

1439 not param.multiple 

1440 and ctx.get_parameter_source(param.name) 

1441 is ParameterSource.COMMANDLINE 

1442 ) 

1443 ): 

1444 continue 

1445 

1446 results.extend( 

1447 CompletionItem(name, help=param.help) 

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

1449 if name.startswith(incomplete) 

1450 ) 

1451 

1452 while ctx.parent is not None: 

1453 ctx = ctx.parent 

1454 

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

1456 results.extend( 

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

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

1459 if name not in ctx._protected_args 

1460 ) 

1461 

1462 return results 

1463 

1464 @t.overload 

1465 def main( 

1466 self, 

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

1468 prog_name: str | None = None, 

1469 complete_var: str | None = None, 

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

1471 **extra: t.Any, 

1472 ) -> t.NoReturn: ... 

1473 

1474 @t.overload 

1475 def main( 

1476 self, 

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

1478 prog_name: str | None = None, 

1479 complete_var: str | None = None, 

1480 standalone_mode: bool = ..., 

1481 **extra: t.Any, 

1482 ) -> t.Any: ... 

1483 

1484 def main( 

1485 self, 

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

1487 prog_name: str | None = None, 

1488 complete_var: str | None = None, 

1489 standalone_mode: bool = True, 

1490 windows_expand_args: bool = True, 

1491 **extra: t.Any, 

1492 ) -> t.Any: 

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

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

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

1496 needs to be caught. 

1497 

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

1499 a :class:`Command`. 

1500 

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

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

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

1504 the program name is constructed by taking the file 

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

1506 :param complete_var: the environment variable that controls the 

1507 bash completion support. The default is 

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

1509 uppercase. 

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

1511 in standalone mode. Click will then 

1512 handle exceptions and convert them into 

1513 error messages and the function will never 

1514 return but shut down the interpreter. If 

1515 this is set to `False` they will be 

1516 propagated to the caller and the return 

1517 value of this function is the return value 

1518 of :meth:`invoke`. 

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

1520 env vars in command line args on Windows. 

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

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

1523 

1524 .. versionchanged:: 8.0.1 

1525 Added the ``windows_expand_args`` parameter to allow 

1526 disabling command line arg expansion on Windows. 

1527 

1528 .. versionchanged:: 8.0 

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

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

1531 

1532 .. versionchanged:: 3.0 

1533 Added the ``standalone_mode`` parameter. 

1534 """ 

1535 if args is None: 

1536 args = sys.argv[1:] 

1537 

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

1539 args = _expand_args(args) 

1540 else: 

1541 args = list(args) 

1542 

1543 if prog_name is None: 

1544 prog_name = _detect_program_name() 

1545 

1546 # Process shell completion requests and exit early. 

1547 self._main_shell_completion(extra, prog_name, complete_var) 

1548 

1549 try: 

1550 try: 

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

1552 rv = self.invoke(ctx) 

1553 if not standalone_mode: 

1554 return rv 

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

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

1557 # has obvious effects 

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

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

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

1561 # by its truthiness/falsiness 

1562 ctx.exit() 

1563 except (EOFError, KeyboardInterrupt) as e: 

1564 echo(file=sys.stderr) 

1565 raise Abort() from e 

1566 except ClickException as e: 

1567 if not standalone_mode: 

1568 raise 

1569 e.show() 

1570 sys.exit(e.exit_code) 

1571 except OSError as e: 

1572 if e.errno == errno.EPIPE: 

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

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

1575 sys.exit(1) 

1576 else: 

1577 raise 

1578 except Exit as e: 

1579 if standalone_mode: 

1580 sys.exit(e.exit_code) 

1581 else: 

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

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

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

1585 # would return its result 

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

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

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

1589 # tell the difference between the two 

1590 return e.exit_code 

1591 except Abort: 

1592 if not standalone_mode: 

1593 raise 

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

1595 sys.exit(1) 

1596 

1597 def _main_shell_completion( 

1598 self, 

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

1600 prog_name: str, 

1601 complete_var: str | None = None, 

1602 ) -> None: 

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

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

1605 program is invoked. 

1606 

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

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

1609 the completion instruction. Defaults to 

1610 ``_{PROG_NAME}_COMPLETE``. 

1611 

1612 .. versionchanged:: 8.2.0 

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

1614 """ 

1615 if complete_var is None: 

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

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

1618 

1619 instruction = os.environ.get(complete_var) 

1620 

1621 if not instruction: 

1622 return 

1623 

1624 from .shell_completion import shell_complete 

1625 

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

1627 sys.exit(rv) 

1628 

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

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

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

1632 

1633 

1634class _FakeSubclassCheck(type): 

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

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

1637 

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

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

1640 

1641 

1642class _BaseCommand(Command, metaclass=_FakeSubclassCheck): 

1643 """ 

1644 .. deprecated:: 8.2 

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

1646 """ 

1647 

1648 

1649class Group(Command): 

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

1651 

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

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

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

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

1656 subcommand is not given. 

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

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

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

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

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

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

1663 matched, and so on. 

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

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

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

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

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

1669 ``chain`` is enabled. 

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

1671 

1672 .. versionchanged:: 8.0 

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

1674 

1675 .. versionchanged:: 8.2 

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

1677 """ 

1678 

1679 allow_extra_args = True 

1680 allow_interspersed_args = False 

1681 

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

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

1684 #: subcommands use a custom command class. 

1685 #: 

1686 #: .. versionadded:: 8.0 

1687 command_class: type[Command] | None = None 

1688 

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

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

1691 #: subgroups use a custom group class. 

1692 #: 

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

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

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

1696 #: custom groups. 

1697 #: 

1698 #: .. versionadded:: 8.0 

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

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

1701 

1702 commands: cabc.MutableMapping[str, Command] 

1703 invoke_without_command: bool 

1704 subcommand_metavar: str 

1705 chain: bool 

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

1707 

1708 def __init__( 

1709 self, 

1710 name: str | None = None, 

1711 commands: cabc.MutableMapping[str, Command] 

1712 | cabc.Sequence[Command] 

1713 | None = None, 

1714 invoke_without_command: bool = False, 

1715 no_args_is_help: bool | None = None, 

1716 subcommand_metavar: str | None = None, 

1717 chain: bool = False, 

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

1719 **kwargs: t.Any, 

1720 ) -> None: 

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

1722 

1723 if commands is None: 

1724 commands = {} 

1725 elif isinstance(commands, abc.Sequence): 

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

1727 

1728 #: The registered subcommands by their exported names. 

1729 self.commands = commands 

1730 

1731 if no_args_is_help is None: 

1732 no_args_is_help = not invoke_without_command 

1733 

1734 self.no_args_is_help = no_args_is_help 

1735 self.invoke_without_command = invoke_without_command 

1736 

1737 if subcommand_metavar is None: 

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

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

1740 if chain: 

1741 if invoke_without_command: 

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

1743 else: 

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

1745 elif invoke_without_command: 

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

1747 else: 

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

1749 

1750 self.subcommand_metavar = subcommand_metavar 

1751 self.chain = chain 

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

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

1754 self._result_callback = result_callback 

1755 

1756 if self.chain: 

1757 for param in self.params: 

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

1759 raise RuntimeError( 

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

1761 ) 

1762 

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

1764 info_dict = super().to_info_dict(ctx) 

1765 commands = {} 

1766 

1767 for name in self.list_commands(ctx): 

1768 command = self.get_command(ctx, name) 

1769 

1770 if command is None: 

1771 continue 

1772 

1773 sub_ctx = ctx._make_sub_context(command) 

1774 

1775 with sub_ctx.scope(cleanup=False): 

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

1777 

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

1779 return info_dict 

1780 

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

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

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

1784 """ 

1785 name = name or cmd.name 

1786 if name is None: 

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

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

1789 self.commands[name] = cmd 

1790 

1791 @t.overload 

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

1793 

1794 @t.overload 

1795 def command( 

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

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

1798 

1799 def command( 

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

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

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

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

1804 immediately registers the created command with this group by 

1805 calling :meth:`add_command`. 

1806 

1807 To customize the command class used, set the 

1808 :attr:`command_class` attribute. 

1809 

1810 .. versionchanged:: 8.1 

1811 This decorator can be applied without parentheses. 

1812 

1813 .. versionchanged:: 8.0 

1814 Added the :attr:`command_class` attribute. 

1815 """ 

1816 from .decorators import command 

1817 

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

1819 

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

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

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

1823 ) 

1824 (func,) = args 

1825 args = () 

1826 

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

1828 kwargs["cls"] = self.command_class 

1829 

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

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

1832 self.add_command(cmd) 

1833 return cmd 

1834 

1835 if func is not None: 

1836 return decorator(func) 

1837 

1838 return decorator 

1839 

1840 @t.overload 

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

1842 

1843 @t.overload 

1844 def group( 

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

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

1847 

1848 def group( 

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

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

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

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

1853 immediately registers the created group with this group by 

1854 calling :meth:`add_command`. 

1855 

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

1857 attribute. 

1858 

1859 .. versionchanged:: 8.1 

1860 This decorator can be applied without parentheses. 

1861 

1862 .. versionchanged:: 8.0 

1863 Added the :attr:`group_class` attribute. 

1864 """ 

1865 from .decorators import group 

1866 

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

1868 

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

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

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

1872 ) 

1873 (func,) = args 

1874 args = () 

1875 

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

1877 if self.group_class is type: 

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

1879 else: 

1880 kwargs["cls"] = self.group_class 

1881 

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

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

1884 self.add_command(cmd) 

1885 return cmd 

1886 

1887 if func is not None: 

1888 return decorator(func) 

1889 

1890 return decorator 

1891 

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

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

1894 result callback is already registered this will chain them but 

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

1896 callback is invoked with the return value of the subcommand 

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

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

1899 to the main callback. 

1900 

1901 Example:: 

1902 

1903 @click.group() 

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

1905 def cli(input): 

1906 return 42 

1907 

1908 @cli.result_callback() 

1909 def process_result(result, input): 

1910 return result + input 

1911 

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

1913 callback will be removed. 

1914 

1915 .. versionchanged:: 8.0 

1916 Renamed from ``resultcallback``. 

1917 

1918 .. versionadded:: 3.0 

1919 """ 

1920 

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

1922 old_callback = self._result_callback 

1923 

1924 if old_callback is None or replace: 

1925 self._result_callback = f 

1926 return f 

1927 

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

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

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

1931 

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

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

1934 

1935 return decorator 

1936 

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

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

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

1940 """ 

1941 return self.commands.get(cmd_name) 

1942 

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

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

1945 return sorted(self.commands) 

1946 

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

1948 rv = super().collect_usage_pieces(ctx) 

1949 rv.append(self.subcommand_metavar) 

1950 return rv 

1951 

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

1953 super().format_options(ctx, formatter) 

1954 self.format_commands(ctx, formatter) 

1955 

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

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

1958 after the options. 

1959 """ 

1960 commands = [] 

1961 for subcommand in self.list_commands(ctx): 

1962 cmd = self.get_command(ctx, subcommand) 

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

1964 if cmd is None: 

1965 continue 

1966 if cmd.hidden: 

1967 continue 

1968 

1969 commands.append((subcommand, cmd)) 

1970 

1971 # allow for 3 times the default spacing 

1972 if len(commands): 

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

1974 

1975 rows = [] 

1976 for subcommand, cmd in commands: 

1977 help = cmd.get_short_help_str(limit) 

1978 rows.append((subcommand, help)) 

1979 

1980 if rows: 

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

1982 formatter.write_dl(rows) 

1983 

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

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

1986 raise NoArgsIsHelpError(ctx) 

1987 

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

1989 

1990 if self.chain: 

1991 ctx._protected_args = rest 

1992 ctx.args = [] 

1993 elif rest: 

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

1995 

1996 return ctx.args 

1997 

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

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

2000 if self._result_callback is not None: 

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

2002 return value 

2003 

2004 if not ctx._protected_args: 

2005 if self.invoke_without_command: 

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

2007 # invoked with the group return value for regular 

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

2009 with ctx: 

2010 rv = super().invoke(ctx) 

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

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

2013 

2014 # Fetch args back out 

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

2016 ctx.args = [] 

2017 ctx._protected_args = [] 

2018 

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

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

2021 # name of the command to invoke. 

2022 if not self.chain: 

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

2024 # resources until the result processor has worked. 

2025 with ctx: 

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

2027 assert cmd is not None 

2028 ctx.invoked_subcommand = cmd_name 

2029 super().invoke(ctx) 

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

2031 with sub_ctx: 

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

2033 

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

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

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

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

2038 # but nothing else. 

2039 with ctx: 

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

2041 super().invoke(ctx) 

2042 

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

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

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

2046 contexts = [] 

2047 while args: 

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

2049 assert cmd is not None 

2050 sub_ctx = cmd.make_context( 

2051 cmd_name, 

2052 args, 

2053 parent=ctx, 

2054 allow_extra_args=True, 

2055 allow_interspersed_args=False, 

2056 ) 

2057 contexts.append(sub_ctx) 

2058 args, sub_ctx.args = sub_ctx.args, [] 

2059 

2060 rv = [] 

2061 for sub_ctx in contexts: 

2062 with sub_ctx: 

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

2064 return _process_result(rv) 

2065 

2066 def resolve_command( 

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

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

2069 cmd_name = make_str(args[0]) 

2070 

2071 # Get the command 

2072 cmd = self.get_command(ctx, cmd_name) 

2073 

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

2075 # function available, we try with that one. 

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

2077 cmd_name = ctx.token_normalize_func(cmd_name) 

2078 cmd = self.get_command(ctx, cmd_name) 

2079 

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

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

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

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

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

2085 # place. 

2086 if cmd is None and not ctx.resilient_parsing: 

2087 if _split_opt(cmd_name)[0]: 

2088 self.parse_args(ctx, args) 

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

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

2091 

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

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

2094 at the names of options, subcommands, and chained 

2095 multi-commands. 

2096 

2097 :param ctx: Invocation context for this command. 

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

2099 

2100 .. versionadded:: 8.0 

2101 """ 

2102 from click.shell_completion import CompletionItem 

2103 

2104 results = [ 

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

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

2107 ] 

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

2109 return results 

2110 

2111 

2112class _MultiCommand(Group, metaclass=_FakeSubclassCheck): 

2113 """ 

2114 .. deprecated:: 8.2 

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

2116 """ 

2117 

2118 

2119class CommandCollection(Group): 

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

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

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

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

2124 commands in many groups into this one group. 

2125 

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

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

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

2129 

2130 .. versionchanged:: 8.2 

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

2132 group, then each of its sources. 

2133 """ 

2134 

2135 sources: list[Group] 

2136 

2137 def __init__( 

2138 self, 

2139 name: str | None = None, 

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

2141 **kwargs: t.Any, 

2142 ) -> None: 

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

2144 #: The list of registered groups. 

2145 self.sources = sources or [] 

2146 

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

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

2149 self.sources.append(group) 

2150 

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

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

2153 

2154 if rv is not None: 

2155 return rv 

2156 

2157 for source in self.sources: 

2158 rv = source.get_command(ctx, cmd_name) 

2159 

2160 if rv is not None: 

2161 if self.chain: 

2162 _check_nested_chain(self, cmd_name, rv) 

2163 

2164 return rv 

2165 

2166 return None 

2167 

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

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

2170 

2171 for source in self.sources: 

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

2173 

2174 return sorted(rv) 

2175 

2176 

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

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

2179 error, or return an iterator over the value. 

2180 """ 

2181 if isinstance(value, str): 

2182 raise TypeError 

2183 

2184 return iter(value) 

2185 

2186 

2187class Parameter(ABC): 

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

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

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

2191 intentionally not finalized. 

2192 

2193 Some settings are supported by both options and arguments. 

2194 

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

2196 argument. This is a list of flags or argument 

2197 names. 

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

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

2200 automatically if supported. 

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

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

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

2204 without any arguments. 

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

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

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

2208 including prompts. 

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

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

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

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

2213 parameters are collected. 

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

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

2216 to the command callback and stored on the context, 

2217 otherwise it's skipped. 

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

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

2220 order of processing. 

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

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

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

2224 :param shell_complete: A function that returns custom shell 

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

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

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

2228 strings. 

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

2230 indicating that the argument is deprecated and highlights 

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

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

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

2234 

2235 .. versionchanged:: 8.2.0 

2236 Introduction of ``deprecated``. 

2237 

2238 .. versionchanged:: 8.2 

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

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

2241 

2242 .. versionchanged:: 8.2 

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

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

2245 

2246 .. versionchanged:: 8.0 

2247 ``process_value`` validates required parameters and bounded 

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

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

2250 ``full_process_value`` is removed. 

2251 

2252 .. versionchanged:: 8.0 

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

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

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

2256 new requirements. 

2257 

2258 .. versionchanged:: 8.0 

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

2260 tuples. 

2261 

2262 .. versionchanged:: 8.0 

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

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

2265 default to ``()``. 

2266 

2267 .. versionchanged:: 7.1 

2268 Empty environment variables are ignored rather than taking the 

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

2270 variables if they can't unset them. 

2271 

2272 .. versionchanged:: 2.0 

2273 Changed signature for parameter callback to also be passed the 

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

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

2276 """ 

2277 

2278 param_type_name = "parameter" 

2279 

2280 name: str 

2281 opts: list[str] 

2282 secondary_opts: list[str] 

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

2284 required: bool 

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

2286 nargs: int 

2287 multiple: bool 

2288 expose_value: bool 

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

2290 _default_explicit: bool 

2291 is_eager: bool 

2292 metavar: str | None 

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

2294 _custom_shell_complete: ( 

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

2296 ) 

2297 deprecated: bool | str 

2298 

2299 def __init__( 

2300 self, 

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

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

2303 required: bool = False, 

2304 # XXX The default historically embed two concepts: 

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

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

2307 # self.name, like flag options), 

2308 # - and the actual value of the default. 

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

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

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

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

2313 # Parameter.is_default and Parameter.default_value. 

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

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

2316 nargs: int | None = None, 

2317 multiple: bool = False, 

2318 metavar: str | None = None, 

2319 expose_value: bool = True, 

2320 is_eager: bool = False, 

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

2322 shell_complete: t.Callable[ 

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

2324 ] 

2325 | None = None, 

2326 deprecated: bool | str = False, 

2327 ) -> None: 

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

2329 param_decls or (), expose_value 

2330 ) 

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

2332 

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

2334 # information available. 

2335 if nargs is None: 

2336 if self.type.is_composite: 

2337 nargs = self.type.arity 

2338 else: 

2339 nargs = 1 

2340 

2341 self.required = required 

2342 self.callback = callback 

2343 self.nargs = nargs 

2344 self.multiple = multiple 

2345 self.expose_value = expose_value 

2346 self.default = default 

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

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

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

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

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

2352 self._default_explicit = default is not UNSET 

2353 self.is_eager = is_eager 

2354 self.metavar = metavar 

2355 self.envvar = envvar 

2356 self._custom_shell_complete = shell_complete 

2357 self.deprecated = deprecated 

2358 

2359 if __debug__: 

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

2361 raise ValueError( 

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

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

2364 ) 

2365 

2366 if required and deprecated: 

2367 raise ValueError( 

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

2369 "is deprecated and still required. A deprecated " 

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

2371 ) 

2372 

2373 @staticmethod 

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

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

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

2377 implementation detail. 

2378 """ 

2379 return None if value is UNSET else value 

2380 

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

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

2383 user-facing documentation. 

2384 

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

2386 CLI structure. 

2387 

2388 .. versionchanged:: 8.3.0 

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

2390 

2391 .. versionadded:: 8.0 

2392 """ 

2393 return { 

2394 "name": self.name, 

2395 "param_type_name": self.param_type_name, 

2396 "opts": self.opts, 

2397 "secondary_opts": self.secondary_opts, 

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

2399 "required": self.required, 

2400 "nargs": self.nargs, 

2401 "multiple": self.multiple, 

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

2403 "envvar": self.envvar, 

2404 } 

2405 

2406 def __repr__(self) -> str: 

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

2408 

2409 @abstractmethod 

2410 def _parse_decls( 

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

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

2413 

2414 @property 

2415 def human_readable_name(self) -> str: 

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

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

2418 """ 

2419 return self.name 

2420 

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

2422 if self.metavar is not None: 

2423 return self.metavar 

2424 

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

2426 

2427 if metavar is None: 

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

2429 

2430 if self.nargs != 1: 

2431 metavar += "..." 

2432 

2433 return metavar 

2434 

2435 @t.overload 

2436 def get_default( 

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

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

2439 

2440 @t.overload 

2441 def get_default( 

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

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

2444 

2445 def get_default( 

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

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

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

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

2450 

2451 :param ctx: Current context. 

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

2453 return the callable instead. 

2454 

2455 .. versionchanged:: 8.0.2 

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

2457 

2458 .. versionchanged:: 8.0.1 

2459 Type casting can fail in resilient parsing mode. Invalid 

2460 defaults will not prevent showing help text. 

2461 

2462 .. versionchanged:: 8.0 

2463 Looks at ``ctx.default_map`` first. 

2464 

2465 .. versionchanged:: 8.0 

2466 Added the ``call`` parameter. 

2467 """ 

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

2469 

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

2471 value = self.default 

2472 

2473 if call and callable(value): 

2474 value = value() 

2475 

2476 return value 

2477 

2478 @abstractmethod 

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

2480 

2481 def consume_value( 

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

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

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

2485 

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

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

2488 default value. In that order of precedence. 

2489 

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

2491 

2492 :meta private: 

2493 """ 

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

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

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

2497 # parser, otherwise it left unset by default. 

2498 source = ( 

2499 ParameterSource.COMMANDLINE 

2500 if value is not UNSET 

2501 else ParameterSource.DEFAULT 

2502 ) 

2503 

2504 if value is UNSET: 

2505 envvar_value = self.value_from_envvar(ctx) 

2506 if envvar_value is not None: 

2507 value = envvar_value 

2508 source = ParameterSource.ENVIRONMENT 

2509 

2510 if value is UNSET: 

2511 default_map_value = ctx.lookup_default(self.name) 

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

2513 value = default_map_value 

2514 source = ParameterSource.DEFAULT_MAP 

2515 

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

2517 # parameters, matching value_from_envvar behavior. 

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

2519 value = self.type.split_envvar_value(value) 

2520 

2521 if value is UNSET: 

2522 default_value = self.get_default(ctx) 

2523 if default_value is not UNSET: 

2524 value = default_value 

2525 source = ParameterSource.DEFAULT 

2526 

2527 return value, source 

2528 

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

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

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

2532 """ 

2533 if value is None: 

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

2535 return () 

2536 else: 

2537 return value 

2538 

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

2540 try: 

2541 return _check_iter(value) 

2542 except TypeError: 

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

2544 # the parser should construct an iterable when parsing 

2545 # the command line. 

2546 raise BadParameter( 

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

2548 ) from None 

2549 

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

2551 

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

2553 

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

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

2556 

2557 elif self.nargs == -1: 

2558 

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

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

2561 

2562 else: # nargs > 1 

2563 

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

2565 value = tuple(check_iter(value)) 

2566 

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

2568 raise BadParameter( 

2569 ngettext( 

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

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

2572 len(value), 

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

2574 ctx=ctx, 

2575 param=self, 

2576 ) 

2577 

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

2579 

2580 if self.multiple: 

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

2582 

2583 return convert(value) 

2584 

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

2586 """A value is considered missing if: 

2587 

2588 - it is :attr:`UNSET`, 

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

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

2591 set). 

2592 

2593 :meta private: 

2594 """ 

2595 if value is UNSET: 

2596 return True 

2597 

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

2599 return True 

2600 

2601 return False 

2602 

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

2604 """Process the value of this parameter: 

2605 

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

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

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

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

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

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

2612 the :attr:`UNSET` sentinel. 

2613 

2614 :meta private: 

2615 """ 

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

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

2618 # 

2619 # Refs: 

2620 # https://github.com/pallets/click/issues/3069 

2621 if value is UNSET: 

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

2623 value = () 

2624 else: 

2625 value = self.type_cast_value(ctx, value) 

2626 

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

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

2629 

2630 if self.callback is not None: 

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

2632 # to None. 

2633 if value is UNSET: 

2634 value = None 

2635 

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

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

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

2639 if not unset_keys: 

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

2641 

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

2643 # to hide UNSET values as None. 

2644 # 

2645 # Refs: 

2646 # https://github.com/pallets/click/issues/3136 

2647 # https://github.com/pallets/click/pull/3137 

2648 else: 

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

2650 # context is temporarily modified. 

2651 with ctx: 

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

2653 ctx.params.update(unset_keys) 

2654 # Feed these fake context parameters to the callback. 

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

2656 # Restore the UNSET values in the context parameters. 

2657 ctx.params.update( 

2658 { 

2659 k: UNSET 

2660 for k in unset_keys 

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

2662 # the callback modified other parameters. 

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

2664 } 

2665 ) 

2666 

2667 return value 

2668 

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

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

2671 parameter. 

2672 

2673 Environment variables values are `always returned as strings 

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

2675 

2676 This method returns ``None`` if: 

2677 

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

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

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

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

2682 

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

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

2685 

2686 .. caution:: 

2687 

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

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

2690 the :class:`Parameter`'s :attr:`type`. 

2691 

2692 :meta private: 

2693 """ 

2694 if not self.envvar: 

2695 return None 

2696 

2697 if isinstance(self.envvar, str): 

2698 rv = os.environ.get(self.envvar) 

2699 

2700 if rv: 

2701 return rv 

2702 else: 

2703 for envvar in self.envvar: 

2704 rv = os.environ.get(envvar) 

2705 

2706 # Return the first non-empty value of the list of environment variables. 

2707 if rv: 

2708 return rv 

2709 # Else, absence of value is interpreted as an environment variable that 

2710 # is not set, so proceed to the next one. 

2711 

2712 return None 

2713 

2714 def value_from_envvar(self, ctx: Context) -> str | cabc.Sequence[str] | None: 

2715 """Process the raw environment variable string for this parameter. 

2716 

2717 Returns the string as-is or splits it into a sequence of strings if the 

2718 parameter is expecting multiple values (i.e. its :attr:`nargs` property is set 

2719 to a value other than ``1``). 

2720 

2721 :meta private: 

2722 """ 

2723 rv = self.resolve_envvar_value(ctx) 

2724 

2725 if rv is not None and self.nargs != 1: 

2726 return self.type.split_envvar_value(rv) 

2727 

2728 return rv 

2729 

2730 def handle_parse_result( 

2731 self, ctx: Context, opts: cabc.Mapping[str, t.Any], args: list[str] 

2732 ) -> tuple[t.Any, list[str]]: 

2733 """Process the value produced by the parser from user input. 

2734 

2735 Always process the value through the Parameter's :attr:`type`, wherever it 

2736 comes from. 

2737 

2738 If the parameter is deprecated, this method warn the user about it. But only if 

2739 the value has been explicitly set by the user (and as such, is not coming from 

2740 a default). 

2741 

2742 :meta private: 

2743 """ 

2744 # Capture the slot's existing state before we mutate 

2745 # ``_parameter_source`` so the write decision below can compare our 

2746 # incoming source against the source of the option that already wrote 

2747 # the slot (if any). 

2748 existing_value = ctx.params.get(self.name, UNSET) 

2749 existing_source = ctx.get_parameter_source(self.name) 

2750 existing_default_explicit = ctx._param_default_explicit.get(self.name, False) 

2751 

2752 with augment_usage_errors(ctx, param=self): 

2753 value, source = self.consume_value(ctx, opts) 

2754 

2755 # Record the source before processing so eager callbacks and type 

2756 # conversion can inspect it. Restored after arbitration if this 

2757 # option loses a feature-switch group. 

2758 ctx.set_parameter_source(self.name, source) 

2759 

2760 # Display a deprecation warning if necessary. 

2761 if ( 

2762 self.deprecated 

2763 and value is not UNSET 

2764 and source < ParameterSource.DEFAULT_MAP 

2765 ): 

2766 message = _( 

2767 "DeprecationWarning: The {param_type} {name!r} is deprecated." 

2768 "{extra_message}" 

2769 ).format( 

2770 param_type=self.param_type_name, 

2771 name=self.human_readable_name, 

2772 extra_message=_format_deprecated_suffix(self.deprecated), 

2773 ) 

2774 echo(style(message, fg="red"), err=True) 

2775 

2776 # Process the value through the parameter's type. 

2777 try: 

2778 value = self.process_value(ctx, value) 

2779 except Exception: 

2780 if not ctx.resilient_parsing: 

2781 raise 

2782 # In resilient parsing mode, we do not want to fail the command if the 

2783 # value is incompatible with the parameter type, so we reset the value 

2784 # to UNSET, which will be interpreted as a missing value. 

2785 value = UNSET 

2786 

2787 # Arbitrate the slot when several parameters target the same variable 

2788 # name (feature-switch groups). See: https://github.com/pallets/click/issues/3403 

2789 slot_empty = existing_value is UNSET 

2790 more_explicit = existing_source is not None and source < existing_source 

2791 same_source = existing_source is not None and source == existing_source 

2792 auto_would_downgrade_explicit = ( 

2793 same_source 

2794 and source == ParameterSource.DEFAULT 

2795 and existing_default_explicit 

2796 and not self._default_explicit 

2797 ) 

2798 is_winner = ( 

2799 slot_empty 

2800 or more_explicit 

2801 or (same_source and not auto_would_downgrade_explicit) 

2802 ) 

2803 

2804 if is_winner: 

2805 if self.expose_value: 

2806 ctx.params[self.name] = value 

2807 ctx._param_default_explicit[self.name] = self._default_explicit 

2808 elif existing_source is not None: 

2809 # Lost arbitration; restore the winning option's source. 

2810 ctx.set_parameter_source(self.name, existing_source) 

2811 # else: ctx.params[self.name] was populated by code that bypassed 

2812 # handle_parse_result (from another option's callback for example). Keep 

2813 # the provisional source recorded before process_value so downstream 

2814 # lookups don't return ``None``. 

2815 

2816 return value, args 

2817 

2818 def get_help_record(self, ctx: Context) -> tuple[str, str] | None: 

2819 return None 

2820 

2821 def get_usage_pieces(self, ctx: Context) -> list[str]: 

2822 return [] 

2823 

2824 def get_error_hint(self, ctx: Context | None) -> str: 

2825 """Get a stringified version of the param for use in error messages to 

2826 indicate which param caused the error. 

2827 

2828 .. versionchanged:: 8.4.0 

2829 ``ctx`` can be ``None``. 

2830 """ 

2831 hint_list = self.opts or [self.human_readable_name] 

2832 return " / ".join(f"'{x}'" for x in hint_list) 

2833 

2834 def shell_complete(self, ctx: Context, incomplete: str) -> list[CompletionItem]: 

2835 """Return a list of completions for the incomplete value. If a 

2836 ``shell_complete`` function was given during init, it is used. 

2837 Otherwise, the :attr:`type` 

2838 :meth:`~click.types.ParamType[t.Any].shell_complete` function is used. 

2839 

2840 :param ctx: Invocation context for this command. 

2841 :param incomplete: Value being completed. May be empty. 

2842 

2843 .. versionadded:: 8.0 

2844 """ 

2845 if self._custom_shell_complete is not None: 

2846 results = self._custom_shell_complete(ctx, self, incomplete) 

2847 

2848 if results and isinstance(results[0], str): 

2849 from click.shell_completion import CompletionItem 

2850 

2851 results = [CompletionItem(c) for c in results] 

2852 

2853 return t.cast("list[CompletionItem]", results) 

2854 

2855 return self.type.shell_complete(ctx, self, incomplete) 

2856 

2857 

2858class Option(Parameter): 

2859 """Options are usually optional values on the command line and 

2860 have some extra features that arguments don't have. 

2861 

2862 All other parameters are passed onwards to the parameter constructor. 

2863 

2864 :param show_default: Show the default value for this option in its 

2865 help text. Values are not shown by default, unless 

2866 :attr:`Context.show_default` is ``True``. If this value is a 

2867 string, it shows that string in parentheses instead of the 

2868 actual value. This is particularly useful for dynamic options. 

2869 For single option boolean flags, the default remains hidden if 

2870 its value is ``False``. 

2871 :param show_envvar: Controls if an environment variable should be 

2872 shown on the help page and error messages. 

2873 Normally, environment variables are not shown. 

2874 :param prompt: If set to ``True`` or a non empty string then the 

2875 user will be prompted for input. If set to ``True`` the prompt 

2876 will be the option name capitalized. A deprecated option cannot be 

2877 prompted. 

2878 :param confirmation_prompt: Prompt a second time to confirm the 

2879 value if it was prompted for. Can be set to a string instead of 

2880 ``True`` to customize the message. 

2881 :param prompt_required: If set to ``False``, the user will be 

2882 prompted for input only when the option was specified as a flag 

2883 without a value. 

2884 :param hide_input: If this is ``True`` then the input on the prompt 

2885 will be hidden from the user. This is useful for password input. 

2886 :param is_flag: forces this option to act as a flag. The default is 

2887 auto detection. 

2888 :param flag_value: which value should be used for this flag if it's 

2889 enabled. This is set to a boolean automatically if 

2890 the option string contains a slash to mark two options. 

2891 :param multiple: if this is set to `True` then the argument is accepted 

2892 multiple times and recorded. This is similar to ``nargs`` 

2893 in how it works but supports arbitrary number of 

2894 arguments. 

2895 :param count: this flag makes an option increment an integer. 

2896 :param allow_from_autoenv: if this is enabled then the value of this 

2897 parameter will be pulled from an environment 

2898 variable in case a prefix is defined on the 

2899 context. 

2900 :param help: the help string. 

2901 :param hidden: hide this option from help outputs. 

2902 :param attrs: Other command arguments described in :class:`Parameter`. 

2903 

2904 .. versionchanged:: 8.4.0 

2905 Non-basic ``flag_value`` types (not ``str``, ``int``, ``float``, or 

2906 ``bool``) are passed through unchanged instead of being stringified. 

2907 Previously, ``type=click.UNPROCESSED`` was required to preserve them. 

2908 

2909 .. versionchanged:: 8.2 

2910 ``envvar`` used with ``flag_value`` will always use the ``flag_value``, 

2911 previously it would use the value of the environment variable. 

2912 

2913 .. versionchanged:: 8.1 

2914 Help text indentation is cleaned here instead of only in the 

2915 ``@option`` decorator. 

2916 

2917 .. versionchanged:: 8.1 

2918 The ``show_default`` parameter overrides 

2919 ``Context.show_default``. 

2920 

2921 .. versionchanged:: 8.1 

2922 The default of a single option boolean flag is not shown if the 

2923 default value is ``False``. 

2924 

2925 .. versionchanged:: 8.0.1 

2926 ``type`` is detected from ``flag_value`` if given, for basic Python 

2927 types (``str``, ``int``, ``float``, ``bool``). 

2928 """ 

2929 

2930 param_type_name = "option" 

2931 

2932 prompt: str | None 

2933 confirmation_prompt: bool | str 

2934 prompt_required: bool 

2935 hide_input: bool 

2936 hidden: bool 

2937 

2938 _flag_needs_value: bool 

2939 is_flag: bool 

2940 flag_value: t.Any 

2941 type: types.ParamType[t.Any] 

2942 default: t.Any | t.Callable[[], t.Any] | None 

2943 

2944 count: bool 

2945 allow_from_autoenv: bool 

2946 help: str | None 

2947 show_default: bool | str | None 

2948 show_choices: bool 

2949 show_envvar: bool 

2950 

2951 def __init__( 

2952 self, 

2953 param_decls: cabc.Sequence[str] | None = None, 

2954 show_default: bool | str | None = None, 

2955 prompt: bool | str = False, 

2956 confirmation_prompt: bool | str = False, 

2957 prompt_required: bool = True, 

2958 hide_input: bool = False, 

2959 is_flag: bool | None = None, 

2960 flag_value: t.Any = UNSET, 

2961 multiple: bool = False, 

2962 count: bool = False, 

2963 allow_from_autoenv: bool = True, 

2964 type: types.ParamType[t.Any] | t.Any | None = None, 

2965 help: str | None = None, 

2966 hidden: bool = False, 

2967 show_choices: bool = True, 

2968 show_envvar: bool = False, 

2969 deprecated: bool | str = False, 

2970 **attrs: t.Any, 

2971 ) -> None: 

2972 if help: 

2973 help = inspect.cleandoc(help) 

2974 

2975 super().__init__( 

2976 param_decls, type=type, multiple=multiple, deprecated=deprecated, **attrs 

2977 ) 

2978 

2979 # Phase 1: prompt-related attributes. ``_infer_flag_kind`` reads ``self.prompt`` 

2980 # and ``self.prompt_required`` so this must run first. 

2981 if prompt is True: 

2982 if not self.name: 

2983 raise TypeError("'name' is required with 'prompt=True'.") 

2984 

2985 prompt_text = self.name.replace("_", " ").capitalize() 

2986 elif prompt is False: 

2987 prompt_text = None 

2988 else: 

2989 prompt_text = prompt 

2990 

2991 if deprecated: 

2992 label = _format_deprecated_label(deprecated) 

2993 help = f"{help} {label}" if help else label 

2994 

2995 self.prompt = prompt_text 

2996 self.confirmation_prompt = confirmation_prompt 

2997 self.prompt_required = prompt_required 

2998 self.hide_input = hide_input 

2999 self.hidden = hidden 

3000 

3001 # Phase 2: flag-kind inference. 

3002 self.is_flag, self._flag_needs_value = self._infer_flag_kind( 

3003 is_flag, flag_value 

3004 ) 

3005 

3006 # Phase 3: type inference. Override the type set by :meth:`Parameter.__init__` 

3007 # when this option is a flag or a count. 

3008 self.type = self._pick_type(type, flag_value, count, self.is_flag) 

3009 

3010 # Phase 4: store the raw ``flag_value`` and ``count`` settings. 

3011 # ``self.flag_value`` and ``self.default`` deliberately keep the :data:`UNSET` 

3012 # sentinel when the user didn't pass them. Auto-derived values are resolved 

3013 # lazily in :meth:`_resolve_lazy_default` and :attr:`flag_activation_value`. 

3014 # Keeping the raw values means ``is UNSET`` reliably answers "did the user pass 

3015 # this?": #3403 needs it for arbitration, and any future feature needing the 

3016 # same distinction can reuse it without reintroducing parallel "was it 

3017 # explicit?" tracking. 

3018 self.flag_value = flag_value 

3019 self.count = count 

3020 if count and self.default is UNSET: 

3021 self.default = 0 

3022 

3023 self.allow_from_autoenv = allow_from_autoenv 

3024 self.help = help 

3025 self.show_default = show_default 

3026 self.show_choices = show_choices 

3027 self.show_envvar = show_envvar 

3028 

3029 # Phase 5: validate. Raises on illegal kwarg combinations. 

3030 self._validate(prompt, deprecated) 

3031 

3032 @property 

3033 def is_bool_flag(self) -> bool: 

3034 """``True`` when this option is a flag with a boolean type. 

3035 

3036 Derived from :attr:`is_flag` and :attr:`type`; computed on access so it cannot 

3037 drift if a subclass replaces :attr:`type` after construction. 

3038 """ 

3039 return self.is_flag and isinstance(self.type, types.BoolParamType) 

3040 

3041 @property 

3042 def flag_activation_value(self) -> t.Any: 

3043 """Value the function receives when this flag is activated on the command line. 

3044 

3045 Resolves a missing :attr:`flag_value` to ``True`` for actual flag options and 

3046 ``None`` otherwise. Used by the parser bridge (:meth:`add_to_parser`) and the 

3047 runtime (:meth:`consume_value`) so :attr:`flag_value` can keep the :data:`UNSET` 

3048 sentinel for "did the user pass one?" introspection. 

3049 """ 

3050 if self.flag_value is UNSET: 

3051 return True if self.is_flag else None 

3052 return self.flag_value 

3053 

3054 def _infer_flag_kind( 

3055 self, is_flag: bool | None, flag_value: t.Any 

3056 ) -> tuple[bool, bool]: 

3057 """Resolve ``is_flag`` and the parser hint ``_flag_needs_value``. 

3058 

3059 Returns ``(is_flag, flag_needs_value)``, where ``_flag_needs_value`` tells the 

3060 parser this option is a flag that cannot be used standalone and needs a value. 

3061 The parser uses it to decide whether to treat the next CLI token as the flag's 

3062 value or as a new option. If ``prompt`` is enabled with 

3063 ``prompt_required=False``, it opens the door for an interactive value, hence the 

3064 initial condition. Ref: https://github.com/pallets/click/issues/3084 

3065 """ 

3066 needs_value = self.prompt is not None and not self.prompt_required 

3067 

3068 if is_flag is None: 

3069 # Implicitly a flag because flag_value was set. 

3070 if flag_value is not UNSET: 

3071 return True, needs_value 

3072 # Not a flag, but when used as a flag it shows a prompt. 

3073 if needs_value: 

3074 return False, needs_value 

3075 # Implicitly a flag because secondary options names were given. 

3076 if self.secondary_opts: 

3077 return True, needs_value 

3078 return False, needs_value 

3079 

3080 if is_flag is False and not needs_value: 

3081 # Explicit ``is_flag=False`` with a flag-like value/default still makes the 

3082 # option flag-shaped to the parser. 

3083 needs_value = flag_value is not UNSET or self.default is UNSET 

3084 

3085 return bool(is_flag), needs_value 

3086 

3087 def _pick_type( 

3088 self, 

3089 type_arg: t.Any, 

3090 flag_value: t.Any, 

3091 count: bool, 

3092 is_flag: bool, 

3093 ) -> types.ParamType[t.Any]: 

3094 """Pick the final :class:`ParamType` for this option. 

3095 

3096 :meth:`Parameter.__init__` already stored ``self.type`` from the explicit 

3097 ``type`` argument or from ``default``. This method either returns that as-is, or 

3098 overrides it for flag and count options (which are inferred from ``flag_value`` 

3099 rather than ``default``). 

3100 """ 

3101 if type_arg is not None: 

3102 return self.type 

3103 

3104 if count: 

3105 return types.IntRange(min=0) 

3106 

3107 if not is_flag: 

3108 return self.type 

3109 

3110 # A flag without a flag_value is a boolean flag. 

3111 if flag_value is UNSET or isinstance(flag_value, bool): 

3112 return types.BoolParamType() 

3113 

3114 guessed: types.ParamType[t.Any] = types.convert_type(None, flag_value) 

3115 if ( 

3116 isinstance(guessed, types.StringParamType) 

3117 and not isinstance(flag_value, str) 

3118 and flag_value is not None 

3119 ): 

3120 # The flag_value type couldn't be auto-detected (not str, int, float, or 

3121 # bool). Since flag_value is a programmer-provided Python object, not CLI 

3122 # input, pass it through unchanged instead of stringifying it. 

3123 return types.UNPROCESSED 

3124 return guessed 

3125 

3126 def _resolve_lazy_default(self, value: t.Any) -> t.Any: 

3127 """Apply lazy auto-derivations to a default-style value. 

3128 

3129 Shared between :meth:`get_default` (the runtime path) and :meth:`to_info_dict` 

3130 (the introspection path) so the two views cannot drift apart. Callables are 

3131 *not* invoked here: that is :meth:`get_default`'s responsibility. Rules: 

3132 

3133 * ``UNSET`` resolves to ``False`` for a non-required boolean flag, and to ``()`` 

3134 for a non-required, non-prompted multi flag. 

3135 * ``True`` resolves to :attr:`flag_value` for a non-boolean flag (the "activate 

3136 this flag by default" shorthand). Boolean flags keep ``True`` as a literal. 

3137 """ 

3138 if value is UNSET and self.is_flag: 

3139 if self.multiple and not self.required and not self.prompt: 

3140 return () 

3141 if self.is_bool_flag and not self.required: 

3142 return False 

3143 if value is True and self.is_flag and not self.is_bool_flag: 

3144 # Use ``flag_activation_value`` so an unset ``flag_value`` resolves to 

3145 # ``True`` (the bool-flag activation value) rather than leaking the 

3146 # :data:`UNSET` sentinel. 

3147 return self.flag_activation_value 

3148 return value 

3149 

3150 def _validate(self, prompt: bool | str, deprecated: bool | str) -> None: 

3151 """Raise :class:`TypeError` / :class:`ValueError` on illegal kwarg combinations. 

3152 

3153 Called once, after every other attribute has been assigned, so each check can 

3154 read the final state. 

3155 """ 

3156 if not __debug__: 

3157 return 

3158 if deprecated and prompt: 

3159 raise ValueError("`deprecated` options cannot use `prompt`.") 

3160 if self.nargs == -1: 

3161 raise TypeError("nargs=-1 is not supported for options.") 

3162 if not self.is_bool_flag and self.secondary_opts: 

3163 raise TypeError("Secondary flag is not valid for non-boolean flag.") 

3164 if self.is_bool_flag and self.hide_input and self.prompt is not None: 

3165 raise TypeError("'prompt' with 'hide_input' is not valid for boolean flag.") 

3166 if self.count: 

3167 if self.multiple: 

3168 raise TypeError("'count' is not valid with 'multiple'.") 

3169 if self.is_flag: 

3170 raise TypeError("'count' is not valid with 'is_flag'.") 

3171 

3172 def to_info_dict(self) -> dict[str, t.Any]: 

3173 """ 

3174 .. versionchanged:: 8.5.0 

3175 ``default`` and ``flag_value`` reflect the auto-derived values (``False`` 

3176 for unset boolean-flag defaults, ``True`` for unset boolean-flag activation 

3177 values, etc.) when no explicit value was passed, matching what the function 

3178 would receive at call time. 

3179 

3180 .. versionchanged:: 8.3.0 

3181 Returns ``None`` for the :attr:`flag_value` if it was not set. 

3182 """ 

3183 info_dict = super().to_info_dict() 

3184 info_dict.update( 

3185 default=self._hide_unset(self._resolve_lazy_default(self.default)), 

3186 help=self.help, 

3187 prompt=self.prompt, 

3188 is_flag=self.is_flag, 

3189 flag_value=self.flag_activation_value, 

3190 count=self.count, 

3191 hidden=self.hidden, 

3192 ) 

3193 return info_dict 

3194 

3195 def get_default( 

3196 self, ctx: Context, call: bool = True 

3197 ) -> t.Any | t.Callable[[], t.Any] | None: 

3198 """Return the default value for this option. 

3199 

3200 Several auto-derived defaults are resolved lazily here rather than eagerly in 

3201 :meth:`__init__`. This keeps :attr:`default` raw at construction time, so 

3202 ``self.default is UNSET`` reliably answers "did the user pass a default?" for 

3203 feature-switch-group arbitration and for anything else that needs to distinguish 

3204 "absent" from a chosen value. The resolution rules live in 

3205 :meth:`_resolve_lazy_default`. 

3206 

3207 .. versionchanged:: 8.5.0 

3208 ``UNSET`` defaults for boolean and multi flags are now resolved here instead 

3209 of being coerced in :meth:`__init__`. Reading :attr:`default` directly 

3210 returns the user-supplied value (or ``UNSET`` if none was passed) rather 

3211 than the auto-derived one. 

3212 

3213 .. versionchanged:: 8.3.3 

3214 ``default=True`` is no longer substituted with ``flag_value`` for boolean 

3215 flags, fixing negative boolean flags like 

3216 ``flag_value=False, default=True``. 

3217 """ 

3218 raw = super().get_default(ctx, call=False) 

3219 value = self._resolve_lazy_default(raw) 

3220 # Only invoke the value as a callable when the lazy resolver passed it through 

3221 # unchanged. If the resolver substituted ``True`` -> :attr:`flag_value`, the 

3222 # result is the programmer-supplied ``flag_value`` (often a class or enum), 

3223 # which must NOT be instantiated here. See 

3224 # https://github.com/pallets/click/issues/3121. 

3225 if value is raw and call and callable(value): 

3226 value = value() 

3227 return value 

3228 

3229 def get_error_hint(self, ctx: Context | None) -> str: 

3230 result = super().get_error_hint(ctx) 

3231 if self.show_envvar and self.envvar is not None: 

3232 result += f" (env var: '{self.envvar}')" 

3233 return result 

3234 

3235 def _parse_decls( 

3236 self, decls: cabc.Sequence[str], expose_value: bool 

3237 ) -> tuple[str, list[str], list[str]]: 

3238 opts = [] 

3239 secondary_opts = [] 

3240 name = None 

3241 possible_names = [] 

3242 

3243 for decl in decls: 

3244 if decl.isidentifier(): 

3245 if name is not None: 

3246 raise TypeError(_("Name '{name}' defined twice").format(name=name)) 

3247 name = decl 

3248 else: 

3249 split_char = ";" if decl[:1] == "/" else "/" 

3250 if split_char in decl: 

3251 first, second = decl.split(split_char, 1) 

3252 first = first.rstrip() 

3253 if first: 

3254 possible_names.append(_split_opt(first)) 

3255 opts.append(first) 

3256 second = second.lstrip() 

3257 if second: 

3258 secondary_opts.append(second.lstrip()) 

3259 if first == second: 

3260 raise ValueError( 

3261 _( 

3262 "Boolean option {decl!r} cannot use the" 

3263 " same flag for true/false." 

3264 ).format(decl=decl) 

3265 ) 

3266 else: 

3267 possible_names.append(_split_opt(decl)) 

3268 opts.append(decl) 

3269 

3270 if name is None and possible_names: 

3271 possible_names.sort(key=lambda x: -len(x[0])) # group long options first 

3272 name = possible_names[0][1].replace("-", "_").lower() 

3273 if not name.isidentifier(): 

3274 name = None 

3275 

3276 if name is None: 

3277 if not expose_value: 

3278 return "", opts, secondary_opts 

3279 raise TypeError( 

3280 _( 

3281 "Could not determine name for option with declarations {decls!r}" 

3282 ).format(decls=decls) 

3283 ) 

3284 

3285 if not opts and not secondary_opts: 

3286 raise TypeError( 

3287 _( 

3288 "No options defined but a name was passed ({name})." 

3289 " Did you mean to declare an argument instead? Did" 

3290 " you mean to pass '--{name}'?" 

3291 ).format(name=name) 

3292 ) 

3293 

3294 return name, opts, secondary_opts 

3295 

3296 def add_to_parser(self, parser: _OptionParser, ctx: Context) -> None: 

3297 if self.multiple: 

3298 action = "append" 

3299 elif self.count: 

3300 action = "count" 

3301 else: 

3302 action = "store" 

3303 

3304 if self.is_flag: 

3305 action = f"{action}_const" 

3306 

3307 if self.is_bool_flag and self.secondary_opts: 

3308 parser.add_option( 

3309 obj=self, opts=self.opts, dest=self.name, action=action, const=True 

3310 ) 

3311 parser.add_option( 

3312 obj=self, 

3313 opts=self.secondary_opts, 

3314 dest=self.name, 

3315 action=action, 

3316 const=False, 

3317 ) 

3318 else: 

3319 parser.add_option( 

3320 obj=self, 

3321 opts=self.opts, 

3322 dest=self.name, 

3323 action=action, 

3324 # ``flag_activation_value`` resolves UNSET to the right parser-store 

3325 # constant (``True`` for bool flags) so the raw :attr:`flag_value` 

3326 # can keep the sentinel. 

3327 const=self.flag_activation_value, 

3328 ) 

3329 else: 

3330 parser.add_option( 

3331 obj=self, 

3332 opts=self.opts, 

3333 dest=self.name, 

3334 action=action, 

3335 nargs=self.nargs, 

3336 ) 

3337 

3338 def get_help_record(self, ctx: Context) -> tuple[str, str] | None: 

3339 if self.hidden: 

3340 return None 

3341 

3342 any_prefix_is_slash = False 

3343 

3344 def _write_opts(opts: cabc.Sequence[str]) -> str: 

3345 nonlocal any_prefix_is_slash 

3346 

3347 rv, any_slashes = join_options(opts) 

3348 

3349 if any_slashes: 

3350 any_prefix_is_slash = True 

3351 

3352 if not self.is_flag and not self.count: 

3353 rv += f" {self.make_metavar(ctx=ctx)}" 

3354 

3355 return rv 

3356 

3357 rv = [_write_opts(self.opts)] 

3358 

3359 if self.secondary_opts: 

3360 rv.append(_write_opts(self.secondary_opts)) 

3361 

3362 help = self.help or "" 

3363 

3364 extra = self.get_help_extra(ctx) 

3365 extra_items = [] 

3366 if "envvars" in extra: 

3367 extra_items.append( 

3368 _("env var: {var}").format(var=", ".join(extra["envvars"])) 

3369 ) 

3370 if "default" in extra: 

3371 extra_items.append(_("default: {default}").format(default=extra["default"])) 

3372 if "range" in extra: 

3373 extra_items.append(extra["range"]) 

3374 if "required" in extra: 

3375 extra_items.append(_(extra["required"])) 

3376 

3377 if extra_items: 

3378 extra_str = "; ".join(extra_items) 

3379 help = f"{help} [{extra_str}]" if help else f"[{extra_str}]" 

3380 

3381 return ("; " if any_prefix_is_slash else " / ").join(rv), help 

3382 

3383 def get_help_extra(self, ctx: Context) -> types.OptionHelpExtra: 

3384 extra: types.OptionHelpExtra = {} 

3385 

3386 if self.show_envvar: 

3387 envvar = self.envvar 

3388 

3389 if envvar is None: 

3390 if ( 

3391 self.allow_from_autoenv 

3392 and ctx.auto_envvar_prefix is not None 

3393 and self.name 

3394 ): 

3395 envvar = f"{ctx.auto_envvar_prefix}_{self.name.upper()}" 

3396 

3397 if envvar is not None: 

3398 if isinstance(envvar, str): 

3399 extra["envvars"] = (envvar,) 

3400 else: 

3401 extra["envvars"] = tuple(str(d) for d in envvar) 

3402 

3403 # Temporarily enable resilient parsing to avoid type casting 

3404 # failing for the default. Might be possible to extend this to 

3405 # help formatting in general. 

3406 resilient = ctx.resilient_parsing 

3407 ctx.resilient_parsing = True 

3408 

3409 try: 

3410 default_value = self.get_default(ctx, call=False) 

3411 finally: 

3412 ctx.resilient_parsing = resilient 

3413 

3414 show_default = False 

3415 show_default_is_str = False 

3416 

3417 if self.show_default is not None: 

3418 if isinstance(self.show_default, str): 

3419 show_default_is_str = show_default = True 

3420 else: 

3421 show_default = self.show_default 

3422 elif ctx.show_default is not None: 

3423 show_default = ctx.show_default 

3424 

3425 if show_default_is_str or ( 

3426 show_default and (default_value not in (None, UNSET)) 

3427 ): 

3428 if show_default_is_str: 

3429 default_string = f"({self.show_default})" 

3430 elif isinstance(default_value, (list, tuple)): 

3431 default_string = ", ".join(str(d) for d in default_value) 

3432 elif isinstance(default_value, enum.Enum): 

3433 default_string = default_value.name 

3434 elif inspect.isfunction(default_value): 

3435 default_string = _("(dynamic)") 

3436 elif self.is_bool_flag and self.secondary_opts: 

3437 # For boolean flags that have distinct True/False opts, 

3438 # use the opt without prefix instead of the value. 

3439 default_string = _split_opt( 

3440 (self.opts if default_value else self.secondary_opts)[0] 

3441 )[1] 

3442 elif self.is_bool_flag and not self.secondary_opts and not default_value: 

3443 default_string = "" 

3444 elif isinstance(default_value, str) and default_value == "": 

3445 default_string = '""' 

3446 else: 

3447 default_string = str(default_value) 

3448 

3449 if default_string: 

3450 extra["default"] = default_string 

3451 

3452 if ( 

3453 isinstance(self.type, types._NumberRangeBase) 

3454 # skip count with default range type 

3455 and not (self.count and self.type.min == 0 and self.type.max is None) 

3456 ): 

3457 range_str = self.type._describe_range() 

3458 

3459 if range_str: 

3460 extra["range"] = range_str 

3461 

3462 if self.required: 

3463 extra["required"] = "required" 

3464 

3465 return extra 

3466 

3467 def prompt_for_value(self, ctx: Context) -> t.Any: 

3468 """This is an alternative flow that can be activated in the full 

3469 value processing if a value does not exist. It will prompt the 

3470 user until a valid value exists and then returns the processed 

3471 value as result. 

3472 """ 

3473 assert self.prompt is not None 

3474 

3475 # Calculate the default before prompting anything to lock in the value before 

3476 # attempting any user interaction. 

3477 default = self.get_default(ctx) 

3478 

3479 # A boolean flag can use a simplified [y/n] confirmation prompt. 

3480 if self.is_bool_flag: 

3481 # If we have no boolean default, we force the user to explicitly provide 

3482 # one. 

3483 if default in (UNSET, None): 

3484 default = None 

3485 # Nothing prevent you to declare an option that is simultaneously: 

3486 # 1) auto-detected as a boolean flag, 

3487 # 2) allowed to prompt, and 

3488 # 3) still declare a non-boolean default. 

3489 # This forced casting into a boolean is necessary to align any non-boolean 

3490 # default to the prompt, which is going to be a [y/n]-style confirmation 

3491 # because the option is still a boolean flag. That way, instead of [y/n], 

3492 # we get [Y/n] or [y/N] depending on the truthy value of the default. 

3493 # Refs: https://github.com/pallets/click/pull/3030#discussion_r2289180249 

3494 else: 

3495 default = bool(default) 

3496 return confirm(self.prompt, default) 

3497 

3498 # If show_default is given, provide this to `prompt` as well, 

3499 # otherwise we use `prompt`'s default behavior 

3500 prompt_kwargs: t.Any = {} 

3501 if self.show_default is not None: 

3502 prompt_kwargs["show_default"] = self.show_default 

3503 

3504 return prompt( 

3505 self.prompt, 

3506 # Use ``None`` to inform the prompt() function to reiterate until a valid 

3507 # value is provided by the user if we have no default. 

3508 default=self._hide_unset(default), 

3509 type=self.type, 

3510 hide_input=self.hide_input, 

3511 show_choices=self.show_choices, 

3512 confirmation_prompt=self.confirmation_prompt, 

3513 value_proc=lambda x: self.process_value(ctx, x), 

3514 **prompt_kwargs, 

3515 ) 

3516 

3517 def resolve_envvar_value(self, ctx: Context) -> str | None: 

3518 """:class:`Option` resolves its environment variable the same way as 

3519 :func:`Parameter.resolve_envvar_value`, but it also supports 

3520 :attr:`Context.auto_envvar_prefix`. If we could not find an environment from 

3521 the :attr:`envvar` property, we fallback on :attr:`Context.auto_envvar_prefix` 

3522 to build dynamiccaly the environment variable name using the 

3523 :python:`{ctx.auto_envvar_prefix}_{self.name.upper()}` template. 

3524 

3525 :meta private: 

3526 """ 

3527 rv = super().resolve_envvar_value(ctx) 

3528 

3529 if rv is not None: 

3530 return rv 

3531 

3532 if self.allow_from_autoenv and ctx.auto_envvar_prefix is not None and self.name: 

3533 envvar = f"{ctx.auto_envvar_prefix}_{self.name.upper()}" 

3534 rv = os.environ.get(envvar) 

3535 

3536 if rv: 

3537 return rv 

3538 

3539 return None 

3540 

3541 def value_from_envvar(self, ctx: Context) -> t.Any: 

3542 """For :class:`Option`, this method processes the raw environment variable 

3543 string the same way as :func:`Parameter.value_from_envvar` does. 

3544 

3545 But in the case of non-boolean flags, the value is analyzed to determine if the 

3546 flag is activated or not, and returns a boolean of its activation, or the 

3547 :attr:`flag_value` if the latter is set. 

3548 

3549 This method also takes care of repeated options (i.e. options with 

3550 :attr:`multiple` set to ``True``). 

3551 

3552 :meta private: 

3553 """ 

3554 rv = self.resolve_envvar_value(ctx) 

3555 

3556 # Absent environment variable or an empty string is interpreted as unset. 

3557 if rv is None: 

3558 return None 

3559 

3560 # Non-boolean flags are more liberal in what they accept. But a flag being a 

3561 # flag, its envvar value still needs to be analyzed to determine if the flag is 

3562 # activated or not. 

3563 if self.is_flag and not self.is_bool_flag: 

3564 # An exact match against ``flag_value`` (a non-bool flag always has one 

3565 # explicitly set) returns it directly. Otherwise the value is analyzed as a 

3566 # boolean: a truthy reading activates the flag and the function receives 

3567 # ``flag_value``; a falsy reading produces ``False``; an unrecognized 

3568 # reading falls through as ``None``. Folding the substitution here means 

3569 # :meth:`consume_value` no longer has to repeat it in a source-checked 

3570 # branch. 

3571 if rv == self.flag_value: 

3572 return self.flag_value 

3573 parsed = types.BoolParamType.str_to_bool(rv) 

3574 if parsed is None: 

3575 return None 

3576 return self.flag_value if parsed else False 

3577 

3578 # Split the envvar value if it is allowed to be repeated. 

3579 value_depth = (self.nargs != 1) + bool(self.multiple) 

3580 if value_depth > 0: 

3581 multi_rv = self.type.split_envvar_value(rv) 

3582 if self.multiple and self.nargs != 1: 

3583 multi_rv = batch(multi_rv, self.nargs) # type: ignore[assignment] 

3584 

3585 return multi_rv 

3586 

3587 return rv 

3588 

3589 def consume_value( 

3590 self, ctx: Context, opts: cabc.Mapping[str, Parameter] 

3591 ) -> tuple[t.Any, ParameterSource]: 

3592 """For :class:`Option`, the value can be collected from an interactive prompt 

3593 if the option is a flag that needs a value (and the :attr:`prompt` property is 

3594 set). 

3595 

3596 Additionally, this method handles flag option that are activated without a 

3597 value, in which case the :attr:`flag_value` is returned. 

3598 

3599 :meta private: 

3600 """ 

3601 value, source = super().consume_value(ctx, opts) 

3602 

3603 # The parser emits a sentinel when a flag is allowed to be used without a value. 

3604 # Resolve it to a prompt or to the activation value depending on the option's 

3605 # configuration. 

3606 if value is FLAG_NEEDS_VALUE: 

3607 # If the option allows for a prompt, start an interaction with the user. 

3608 if self.prompt is not None and not ctx.resilient_parsing: 

3609 value = self.prompt_for_value(ctx) 

3610 source = ParameterSource.PROMPT 

3611 # Else the flag takes its activation value (resolves UNSET). 

3612 else: 

3613 value = self.flag_activation_value 

3614 source = ParameterSource.COMMANDLINE 

3615 

3616 # Re-interpret a multiple option that the parser sent through as a list still 

3617 # containing the FLAG_NEEDS_VALUE sentinel, replacing each occurrence with the 

3618 # activation value. 

3619 elif ( 

3620 self.multiple 

3621 and value is not UNSET 

3622 and isinstance(value, cabc.Iterable) 

3623 and source < ParameterSource.DEFAULT_MAP 

3624 and any(v is FLAG_NEEDS_VALUE for v in value) 

3625 ): 

3626 value = [ 

3627 self.flag_activation_value if v is FLAG_NEEDS_VALUE else v 

3628 for v in value 

3629 ] 

3630 source = ParameterSource.COMMANDLINE 

3631 

3632 # The value wasn't set, or used the param's default, prompt for one to the user 

3633 # if prompting is enabled. 

3634 elif ( 

3635 (value is UNSET or source >= ParameterSource.DEFAULT_MAP) 

3636 and self.prompt is not None 

3637 and (self.required or self.prompt_required) 

3638 and not ctx.resilient_parsing 

3639 ): 

3640 value = self.prompt_for_value(ctx) 

3641 source = ParameterSource.PROMPT 

3642 

3643 return value, source 

3644 

3645 def process_value(self, ctx: Context, value: t.Any) -> t.Any: 

3646 # process_value has to be overridden on Options in order to capture 

3647 # `value == UNSET` cases before `type_cast_value()` gets called. 

3648 # 

3649 # Refs: 

3650 # https://github.com/pallets/click/issues/3069 

3651 if self.is_flag and not self.required and self.is_bool_flag and value is UNSET: 

3652 value = False 

3653 

3654 if self.callback is not None: 

3655 value = self.callback(ctx, self, value) 

3656 

3657 return value 

3658 

3659 # in the normal case, rely on Parameter.process_value 

3660 return super().process_value(ctx, value) 

3661 

3662 

3663class Argument(Parameter): 

3664 """Arguments are positional parameters to a command. They generally 

3665 provide fewer features than options but can have infinite ``nargs`` 

3666 and are required by default. 

3667 

3668 All parameters are passed onwards to the constructor of :class:`Parameter`. 

3669 

3670 :param help: the help string. 

3671 

3672 .. versionchanged:: 8.5.0 

3673 Added the ``help`` parameter. 

3674 """ 

3675 

3676 param_type_name = "argument" 

3677 

3678 def __init__( 

3679 self, 

3680 param_decls: cabc.Sequence[str], 

3681 required: bool | None = None, 

3682 help: str | None = None, 

3683 **attrs: t.Any, 

3684 ) -> None: 

3685 # Auto-detect the requirement status of the argument if not explicitly set. 

3686 if required is None: 

3687 # The argument gets automatically required if it has no explicit default 

3688 # value set and is setup to match at least one value. 

3689 if attrs.get("default", UNSET) is UNSET: 

3690 required = attrs.get("nargs", 1) > 0 

3691 # If the argument has a default value, it is not required. 

3692 else: 

3693 required = False 

3694 

3695 if "multiple" in attrs: 

3696 raise TypeError("__init__() got an unexpected keyword argument 'multiple'.") 

3697 

3698 deprecated = attrs.get("deprecated", False) 

3699 

3700 if help: 

3701 help = inspect.cleandoc(help) 

3702 

3703 if deprecated: 

3704 label = _format_deprecated_label(deprecated) 

3705 help = f"{help} {label}" if help else label 

3706 

3707 self.help = help 

3708 

3709 super().__init__(param_decls, required=required, **attrs) 

3710 

3711 def to_info_dict(self) -> dict[str, t.Any]: 

3712 info_dict = super().to_info_dict() 

3713 info_dict.update(help=self.help) 

3714 return info_dict 

3715 

3716 @property 

3717 def human_readable_name(self) -> str: 

3718 if self.metavar is not None: 

3719 return self.metavar 

3720 return self.name.upper() 

3721 

3722 def make_metavar(self, ctx: Context) -> str: 

3723 if self.metavar is not None: 

3724 return self.metavar 

3725 var = self.type.get_metavar(param=self, ctx=ctx) 

3726 if not var: 

3727 var = self.name.upper() 

3728 # Types like ``Choice`` and ``DateTime`` already surround their metavar 

3729 # with square brackets to enumerate the allowed values. Reuse those 

3730 # outer brackets as the optional-argument indicator instead of wrapping 

3731 # the metavar in a second pair, which would produce ``[[a|b|c]]``. 

3732 already_bracketed = var.startswith("[") and var.endswith("]") 

3733 if self.deprecated: 

3734 var += "!" 

3735 if not self.required and not already_bracketed: 

3736 var = f"[{var}]" 

3737 if self.nargs != 1: 

3738 var += "..." 

3739 return var 

3740 

3741 def _parse_decls( 

3742 self, decls: cabc.Sequence[str], expose_value: bool 

3743 ) -> tuple[str, list[str], list[str]]: 

3744 if not decls: 

3745 if not expose_value: 

3746 return "", [], [] 

3747 raise TypeError("Argument is marked as exposed, but does not have a name.") 

3748 if len(decls) == 1: 

3749 name = arg = decls[0] 

3750 name = name.replace("-", "_").lower() 

3751 else: 

3752 raise TypeError( 

3753 _( 

3754 "Arguments take exactly one parameter declaration, got" 

3755 " {length}: {decls}." 

3756 ).format(length=len(decls), decls=decls) 

3757 ) 

3758 return name, [arg], [] 

3759 

3760 def get_usage_pieces(self, ctx: Context) -> list[str]: 

3761 return [self.make_metavar(ctx)] 

3762 

3763 def get_help_record(self, ctx: Context) -> tuple[str, str] | None: 

3764 if self.help is None: 

3765 return None 

3766 

3767 return self.make_metavar(ctx), self.help 

3768 

3769 def get_error_hint(self, ctx: Context | None) -> str: 

3770 if ctx is not None: 

3771 return f"'{self.make_metavar(ctx)}'" 

3772 return f"'{self.human_readable_name}'" 

3773 

3774 def add_to_parser(self, parser: _OptionParser, ctx: Context) -> None: 

3775 parser.add_argument(dest=self.name, nargs=self.nargs, obj=self) 

3776 

3777 

3778def __getattr__(name: str) -> object: 

3779 import warnings 

3780 

3781 if name == "BaseCommand": 

3782 warnings.warn( 

3783 "'BaseCommand' is deprecated and will be removed in Click 9.0. Use" 

3784 " 'Command' instead.", 

3785 DeprecationWarning, 

3786 stacklevel=2, 

3787 ) 

3788 return _BaseCommand 

3789 

3790 if name == "MultiCommand": 

3791 warnings.warn( 

3792 "'MultiCommand' is deprecated and will be removed in Click 9.0. Use" 

3793 " 'Group' instead.", 

3794 DeprecationWarning, 

3795 stacklevel=2, 

3796 ) 

3797 return _MultiCommand 

3798 

3799 raise AttributeError(name)