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

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1341 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 echo 

46from .utils import make_default_short_help 

47from .utils import make_str 

48from .utils import PacifyFlushWrapper 

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 

59def _complete_visible_commands( 

60 ctx: Context, incomplete: str 

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

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

63 incomplete value and aren't hidden. 

64 

65 :param ctx: Invocation context for the group. 

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

67 """ 

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

69 

70 for name in multi.list_commands(ctx): 

71 if name.startswith(incomplete): 

72 command = multi.get_command(ctx, name) 

73 

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

75 yield name, command 

76 

77 

78def _check_nested_chain( 

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

80) -> None: 

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

82 return 

83 

84 if register: 

85 message = ( 

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

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

88 ) 

89 else: 

90 message = ( 

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

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

93 ) 

94 

95 raise RuntimeError(message) 

96 

97 

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

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

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

101 if isinstance(deprecated, str): 

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

103 return f"({label})" 

104 

105 

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

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

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

109 """ 

110 if isinstance(deprecated, str): 

111 return f" {deprecated}" 

112 return "" 

113 

114 

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

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

117 

118 

119@contextmanager 

120def augment_usage_errors( 

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

122) -> cabc.Generator[None]: 

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

124 try: 

125 yield 

126 except BadParameter as e: 

127 if e.ctx is None: 

128 e.ctx = ctx 

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

130 e.param = param 

131 raise 

132 except UsageError as e: 

133 if e.ctx is None: 

134 e.ctx = ctx 

135 raise 

136 

137 

138def iter_params_for_processing( 

139 invocation_order: cabc.Sequence[Parameter], 

140 declaration_order: cabc.Sequence[Parameter], 

141) -> list[Parameter]: 

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

143 

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

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

146 

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

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

149 

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

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

152 """ 

153 

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

155 try: 

156 idx: float = invocation_order.index(item) 

157 except ValueError: 

158 idx = float("inf") 

159 

160 return not item.is_eager, idx 

161 

162 return sorted(declaration_order, key=sort_key) 

163 

164 

165class ParameterSource(enum.IntEnum): 

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

167 parameter's value. 

168 

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

170 source for a parameter by name. 

171 

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

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

174 

175 .. code-block:: python 

176 

177 source = ctx.get_parameter_source("port") 

178 if source < click.ParameterSource.DEFAULT_MAP: 

179 ... # value was explicitly set 

180 

181 .. versionchanged:: 8.3.3 

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

183 least explicit. Supports comparison operators. 

184 

185 .. versionchanged:: 8.0 

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

187 

188 .. versionchanged:: 8.0 

189 Added the ``PROMPT`` value. 

190 """ 

191 

192 PROMPT = enum.auto() 

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

194 COMMANDLINE = enum.auto() 

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

196 ENVIRONMENT = enum.auto() 

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

198 DEFAULT_MAP = enum.auto() 

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

200 DEFAULT = enum.auto() 

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

202 

203 

204class Context: 

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

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

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

208 

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

210 control special execution features such as reading data from 

211 environment variables. 

212 

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

214 :meth:`close` on teardown. 

215 

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

217 :param parent: the parent context. 

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

219 is the most descriptive name for the script or 

220 command. For the toplevel script it is usually 

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

222 the name of the script. 

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

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

225 variables. If this is `None` then reading 

226 from environment variables is disabled. This 

227 does not affect manually set environment 

228 variables which are always read. 

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

230 for parameters. 

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

232 inherit from parent context. If no context 

233 defines the terminal width then auto 

234 detection will be applied. 

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

236 Click (this currently only affects help 

237 pages). This defaults to 80 characters if 

238 not overridden. In other words: even if the 

239 terminal is larger than that, Click will not 

240 format things wider than 80 characters by 

241 default. In addition to that, formatters might 

242 add some safety mapping on the right. 

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

244 parse without any interactivity or callback 

245 invocation. Default values will also be 

246 ignored. This is useful for implementing 

247 things such as completion support. 

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

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

250 kept on the context. The default is to inherit 

251 from the command. 

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

253 and arguments cannot be mixed. The 

254 default is to inherit from the command. 

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

256 not know and keeps them for later 

257 processing. 

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

259 the default help parameter is named. The 

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

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

262 normalize tokens (options, choices, 

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

264 implement case insensitive behavior. 

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

266 default is autodetection. This is only needed if ANSI 

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

268 default not the case. This for instance would affect 

269 help output. 

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

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

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

273 specific command. 

274 

275 .. versionchanged:: 8.2 

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

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

278 

279 .. versionchanged:: 8.1 

280 The ``show_default`` parameter is overridden by 

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

282 

283 .. versionchanged:: 8.0 

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

285 parent context. 

286 

287 .. versionchanged:: 7.1 

288 Added the ``show_default`` parameter. 

289 

290 .. versionchanged:: 4.0 

291 Added the ``color``, ``ignore_unknown_options``, and 

292 ``max_content_width`` parameters. 

293 

294 .. versionchanged:: 3.0 

295 Added the ``allow_extra_args`` and ``allow_interspersed_args`` 

296 parameters. 

297 

298 .. versionchanged:: 2.0 

299 Added the ``resilient_parsing``, ``help_option_names``, and 

300 ``token_normalize_func`` parameters. 

301 """ 

302 

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

304 #: 

305 #: .. versionadded:: 8.0 

306 formatter_class: type[HelpFormatter] = HelpFormatter 

307 

308 parent: Context | None 

309 command: Command 

310 info_name: str | None 

311 params: dict[str, t.Any] 

312 args: list[str] 

313 _protected_args: list[str] 

314 _opt_prefixes: set[str] 

315 obj: t.Any 

316 _meta: dict[str, t.Any] 

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

318 invoked_subcommand: str | None 

319 terminal_width: int | None 

320 max_content_width: int | None 

321 allow_extra_args: bool 

322 allow_interspersed_args: bool 

323 ignore_unknown_options: bool 

324 help_option_names: list[str] 

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

326 resilient_parsing: bool 

327 auto_envvar_prefix: str | None 

328 color: bool | None 

329 show_default: bool | None 

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

331 _depth: int 

332 _parameter_source: dict[str, ParameterSource] 

333 _param_default_explicit: dict[str, bool] 

334 _exit_stack: ExitStack 

335 

336 def __init__( 

337 self, 

338 command: Command, 

339 parent: Context | None = None, 

340 info_name: str | None = None, 

341 obj: t.Any | None = None, 

342 auto_envvar_prefix: str | None = None, 

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

344 terminal_width: int | None = None, 

345 max_content_width: int | None = None, 

346 resilient_parsing: bool = False, 

347 allow_extra_args: bool | None = None, 

348 allow_interspersed_args: bool | None = None, 

349 ignore_unknown_options: bool | None = None, 

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

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

352 color: bool | None = None, 

353 show_default: bool | None = None, 

354 ) -> None: 

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

356 self.parent = parent 

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

358 self.command = command 

359 #: the descriptive information name 

360 self.info_name = info_name 

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

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

363 self.params = {} 

364 #: the leftover arguments. 

365 self.args = [] 

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

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

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

369 #: to implement nested parsing. 

370 self._protected_args = [] 

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

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

373 

374 if obj is None and parent is not None: 

375 obj = parent.obj 

376 

377 #: the user object stored. 

378 self.obj = obj 

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

380 

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

382 if ( 

383 default_map is None 

384 and info_name is not None 

385 and parent is not None 

386 and parent.default_map is not None 

387 ): 

388 default_map = parent.default_map.get(info_name) 

389 

390 self.default_map = default_map 

391 

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

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

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

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

396 #: the name of the subcommand to execute. 

397 #: 

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

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

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

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

402 self.invoked_subcommand = None 

403 

404 if terminal_width is None and parent is not None: 

405 terminal_width = parent.terminal_width 

406 

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

408 self.terminal_width = terminal_width 

409 

410 if max_content_width is None and parent is not None: 

411 max_content_width = parent.max_content_width 

412 

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

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

415 self.max_content_width = max_content_width 

416 

417 if allow_extra_args is None: 

418 allow_extra_args = command.allow_extra_args 

419 

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

421 #: fail on parsing. 

422 #: 

423 #: .. versionadded:: 3.0 

424 self.allow_extra_args = allow_extra_args 

425 

426 if allow_interspersed_args is None: 

427 allow_interspersed_args = command.allow_interspersed_args 

428 

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

430 #: options or not. 

431 #: 

432 #: .. versionadded:: 3.0 

433 self.allow_interspersed_args = allow_interspersed_args 

434 

435 if ignore_unknown_options is None: 

436 ignore_unknown_options = command.ignore_unknown_options 

437 

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

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

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

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

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

443 #: forward all arguments. 

444 #: 

445 #: .. versionadded:: 4.0 

446 self.ignore_unknown_options = ignore_unknown_options 

447 

448 if help_option_names is None: 

449 if parent is not None: 

450 help_option_names = parent.help_option_names 

451 else: 

452 help_option_names = ["--help"] 

453 

454 #: The names for the help options. 

455 self.help_option_names = help_option_names 

456 

457 if token_normalize_func is None and parent is not None: 

458 token_normalize_func = parent.token_normalize_func 

459 

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

461 #: options, choices, commands etc. 

462 self.token_normalize_func = token_normalize_func 

463 

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

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

466 #: will be ignored. Useful for completion. 

467 self.resilient_parsing = resilient_parsing 

468 

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

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

471 # prefix automatically. 

472 if auto_envvar_prefix is None: 

473 if ( 

474 parent is not None 

475 and parent.auto_envvar_prefix is not None 

476 and self.info_name is not None 

477 ): 

478 auto_envvar_prefix = ( 

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

480 ) 

481 else: 

482 auto_envvar_prefix = auto_envvar_prefix.upper() 

483 

484 if auto_envvar_prefix is not None: 

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

486 

487 self.auto_envvar_prefix = auto_envvar_prefix 

488 

489 if color is None and parent is not None: 

490 color = parent.color 

491 

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

493 self.color = color 

494 

495 if show_default is None and parent is not None: 

496 show_default = parent.show_default 

497 

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

499 self.show_default = show_default 

500 

501 self._close_callbacks = [] 

502 self._depth = 0 

503 self._parameter_source = {} 

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

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

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

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

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

509 self._param_default_explicit = {} 

510 self._exit_stack = ExitStack() 

511 

512 @property 

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

514 import warnings 

515 

516 warnings.warn( 

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

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

519 DeprecationWarning, 

520 stacklevel=2, 

521 ) 

522 return self._protected_args 

523 

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

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

526 user-facing documentation. This traverses the entire CLI 

527 structure. 

528 

529 .. code-block:: python 

530 

531 with Context(cli) as ctx: 

532 info = ctx.to_info_dict() 

533 

534 .. versionadded:: 8.0 

535 """ 

536 return { 

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

538 "info_name": self.info_name, 

539 "allow_extra_args": self.allow_extra_args, 

540 "allow_interspersed_args": self.allow_interspersed_args, 

541 "ignore_unknown_options": self.ignore_unknown_options, 

542 "auto_envvar_prefix": self.auto_envvar_prefix, 

543 } 

544 

545 def __enter__(self) -> Self: 

546 self._depth += 1 

547 push_context(self) 

548 return self 

549 

550 def __exit__( 

551 self, 

552 exc_type: type[BaseException] | None, 

553 exc_value: BaseException | None, 

554 tb: TracebackType | None, 

555 ) -> bool | None: 

556 self._depth -= 1 

557 exit_result: bool | None = None 

558 if self._depth == 0: 

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

560 pop_context() 

561 

562 return exit_result 

563 

564 @contextmanager 

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

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

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

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

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

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

571 

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

573 used as a context manager. 

574 

575 Example usage:: 

576 

577 with ctx.scope(): 

578 assert get_current_context() is ctx 

579 

580 This is equivalent:: 

581 

582 with ctx: 

583 assert get_current_context() is ctx 

584 

585 .. versionadded:: 5.0 

586 

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

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

589 some situations the context only wants to be 

590 temporarily pushed in which case this can be disabled. 

591 Nested pushes automatically defer the cleanup. 

592 """ 

593 if not cleanup: 

594 self._depth += 1 

595 try: 

596 with self as rv: 

597 yield rv 

598 finally: 

599 if not cleanup: 

600 self._depth -= 1 

601 

602 @property 

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

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

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

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

607 that code to manage this dictionary well. 

608 

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

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

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

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

613 the system. 

614 

615 Example usage:: 

616 

617 LANG_KEY = f'{__name__}.lang' 

618 

619 def set_language(value): 

620 ctx = get_current_context() 

621 ctx.meta[LANG_KEY] = value 

622 

623 def get_language(): 

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

625 

626 .. versionadded:: 5.0 

627 """ 

628 return self._meta 

629 

630 def make_formatter(self) -> HelpFormatter: 

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

632 usage output. 

633 

634 To quickly customize the formatter class used without overriding 

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

636 

637 .. versionchanged:: 8.0 

638 Added the :attr:`formatter_class` attribute. 

639 """ 

640 return self.formatter_class( 

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

642 ) 

643 

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

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

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

647 popped. 

648 

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

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

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

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

653 

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

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

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

657 

658 .. code-block:: python 

659 

660 @click.group() 

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

662 @click.pass_context 

663 def cli(ctx): 

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

665 

666 :param context_manager: The context manager to enter. 

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

668 

669 .. versionadded:: 8.0 

670 """ 

671 return self._exit_stack.enter_context(context_manager) 

672 

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

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

675 

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

677 execution. Resources that support Python's context manager 

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

679 registered with :meth:`with_resource` instead. 

680 

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

682 """ 

683 return self._exit_stack.callback(f) 

684 

685 def close(self) -> None: 

686 """Invoke all close callbacks registered with 

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

688 with :meth:`with_resource`. 

689 """ 

690 self._close_with_exception_info(None, None, None) 

691 

692 def _close_with_exception_info( 

693 self, 

694 exc_type: type[BaseException] | None, 

695 exc_value: BaseException | None, 

696 tb: TracebackType | None, 

697 ) -> bool | None: 

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

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

700 using :meth;`with_resource` 

701 

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

703 """ 

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

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

706 self._exit_stack = ExitStack() 

707 

708 return exit_result 

709 

710 @property 

711 def command_path(self) -> str: 

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

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

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

715 """ 

716 rv = "" 

717 if self.info_name is not None: 

718 rv = self.info_name 

719 if self.parent is not None: 

720 parent_command_path = [self.parent.command_path] 

721 

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

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

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

725 

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

727 return rv.lstrip() 

728 

729 def find_root(self) -> Context: 

730 """Finds the outermost context.""" 

731 node = self 

732 while node.parent is not None: 

733 node = node.parent 

734 return node 

735 

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

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

738 node: Context | None = self 

739 

740 while node is not None: 

741 if isinstance(node.obj, object_type): 

742 return node.obj 

743 

744 node = node.parent 

745 

746 return None 

747 

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

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

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

751 """ 

752 rv = self.find_object(object_type) 

753 if rv is None: 

754 self.obj = rv = object_type() 

755 return rv 

756 

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

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

759 

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

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

762 :data:`UNSET` sentinel. 

763 """ 

764 return ( 

765 name is not None 

766 and self.default_map is not None 

767 and name in self.default_map 

768 and self.default_map[name] is not UNSET 

769 ) 

770 

771 @t.overload 

772 def lookup_default( 

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

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

775 

776 @t.overload 

777 def lookup_default( 

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

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

780 

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

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

783 

784 :param name: Name of the parameter. 

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

786 return the callable instead. 

787 

788 .. versionchanged:: 8.0 

789 Added the ``call`` parameter. 

790 """ 

791 if not self._default_map_has(name): 

792 return None 

793 

794 # Assert to make the type checker happy. 

795 assert self.default_map is not None 

796 value = self.default_map[name] 

797 

798 if call and callable(value): 

799 return value() 

800 

801 return value 

802 

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

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

805 message. 

806 

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

808 """ 

809 raise UsageError(message, self) 

810 

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

812 """Aborts the script.""" 

813 raise Abort() 

814 

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

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

817 

818 .. versionchanged:: 8.2 

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

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

821 """ 

822 self.close() 

823 raise Exit(code) 

824 

825 def get_usage(self) -> str: 

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

827 context and command. 

828 """ 

829 return self.command.get_usage(self) 

830 

831 def get_help(self) -> str: 

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

833 context and command. 

834 """ 

835 return self.command.get_help(self) 

836 

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

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

839 for a new command. 

840 

841 :meta private: 

842 """ 

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

844 

845 @t.overload 

846 def invoke( 

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

848 ) -> V: ... 

849 

850 @t.overload 

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

852 

853 def invoke( 

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

855 ) -> t.Any | V: 

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

857 are two ways to invoke this method: 

858 

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

860 keyword arguments are forwarded directly to the function. 

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

862 arguments are forwarded as well but proper click parameters 

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

864 will fill in defaults. 

865 

866 .. versionchanged:: 8.0 

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

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

869 

870 .. versionchanged:: 3.2 

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

872 """ 

873 if isinstance(callback, Command): 

874 other_cmd = callback 

875 

876 if other_cmd.callback is None: 

877 raise TypeError( 

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

879 ) 

880 else: 

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

882 

883 ctx = self._make_sub_context(other_cmd) 

884 

885 for param in other_cmd.params: 

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

887 default_value = param.get_default(ctx) 

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

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

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

891 # instead. Refs: 

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

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

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

895 if default_value is UNSET: 

896 default_value = None 

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

898 

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

900 # them on in subsequent calls. 

901 ctx.params.update(kwargs) 

902 else: 

903 ctx = self 

904 

905 with augment_usage_errors(self): 

906 with ctx: 

907 return callback(*args, **kwargs) 

908 

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

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

911 arguments from the current context if the other command expects 

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

913 

914 .. versionchanged:: 8.0 

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

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

917 """ 

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

919 if not isinstance(cmd, Command): 

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

921 

922 for param in self.params: 

923 if param not in kwargs: 

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

925 

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

927 

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

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

930 from which the value of the parameter was obtained. 

931 

932 :param name: The name of the parameter. 

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

934 """ 

935 self._parameter_source[name] = source 

936 

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

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

939 from which the value of the parameter was obtained. 

940 

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

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

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

944 value was actually taken from the default. 

945 

946 :param name: The name of the parameter. 

947 :rtype: ParameterSource 

948 

949 .. versionchanged:: 8.0 

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

951 source. 

952 """ 

953 return self._parameter_source.get(name) 

954 

955 

956class Command: 

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

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

959 more parsing to commands nested below it. 

960 

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

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

963 passed to the context object. 

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

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

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

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

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

969 help page after everything else. 

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

971 shown on the command listing of the parent command. 

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

973 option. This can be disabled by this parameter. 

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

975 provided. This option is disabled by default. 

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

977 if no arguments are passed 

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

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

980 indicating that the command is deprecated and highlights 

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

982 by using a string as the value. 

983 

984 .. versionchanged:: 8.2 

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

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

987 deprecation message. 

988 

989 .. versionchanged:: 8.1 

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

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

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

993 

994 .. versionchanged:: 8.0 

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

996 

997 .. versionchanged:: 7.1 

998 Added the ``no_args_is_help`` parameter. 

999 

1000 .. versionchanged:: 2.0 

1001 Added the ``context_settings`` parameter. 

1002 """ 

1003 

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

1005 #: 

1006 #: .. versionadded:: 8.0 

1007 context_class: type[Context] = Context 

1008 

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

1010 allow_extra_args = False 

1011 

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

1013 allow_interspersed_args = True 

1014 

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

1016 ignore_unknown_options = False 

1017 

1018 name: str | None 

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

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

1021 params: list[Parameter] 

1022 help: str | None 

1023 epilog: str | None 

1024 options_metavar: str | None 

1025 short_help: str | None 

1026 add_help_option: bool 

1027 _help_option: Option | None 

1028 no_args_is_help: bool 

1029 hidden: bool 

1030 deprecated: bool | str 

1031 

1032 def __init__( 

1033 self, 

1034 name: str | None, 

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

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

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

1038 help: str | None = None, 

1039 epilog: str | None = None, 

1040 short_help: str | None = None, 

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

1042 add_help_option: bool = True, 

1043 no_args_is_help: bool = False, 

1044 hidden: bool = False, 

1045 deprecated: bool | str = False, 

1046 ) -> None: 

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

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

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

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

1051 self.name = name 

1052 

1053 if context_settings is None: 

1054 context_settings = {} 

1055 

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

1057 self.context_settings = context_settings 

1058 

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

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

1061 self.callback = callback 

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

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

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

1065 self.params = params or [] 

1066 self.help = help 

1067 self.epilog = epilog 

1068 self.options_metavar = options_metavar 

1069 self.short_help = short_help 

1070 self.add_help_option = add_help_option 

1071 self._help_option = None 

1072 self.no_args_is_help = no_args_is_help 

1073 self.hidden = hidden 

1074 self.deprecated = deprecated 

1075 

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

1077 return { 

1078 "name": self.name, 

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

1080 "help": self.help, 

1081 "epilog": self.epilog, 

1082 "short_help": self.short_help, 

1083 "hidden": self.hidden, 

1084 "deprecated": self.deprecated, 

1085 } 

1086 

1087 def __repr__(self) -> str: 

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

1089 

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

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

1092 

1093 Calls :meth:`format_usage` internally. 

1094 """ 

1095 formatter = ctx.make_formatter() 

1096 self.format_usage(ctx, formatter) 

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

1098 

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

1100 params = self.params 

1101 help_option = self.get_help_option(ctx) 

1102 

1103 if help_option is not None: 

1104 params = [*params, help_option] 

1105 

1106 if __debug__: 

1107 import warnings 

1108 

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

1110 opts_counter = Counter(opts) 

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

1112 

1113 for duplicate_opt in duplicate_opts: 

1114 warnings.warn( 

1115 ( 

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

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

1118 ), 

1119 stacklevel=3, 

1120 ) 

1121 

1122 return params 

1123 

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

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

1126 

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

1128 """ 

1129 pieces = self.collect_usage_pieces(ctx) 

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

1131 

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

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

1134 it as a list of strings. 

1135 """ 

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

1137 

1138 for param in self.get_params(ctx): 

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

1140 

1141 return rv 

1142 

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

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

1145 all_names = set(ctx.help_option_names) 

1146 for param in self.params: 

1147 all_names.difference_update(param.opts) 

1148 all_names.difference_update(param.secondary_opts) 

1149 return list(all_names) 

1150 

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

1152 """Returns the help option object. 

1153 

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

1155 

1156 .. versionchanged:: 8.1.8 

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

1158 """ 

1159 help_option_names = self.get_help_option_names(ctx) 

1160 

1161 if not help_option_names or not self.add_help_option: 

1162 return None 

1163 

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

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

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

1167 # object comparison. 

1168 if self._help_option is None: 

1169 # Avoid circular import. 

1170 from .decorators import help_option 

1171 

1172 # Apply help_option decorator and pop resulting option 

1173 help_option(*help_option_names)(self) 

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

1175 

1176 return self._help_option 

1177 

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

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

1180 parser = _OptionParser(ctx) 

1181 for param in self.get_params(ctx): 

1182 param.add_to_parser(parser, ctx) 

1183 return parser 

1184 

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

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

1187 

1188 Calls :meth:`format_help` internally. 

1189 """ 

1190 formatter = ctx.make_formatter() 

1191 self.format_help(ctx, formatter) 

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

1193 

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

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

1196 long help string. 

1197 """ 

1198 if self.short_help: 

1199 text = inspect.cleandoc(self.short_help) 

1200 elif self.help: 

1201 text = make_default_short_help(self.help, limit) 

1202 else: 

1203 text = "" 

1204 

1205 if self.deprecated: 

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

1207 

1208 return text.strip() 

1209 

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

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

1212 

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

1214 

1215 This calls the following methods: 

1216 

1217 - :meth:`format_usage` 

1218 - :meth:`format_help_text` 

1219 - :meth:`format_options` 

1220 - :meth:`format_epilog` 

1221 """ 

1222 self.format_usage(ctx, formatter) 

1223 self.format_help_text(ctx, formatter) 

1224 self.format_options(ctx, formatter) 

1225 self.format_epilog(ctx, formatter) 

1226 

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

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

1229 if self.help is not None: 

1230 # truncate the help text to the first form feed 

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

1232 else: 

1233 text = "" 

1234 

1235 if self.deprecated: 

1236 label = _format_deprecated_label(self.deprecated) 

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

1238 

1239 if text: 

1240 formatter.write_paragraph() 

1241 

1242 with formatter.indentation(): 

1243 formatter.write_text(text) 

1244 

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

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

1247 opts = [] 

1248 for param in self.get_params(ctx): 

1249 rv = param.get_help_record(ctx) 

1250 if rv is not None: 

1251 opts.append(rv) 

1252 

1253 if opts: 

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

1255 formatter.write_dl(opts) 

1256 

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

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

1259 if self.epilog: 

1260 epilog = inspect.cleandoc(self.epilog) 

1261 formatter.write_paragraph() 

1262 

1263 with formatter.indentation(): 

1264 formatter.write_text(epilog) 

1265 

1266 def make_context( 

1267 self, 

1268 info_name: str | None, 

1269 args: list[str], 

1270 parent: Context | None = None, 

1271 **extra: t.Any, 

1272 ) -> Context: 

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

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

1275 invoke the actual command callback though. 

1276 

1277 To quickly customize the context class used without overriding 

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

1279 

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

1281 is the most descriptive name for the script or 

1282 command. For the toplevel script it's usually 

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

1284 the name of the command. 

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

1286 :param parent: the parent context if available. 

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

1288 constructor. 

1289 

1290 .. versionchanged:: 8.0 

1291 Added the :attr:`context_class` attribute. 

1292 """ 

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

1294 if key not in extra: 

1295 extra[key] = value 

1296 

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

1298 

1299 with ctx.scope(cleanup=False): 

1300 self.parse_args(ctx, args) 

1301 return ctx 

1302 

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

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

1305 raise NoArgsIsHelpError(ctx) 

1306 

1307 parser = self.make_parser(ctx) 

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

1309 

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

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

1312 

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

1314 # the `UNSET` sentinel. 

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

1316 # 

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

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

1319 # Refs: 

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

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

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

1323 if value is UNSET: 

1324 ctx.params[name] = None 

1325 

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

1327 ctx.fail( 

1328 ngettext( 

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

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

1331 len(args), 

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

1333 ) 

1334 

1335 ctx.args = args 

1336 ctx._opt_prefixes.update(parser._opt_prefixes) 

1337 return args 

1338 

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

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

1341 in the right way. 

1342 """ 

1343 if self.deprecated: 

1344 message = _( 

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

1346 ).format( 

1347 name=self.name, 

1348 extra_message=_format_deprecated_suffix(self.deprecated), 

1349 ) 

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

1351 

1352 if self.callback is not None: 

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

1354 

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

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

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

1358 

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

1360 commands are valid at any point during command completion. 

1361 

1362 :param ctx: Invocation context for this command. 

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

1364 

1365 .. versionadded:: 8.0 

1366 """ 

1367 from click.shell_completion import CompletionItem 

1368 

1369 results: list[CompletionItem] = [] 

1370 

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

1372 for param in self.get_params(ctx): 

1373 if ( 

1374 not isinstance(param, Option) 

1375 or param.hidden 

1376 or ( 

1377 not param.multiple 

1378 and ctx.get_parameter_source(param.name) 

1379 is ParameterSource.COMMANDLINE 

1380 ) 

1381 ): 

1382 continue 

1383 

1384 results.extend( 

1385 CompletionItem(name, help=param.help) 

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

1387 if name.startswith(incomplete) 

1388 ) 

1389 

1390 while ctx.parent is not None: 

1391 ctx = ctx.parent 

1392 

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

1394 results.extend( 

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

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

1397 if name not in ctx._protected_args 

1398 ) 

1399 

1400 return results 

1401 

1402 @t.overload 

1403 def main( 

1404 self, 

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

1406 prog_name: str | None = None, 

1407 complete_var: str | None = None, 

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

1409 **extra: t.Any, 

1410 ) -> t.NoReturn: ... 

1411 

1412 @t.overload 

1413 def main( 

1414 self, 

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

1416 prog_name: str | None = None, 

1417 complete_var: str | None = None, 

1418 standalone_mode: bool = ..., 

1419 **extra: t.Any, 

1420 ) -> t.Any: ... 

1421 

1422 def main( 

1423 self, 

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

1425 prog_name: str | None = None, 

1426 complete_var: str | None = None, 

1427 standalone_mode: bool = True, 

1428 windows_expand_args: bool = True, 

1429 **extra: t.Any, 

1430 ) -> t.Any: 

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

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

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

1434 needs to be caught. 

1435 

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

1437 a :class:`Command`. 

1438 

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

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

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

1442 the program name is constructed by taking the file 

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

1444 :param complete_var: the environment variable that controls the 

1445 bash completion support. The default is 

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

1447 uppercase. 

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

1449 in standalone mode. Click will then 

1450 handle exceptions and convert them into 

1451 error messages and the function will never 

1452 return but shut down the interpreter. If 

1453 this is set to `False` they will be 

1454 propagated to the caller and the return 

1455 value of this function is the return value 

1456 of :meth:`invoke`. 

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

1458 env vars in command line args on Windows. 

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

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

1461 

1462 .. versionchanged:: 8.0.1 

1463 Added the ``windows_expand_args`` parameter to allow 

1464 disabling command line arg expansion on Windows. 

1465 

1466 .. versionchanged:: 8.0 

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

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

1469 

1470 .. versionchanged:: 3.0 

1471 Added the ``standalone_mode`` parameter. 

1472 """ 

1473 if args is None: 

1474 args = sys.argv[1:] 

1475 

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

1477 args = _expand_args(args) 

1478 else: 

1479 args = list(args) 

1480 

1481 if prog_name is None: 

1482 prog_name = _detect_program_name() 

1483 

1484 # Process shell completion requests and exit early. 

1485 self._main_shell_completion(extra, prog_name, complete_var) 

1486 

1487 try: 

1488 try: 

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

1490 rv = self.invoke(ctx) 

1491 if not standalone_mode: 

1492 return rv 

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

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

1495 # has obvious effects 

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

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

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

1499 # by its truthiness/falsiness 

1500 ctx.exit() 

1501 except (EOFError, KeyboardInterrupt) as e: 

1502 echo(file=sys.stderr) 

1503 raise Abort() from e 

1504 except ClickException as e: 

1505 if not standalone_mode: 

1506 raise 

1507 e.show() 

1508 sys.exit(e.exit_code) 

1509 except OSError as e: 

1510 if e.errno == errno.EPIPE: 

1511 sys.stdout = t.cast(t.TextIO, PacifyFlushWrapper(sys.stdout)) 

1512 sys.stderr = t.cast(t.TextIO, PacifyFlushWrapper(sys.stderr)) 

1513 sys.exit(1) 

1514 else: 

1515 raise 

1516 except Exit as e: 

1517 if standalone_mode: 

1518 sys.exit(e.exit_code) 

1519 else: 

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

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

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

1523 # would return its result 

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

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

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

1527 # tell the difference between the two 

1528 return e.exit_code 

1529 except Abort: 

1530 if not standalone_mode: 

1531 raise 

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

1533 sys.exit(1) 

1534 

1535 def _main_shell_completion( 

1536 self, 

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

1538 prog_name: str, 

1539 complete_var: str | None = None, 

1540 ) -> None: 

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

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

1543 program is invoked. 

1544 

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

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

1547 the completion instruction. Defaults to 

1548 ``_{PROG_NAME}_COMPLETE``. 

1549 

1550 .. versionchanged:: 8.2.0 

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

1552 """ 

1553 if complete_var is None: 

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

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

1556 

1557 instruction = os.environ.get(complete_var) 

1558 

1559 if not instruction: 

1560 return 

1561 

1562 from .shell_completion import shell_complete 

1563 

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

1565 sys.exit(rv) 

1566 

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

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

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

1570 

1571 

1572class _FakeSubclassCheck(type): 

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

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

1575 

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

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

1578 

1579 

1580class _BaseCommand(Command, metaclass=_FakeSubclassCheck): 

1581 """ 

1582 .. deprecated:: 8.2 

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

1584 """ 

1585 

1586 

1587class Group(Command): 

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

1589 

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

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

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

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

1594 subcommand is not given. 

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

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

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

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

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

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

1601 matched, and so on. 

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

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

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

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

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

1607 ``chain`` is enabled. 

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

1609 

1610 .. versionchanged:: 8.0 

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

1612 

1613 .. versionchanged:: 8.2 

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

1615 """ 

1616 

1617 allow_extra_args = True 

1618 allow_interspersed_args = False 

1619 

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

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

1622 #: subcommands use a custom command class. 

1623 #: 

1624 #: .. versionadded:: 8.0 

1625 command_class: type[Command] | None = None 

1626 

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

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

1629 #: subgroups use a custom group class. 

1630 #: 

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

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

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

1634 #: custom groups. 

1635 #: 

1636 #: .. versionadded:: 8.0 

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

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

1639 

1640 commands: cabc.MutableMapping[str, Command] 

1641 invoke_without_command: bool 

1642 subcommand_metavar: str 

1643 chain: bool 

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

1645 

1646 def __init__( 

1647 self, 

1648 name: str | None = None, 

1649 commands: cabc.MutableMapping[str, Command] 

1650 | cabc.Sequence[Command] 

1651 | None = None, 

1652 invoke_without_command: bool = False, 

1653 no_args_is_help: bool | None = None, 

1654 subcommand_metavar: str | None = None, 

1655 chain: bool = False, 

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

1657 **kwargs: t.Any, 

1658 ) -> None: 

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

1660 

1661 if commands is None: 

1662 commands = {} 

1663 elif isinstance(commands, abc.Sequence): 

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

1665 

1666 #: The registered subcommands by their exported names. 

1667 self.commands = commands 

1668 

1669 if no_args_is_help is None: 

1670 no_args_is_help = not invoke_without_command 

1671 

1672 self.no_args_is_help = no_args_is_help 

1673 self.invoke_without_command = invoke_without_command 

1674 

1675 if subcommand_metavar is None: 

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

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

1678 if chain: 

1679 if invoke_without_command: 

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

1681 else: 

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

1683 elif invoke_without_command: 

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

1685 else: 

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

1687 

1688 self.subcommand_metavar = subcommand_metavar 

1689 self.chain = chain 

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

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

1692 self._result_callback = result_callback 

1693 

1694 if self.chain: 

1695 for param in self.params: 

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

1697 raise RuntimeError( 

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

1699 ) 

1700 

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

1702 info_dict = super().to_info_dict(ctx) 

1703 commands = {} 

1704 

1705 for name in self.list_commands(ctx): 

1706 command = self.get_command(ctx, name) 

1707 

1708 if command is None: 

1709 continue 

1710 

1711 sub_ctx = ctx._make_sub_context(command) 

1712 

1713 with sub_ctx.scope(cleanup=False): 

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

1715 

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

1717 return info_dict 

1718 

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

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

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

1722 """ 

1723 name = name or cmd.name 

1724 if name is None: 

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

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

1727 self.commands[name] = cmd 

1728 

1729 @t.overload 

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

1731 

1732 @t.overload 

1733 def command( 

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

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

1736 

1737 def command( 

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

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

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

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

1742 immediately registers the created command with this group by 

1743 calling :meth:`add_command`. 

1744 

1745 To customize the command class used, set the 

1746 :attr:`command_class` attribute. 

1747 

1748 .. versionchanged:: 8.1 

1749 This decorator can be applied without parentheses. 

1750 

1751 .. versionchanged:: 8.0 

1752 Added the :attr:`command_class` attribute. 

1753 """ 

1754 from .decorators import command 

1755 

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

1757 

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

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

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

1761 ) 

1762 (func,) = args 

1763 args = () 

1764 

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

1766 kwargs["cls"] = self.command_class 

1767 

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

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

1770 self.add_command(cmd) 

1771 return cmd 

1772 

1773 if func is not None: 

1774 return decorator(func) 

1775 

1776 return decorator 

1777 

1778 @t.overload 

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

1780 

1781 @t.overload 

1782 def group( 

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

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

1785 

1786 def group( 

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

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

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

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

1791 immediately registers the created group with this group by 

1792 calling :meth:`add_command`. 

1793 

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

1795 attribute. 

1796 

1797 .. versionchanged:: 8.1 

1798 This decorator can be applied without parentheses. 

1799 

1800 .. versionchanged:: 8.0 

1801 Added the :attr:`group_class` attribute. 

1802 """ 

1803 from .decorators import group 

1804 

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

1806 

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

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

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

1810 ) 

1811 (func,) = args 

1812 args = () 

1813 

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

1815 if self.group_class is type: 

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

1817 else: 

1818 kwargs["cls"] = self.group_class 

1819 

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

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

1822 self.add_command(cmd) 

1823 return cmd 

1824 

1825 if func is not None: 

1826 return decorator(func) 

1827 

1828 return decorator 

1829 

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

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

1832 result callback is already registered this will chain them but 

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

1834 callback is invoked with the return value of the subcommand 

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

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

1837 to the main callback. 

1838 

1839 Example:: 

1840 

1841 @click.group() 

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

1843 def cli(input): 

1844 return 42 

1845 

1846 @cli.result_callback() 

1847 def process_result(result, input): 

1848 return result + input 

1849 

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

1851 callback will be removed. 

1852 

1853 .. versionchanged:: 8.0 

1854 Renamed from ``resultcallback``. 

1855 

1856 .. versionadded:: 3.0 

1857 """ 

1858 

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

1860 old_callback = self._result_callback 

1861 

1862 if old_callback is None or replace: 

1863 self._result_callback = f 

1864 return f 

1865 

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

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

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

1869 

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

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

1872 

1873 return decorator 

1874 

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

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

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

1878 """ 

1879 return self.commands.get(cmd_name) 

1880 

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

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

1883 return sorted(self.commands) 

1884 

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

1886 rv = super().collect_usage_pieces(ctx) 

1887 rv.append(self.subcommand_metavar) 

1888 return rv 

1889 

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

1891 super().format_options(ctx, formatter) 

1892 self.format_commands(ctx, formatter) 

1893 

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

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

1896 after the options. 

1897 """ 

1898 commands = [] 

1899 for subcommand in self.list_commands(ctx): 

1900 cmd = self.get_command(ctx, subcommand) 

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

1902 if cmd is None: 

1903 continue 

1904 if cmd.hidden: 

1905 continue 

1906 

1907 commands.append((subcommand, cmd)) 

1908 

1909 # allow for 3 times the default spacing 

1910 if len(commands): 

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

1912 

1913 rows = [] 

1914 for subcommand, cmd in commands: 

1915 help = cmd.get_short_help_str(limit) 

1916 rows.append((subcommand, help)) 

1917 

1918 if rows: 

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

1920 formatter.write_dl(rows) 

1921 

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

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

1924 raise NoArgsIsHelpError(ctx) 

1925 

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

1927 

1928 if self.chain: 

1929 ctx._protected_args = rest 

1930 ctx.args = [] 

1931 elif rest: 

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

1933 

1934 return ctx.args 

1935 

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

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

1938 if self._result_callback is not None: 

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

1940 return value 

1941 

1942 if not ctx._protected_args: 

1943 if self.invoke_without_command: 

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

1945 # invoked with the group return value for regular 

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

1947 with ctx: 

1948 rv = super().invoke(ctx) 

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

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

1951 

1952 # Fetch args back out 

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

1954 ctx.args = [] 

1955 ctx._protected_args = [] 

1956 

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

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

1959 # name of the command to invoke. 

1960 if not self.chain: 

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

1962 # resources until the result processor has worked. 

1963 with ctx: 

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

1965 assert cmd is not None 

1966 ctx.invoked_subcommand = cmd_name 

1967 super().invoke(ctx) 

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

1969 with sub_ctx: 

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

1971 

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

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

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

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

1976 # but nothing else. 

1977 with ctx: 

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

1979 super().invoke(ctx) 

1980 

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

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

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

1984 contexts = [] 

1985 while args: 

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

1987 assert cmd is not None 

1988 sub_ctx = cmd.make_context( 

1989 cmd_name, 

1990 args, 

1991 parent=ctx, 

1992 allow_extra_args=True, 

1993 allow_interspersed_args=False, 

1994 ) 

1995 contexts.append(sub_ctx) 

1996 args, sub_ctx.args = sub_ctx.args, [] 

1997 

1998 rv = [] 

1999 for sub_ctx in contexts: 

2000 with sub_ctx: 

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

2002 return _process_result(rv) 

2003 

2004 def resolve_command( 

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

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

2007 cmd_name = make_str(args[0]) 

2008 

2009 # Get the command 

2010 cmd = self.get_command(ctx, cmd_name) 

2011 

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

2013 # function available, we try with that one. 

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

2015 cmd_name = ctx.token_normalize_func(cmd_name) 

2016 cmd = self.get_command(ctx, cmd_name) 

2017 

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

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

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

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

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

2023 # place. 

2024 if cmd is None and not ctx.resilient_parsing: 

2025 if _split_opt(cmd_name)[0]: 

2026 self.parse_args(ctx, args) 

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

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

2029 

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

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

2032 at the names of options, subcommands, and chained 

2033 multi-commands. 

2034 

2035 :param ctx: Invocation context for this command. 

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

2037 

2038 .. versionadded:: 8.0 

2039 """ 

2040 from click.shell_completion import CompletionItem 

2041 

2042 results = [ 

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

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

2045 ] 

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

2047 return results 

2048 

2049 

2050class _MultiCommand(Group, metaclass=_FakeSubclassCheck): 

2051 """ 

2052 .. deprecated:: 8.2 

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

2054 """ 

2055 

2056 

2057class CommandCollection(Group): 

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

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

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

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

2062 commands in many groups into this one group. 

2063 

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

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

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

2067 

2068 .. versionchanged:: 8.2 

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

2070 group, then each of its sources. 

2071 """ 

2072 

2073 sources: list[Group] 

2074 

2075 def __init__( 

2076 self, 

2077 name: str | None = None, 

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

2079 **kwargs: t.Any, 

2080 ) -> None: 

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

2082 #: The list of registered groups. 

2083 self.sources = sources or [] 

2084 

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

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

2087 self.sources.append(group) 

2088 

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

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

2091 

2092 if rv is not None: 

2093 return rv 

2094 

2095 for source in self.sources: 

2096 rv = source.get_command(ctx, cmd_name) 

2097 

2098 if rv is not None: 

2099 if self.chain: 

2100 _check_nested_chain(self, cmd_name, rv) 

2101 

2102 return rv 

2103 

2104 return None 

2105 

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

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

2108 

2109 for source in self.sources: 

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

2111 

2112 return sorted(rv) 

2113 

2114 

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

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

2117 error, or return an iterator over the value. 

2118 """ 

2119 if isinstance(value, str): 

2120 raise TypeError 

2121 

2122 return iter(value) 

2123 

2124 

2125class Parameter(ABC): 

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

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

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

2129 intentionally not finalized. 

2130 

2131 Some settings are supported by both options and arguments. 

2132 

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

2134 argument. This is a list of flags or argument 

2135 names. 

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

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

2138 automatically if supported. 

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

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

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

2142 without any arguments. 

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

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

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

2146 including prompts. 

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

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

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

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

2151 parameters are collected. 

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

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

2154 to the command callback and stored on the context, 

2155 otherwise it's skipped. 

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

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

2158 order of processing. 

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

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

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

2162 :param shell_complete: A function that returns custom shell 

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

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

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

2166 strings. 

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

2168 indicating that the argument is deprecated and highlights 

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

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

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

2172 

2173 .. versionchanged:: 8.2.0 

2174 Introduction of ``deprecated``. 

2175 

2176 .. versionchanged:: 8.2 

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

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

2179 

2180 .. versionchanged:: 8.2 

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

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

2183 

2184 .. versionchanged:: 8.0 

2185 ``process_value`` validates required parameters and bounded 

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

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

2188 ``full_process_value`` is removed. 

2189 

2190 .. versionchanged:: 8.0 

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

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

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

2194 new requirements. 

2195 

2196 .. versionchanged:: 8.0 

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

2198 tuples. 

2199 

2200 .. versionchanged:: 8.0 

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

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

2203 default to ``()``. 

2204 

2205 .. versionchanged:: 7.1 

2206 Empty environment variables are ignored rather than taking the 

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

2208 variables if they can't unset them. 

2209 

2210 .. versionchanged:: 2.0 

2211 Changed signature for parameter callback to also be passed the 

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

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

2214 """ 

2215 

2216 param_type_name = "parameter" 

2217 

2218 name: str 

2219 opts: list[str] 

2220 secondary_opts: list[str] 

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

2222 required: bool 

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

2224 nargs: int 

2225 multiple: bool 

2226 expose_value: bool 

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

2228 _default_explicit: bool 

2229 is_eager: bool 

2230 metavar: str | None 

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

2232 _custom_shell_complete: ( 

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

2234 ) 

2235 deprecated: bool | str 

2236 

2237 def __init__( 

2238 self, 

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

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

2241 required: bool = False, 

2242 # XXX The default historically embed two concepts: 

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

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

2245 # self.name, like flag options), 

2246 # - and the actual value of the default. 

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

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

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

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

2251 # Parameter.is_default and Parameter.default_value. 

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

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

2254 nargs: int | None = None, 

2255 multiple: bool = False, 

2256 metavar: str | None = None, 

2257 expose_value: bool = True, 

2258 is_eager: bool = False, 

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

2260 shell_complete: t.Callable[ 

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

2262 ] 

2263 | None = None, 

2264 deprecated: bool | str = False, 

2265 ) -> None: 

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

2267 param_decls or (), expose_value 

2268 ) 

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

2270 

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

2272 # information available. 

2273 if nargs is None: 

2274 if self.type.is_composite: 

2275 nargs = self.type.arity 

2276 else: 

2277 nargs = 1 

2278 

2279 self.required = required 

2280 self.callback = callback 

2281 self.nargs = nargs 

2282 self.multiple = multiple 

2283 self.expose_value = expose_value 

2284 self.default = default 

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

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

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

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

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

2290 self._default_explicit = default is not UNSET 

2291 self.is_eager = is_eager 

2292 self.metavar = metavar 

2293 self.envvar = envvar 

2294 self._custom_shell_complete = shell_complete 

2295 self.deprecated = deprecated 

2296 

2297 if __debug__: 

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

2299 raise ValueError( 

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

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

2302 ) 

2303 

2304 if required and deprecated: 

2305 raise ValueError( 

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

2307 "is deprecated and still required. A deprecated " 

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

2309 ) 

2310 

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

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

2313 user-facing documentation. 

2314 

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

2316 CLI structure. 

2317 

2318 .. versionchanged:: 8.3.0 

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

2320 

2321 .. versionadded:: 8.0 

2322 """ 

2323 return { 

2324 "name": self.name, 

2325 "param_type_name": self.param_type_name, 

2326 "opts": self.opts, 

2327 "secondary_opts": self.secondary_opts, 

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

2329 "required": self.required, 

2330 "nargs": self.nargs, 

2331 "multiple": self.multiple, 

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

2333 # make it an implementation detail. And because ``to_info_dict`` has been 

2334 # designed for documentation purposes, we return ``None`` instead. 

2335 "default": self.default if self.default is not UNSET else None, 

2336 "envvar": self.envvar, 

2337 } 

2338 

2339 def __repr__(self) -> str: 

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

2341 

2342 @abstractmethod 

2343 def _parse_decls( 

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

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

2346 

2347 @property 

2348 def human_readable_name(self) -> str: 

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

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

2351 """ 

2352 return self.name 

2353 

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

2355 if self.metavar is not None: 

2356 return self.metavar 

2357 

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

2359 

2360 if metavar is None: 

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

2362 

2363 if self.nargs != 1: 

2364 metavar += "..." 

2365 

2366 return metavar 

2367 

2368 @t.overload 

2369 def get_default( 

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

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

2372 

2373 @t.overload 

2374 def get_default( 

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

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

2377 

2378 def get_default( 

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

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

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

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

2383 

2384 :param ctx: Current context. 

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

2386 return the callable instead. 

2387 

2388 .. versionchanged:: 8.0.2 

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

2390 

2391 .. versionchanged:: 8.0.1 

2392 Type casting can fail in resilient parsing mode. Invalid 

2393 defaults will not prevent showing help text. 

2394 

2395 .. versionchanged:: 8.0 

2396 Looks at ``ctx.default_map`` first. 

2397 

2398 .. versionchanged:: 8.0 

2399 Added the ``call`` parameter. 

2400 """ 

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

2402 

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

2404 value = self.default 

2405 

2406 if call and callable(value): 

2407 value = value() 

2408 

2409 return value 

2410 

2411 @abstractmethod 

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

2413 

2414 def consume_value( 

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

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

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

2418 

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

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

2421 default value. In that order of precedence. 

2422 

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

2424 

2425 :meta private: 

2426 """ 

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

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

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

2430 # parser, otherwise it left unset by default. 

2431 source = ( 

2432 ParameterSource.COMMANDLINE 

2433 if value is not UNSET 

2434 else ParameterSource.DEFAULT 

2435 ) 

2436 

2437 if value is UNSET: 

2438 envvar_value = self.value_from_envvar(ctx) 

2439 if envvar_value is not None: 

2440 value = envvar_value 

2441 source = ParameterSource.ENVIRONMENT 

2442 

2443 if value is UNSET: 

2444 default_map_value = ctx.lookup_default(self.name) 

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

2446 value = default_map_value 

2447 source = ParameterSource.DEFAULT_MAP 

2448 

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

2450 # parameters, matching value_from_envvar behavior. 

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

2452 value = self.type.split_envvar_value(value) 

2453 

2454 if value is UNSET: 

2455 default_value = self.get_default(ctx) 

2456 if default_value is not UNSET: 

2457 value = default_value 

2458 source = ParameterSource.DEFAULT 

2459 

2460 return value, source 

2461 

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

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

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

2465 """ 

2466 if value is None: 

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

2468 return () 

2469 else: 

2470 return value 

2471 

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

2473 try: 

2474 return _check_iter(value) 

2475 except TypeError: 

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

2477 # the parser should construct an iterable when parsing 

2478 # the command line. 

2479 raise BadParameter( 

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

2481 ) from None 

2482 

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

2484 

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

2486 

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

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

2489 

2490 elif self.nargs == -1: 

2491 

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

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

2494 

2495 else: # nargs > 1 

2496 

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

2498 value = tuple(check_iter(value)) 

2499 

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

2501 raise BadParameter( 

2502 ngettext( 

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

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

2505 len(value), 

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

2507 ctx=ctx, 

2508 param=self, 

2509 ) 

2510 

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

2512 

2513 if self.multiple: 

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

2515 

2516 return convert(value) 

2517 

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

2519 """A value is considered missing if: 

2520 

2521 - it is :attr:`UNSET`, 

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

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

2524 set). 

2525 

2526 :meta private: 

2527 """ 

2528 if value is UNSET: 

2529 return True 

2530 

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

2532 return True 

2533 

2534 return False 

2535 

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

2537 """Process the value of this parameter: 

2538 

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

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

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

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

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

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

2545 the :attr:`UNSET` sentinel. 

2546 

2547 :meta private: 

2548 """ 

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

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

2551 # 

2552 # Refs: 

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

2554 if value is UNSET: 

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

2556 value = () 

2557 else: 

2558 value = self.type_cast_value(ctx, value) 

2559 

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

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

2562 

2563 if self.callback is not None: 

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

2565 # to None. 

2566 if value is UNSET: 

2567 value = None 

2568 

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

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

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

2572 if not unset_keys: 

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

2574 

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

2576 # to hide UNSET values as None. 

2577 # 

2578 # Refs: 

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

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

2581 else: 

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

2583 # context is temporarily modified. 

2584 with ctx: 

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

2586 ctx.params.update(unset_keys) 

2587 # Feed these fake context parameters to the callback. 

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

2589 # Restore the UNSET values in the context parameters. 

2590 ctx.params.update( 

2591 { 

2592 k: UNSET 

2593 for k in unset_keys 

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

2595 # the callback modified other parameters. 

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

2597 } 

2598 ) 

2599 

2600 return value 

2601 

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

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

2604 parameter. 

2605 

2606 Environment variables values are `always returned as strings 

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

2608 

2609 This method returns ``None`` if: 

2610 

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

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

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

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

2615 

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

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

2618 

2619 .. caution:: 

2620 

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

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

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

2624 

2625 :meta private: 

2626 """ 

2627 if not self.envvar: 

2628 return None 

2629 

2630 if isinstance(self.envvar, str): 

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

2632 

2633 if rv: 

2634 return rv 

2635 else: 

2636 for envvar in self.envvar: 

2637 rv = os.environ.get(envvar) 

2638 

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

2640 if rv: 

2641 return rv 

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

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

2644 

2645 return None 

2646 

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

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

2649 

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

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

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

2653 

2654 :meta private: 

2655 """ 

2656 rv = self.resolve_envvar_value(ctx) 

2657 

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

2659 return self.type.split_envvar_value(rv) 

2660 

2661 return rv 

2662 

2663 def handle_parse_result( 

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

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

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

2667 

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

2669 comes from. 

2670 

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

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

2673 a default). 

2674 

2675 :meta private: 

2676 """ 

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

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

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

2680 # the slot (if any). 

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

2682 existing_source = ctx.get_parameter_source(self.name) 

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

2684 

2685 with augment_usage_errors(ctx, param=self): 

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

2687 

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

2689 # conversion can inspect it. Restored after arbitration if this 

2690 # option loses a feature-switch group. 

2691 ctx.set_parameter_source(self.name, source) 

2692 

2693 # Display a deprecation warning if necessary. 

2694 if ( 

2695 self.deprecated 

2696 and value is not UNSET 

2697 and source < ParameterSource.DEFAULT_MAP 

2698 ): 

2699 message = _( 

2700 "DeprecationWarning: The {param_type} {name!r} is deprecated." 

2701 "{extra_message}" 

2702 ).format( 

2703 param_type=self.param_type_name, 

2704 name=self.human_readable_name, 

2705 extra_message=_format_deprecated_suffix(self.deprecated), 

2706 ) 

2707 echo(style(message, fg="red"), err=True) 

2708 

2709 # Process the value through the parameter's type. 

2710 try: 

2711 value = self.process_value(ctx, value) 

2712 except Exception: 

2713 if not ctx.resilient_parsing: 

2714 raise 

2715 # In resilient parsing mode, we do not want to fail the command if the 

2716 # value is incompatible with the parameter type, so we reset the value 

2717 # to UNSET, which will be interpreted as a missing value. 

2718 value = UNSET 

2719 

2720 # Arbitrate the slot when several parameters target the same variable 

2721 # name (feature-switch groups). See: https://github.com/pallets/click/issues/3403 

2722 slot_empty = existing_value is UNSET 

2723 more_explicit = existing_source is not None and source < existing_source 

2724 same_source = existing_source is not None and source == existing_source 

2725 auto_would_downgrade_explicit = ( 

2726 same_source 

2727 and source == ParameterSource.DEFAULT 

2728 and existing_default_explicit 

2729 and not self._default_explicit 

2730 ) 

2731 is_winner = ( 

2732 slot_empty 

2733 or more_explicit 

2734 or (same_source and not auto_would_downgrade_explicit) 

2735 ) 

2736 

2737 if is_winner: 

2738 if self.expose_value: 

2739 ctx.params[self.name] = value 

2740 ctx._param_default_explicit[self.name] = self._default_explicit 

2741 elif existing_source is not None: 

2742 # Lost arbitration; restore the winning option's source. 

2743 ctx.set_parameter_source(self.name, existing_source) 

2744 # else: ctx.params[self.name] was populated by code that bypassed 

2745 # handle_parse_result (from another option's callback for example). Keep 

2746 # the provisional source recorded before process_value so downstream 

2747 # lookups don't return ``None``. 

2748 

2749 return value, args 

2750 

2751 def get_help_record(self, ctx: Context) -> tuple[str, str] | None: 

2752 return None 

2753 

2754 def get_usage_pieces(self, ctx: Context) -> list[str]: 

2755 return [] 

2756 

2757 def get_error_hint(self, ctx: Context | None) -> str: 

2758 """Get a stringified version of the param for use in error messages to 

2759 indicate which param caused the error. 

2760 

2761 .. versionchanged:: 8.4.0 

2762 ``ctx`` can be ``None``. 

2763 """ 

2764 hint_list = self.opts or [self.human_readable_name] 

2765 return " / ".join(f"'{x}'" for x in hint_list) 

2766 

2767 def shell_complete(self, ctx: Context, incomplete: str) -> list[CompletionItem]: 

2768 """Return a list of completions for the incomplete value. If a 

2769 ``shell_complete`` function was given during init, it is used. 

2770 Otherwise, the :attr:`type` 

2771 :meth:`~click.types.ParamType[t.Any].shell_complete` function is used. 

2772 

2773 :param ctx: Invocation context for this command. 

2774 :param incomplete: Value being completed. May be empty. 

2775 

2776 .. versionadded:: 8.0 

2777 """ 

2778 if self._custom_shell_complete is not None: 

2779 results = self._custom_shell_complete(ctx, self, incomplete) 

2780 

2781 if results and isinstance(results[0], str): 

2782 from click.shell_completion import CompletionItem 

2783 

2784 results = [CompletionItem(c) for c in results] 

2785 

2786 return t.cast("list[CompletionItem]", results) 

2787 

2788 return self.type.shell_complete(ctx, self, incomplete) 

2789 

2790 

2791class Option(Parameter): 

2792 """Options are usually optional values on the command line and 

2793 have some extra features that arguments don't have. 

2794 

2795 All other parameters are passed onwards to the parameter constructor. 

2796 

2797 :param show_default: Show the default value for this option in its 

2798 help text. Values are not shown by default, unless 

2799 :attr:`Context.show_default` is ``True``. If this value is a 

2800 string, it shows that string in parentheses instead of the 

2801 actual value. This is particularly useful for dynamic options. 

2802 For single option boolean flags, the default remains hidden if 

2803 its value is ``False``. 

2804 :param show_envvar: Controls if an environment variable should be 

2805 shown on the help page and error messages. 

2806 Normally, environment variables are not shown. 

2807 :param prompt: If set to ``True`` or a non empty string then the 

2808 user will be prompted for input. If set to ``True`` the prompt 

2809 will be the option name capitalized. A deprecated option cannot be 

2810 prompted. 

2811 :param confirmation_prompt: Prompt a second time to confirm the 

2812 value if it was prompted for. Can be set to a string instead of 

2813 ``True`` to customize the message. 

2814 :param prompt_required: If set to ``False``, the user will be 

2815 prompted for input only when the option was specified as a flag 

2816 without a value. 

2817 :param hide_input: If this is ``True`` then the input on the prompt 

2818 will be hidden from the user. This is useful for password input. 

2819 :param is_flag: forces this option to act as a flag. The default is 

2820 auto detection. 

2821 :param flag_value: which value should be used for this flag if it's 

2822 enabled. This is set to a boolean automatically if 

2823 the option string contains a slash to mark two options. 

2824 :param multiple: if this is set to `True` then the argument is accepted 

2825 multiple times and recorded. This is similar to ``nargs`` 

2826 in how it works but supports arbitrary number of 

2827 arguments. 

2828 :param count: this flag makes an option increment an integer. 

2829 :param allow_from_autoenv: if this is enabled then the value of this 

2830 parameter will be pulled from an environment 

2831 variable in case a prefix is defined on the 

2832 context. 

2833 :param help: the help string. 

2834 :param hidden: hide this option from help outputs. 

2835 :param attrs: Other command arguments described in :class:`Parameter`. 

2836 

2837 .. versionchanged:: 8.4.0 

2838 Non-basic ``flag_value`` types (not ``str``, ``int``, ``float``, or 

2839 ``bool``) are passed through unchanged instead of being stringified. 

2840 Previously, ``type=click.UNPROCESSED`` was required to preserve them. 

2841 

2842 .. versionchanged:: 8.2 

2843 ``envvar`` used with ``flag_value`` will always use the ``flag_value``, 

2844 previously it would use the value of the environment variable. 

2845 

2846 .. versionchanged:: 8.1 

2847 Help text indentation is cleaned here instead of only in the 

2848 ``@option`` decorator. 

2849 

2850 .. versionchanged:: 8.1 

2851 The ``show_default`` parameter overrides 

2852 ``Context.show_default``. 

2853 

2854 .. versionchanged:: 8.1 

2855 The default of a single option boolean flag is not shown if the 

2856 default value is ``False``. 

2857 

2858 .. versionchanged:: 8.0.1 

2859 ``type`` is detected from ``flag_value`` if given, for basic Python 

2860 types (``str``, ``int``, ``float``, ``bool``). 

2861 """ 

2862 

2863 param_type_name = "option" 

2864 

2865 prompt: str | None 

2866 confirmation_prompt: bool | str 

2867 prompt_required: bool 

2868 hide_input: bool 

2869 hidden: bool 

2870 

2871 _flag_needs_value: bool 

2872 is_flag: bool 

2873 is_bool_flag: bool 

2874 flag_value: t.Any 

2875 

2876 count: bool 

2877 allow_from_autoenv: bool 

2878 help: str | None 

2879 show_default: bool | str | None 

2880 show_choices: bool 

2881 show_envvar: bool 

2882 

2883 def __init__( 

2884 self, 

2885 param_decls: cabc.Sequence[str] | None = None, 

2886 show_default: bool | str | None = None, 

2887 prompt: bool | str = False, 

2888 confirmation_prompt: bool | str = False, 

2889 prompt_required: bool = True, 

2890 hide_input: bool = False, 

2891 is_flag: bool | None = None, 

2892 flag_value: t.Any = UNSET, 

2893 multiple: bool = False, 

2894 count: bool = False, 

2895 allow_from_autoenv: bool = True, 

2896 type: types.ParamType[t.Any] | t.Any | None = None, 

2897 help: str | None = None, 

2898 hidden: bool = False, 

2899 show_choices: bool = True, 

2900 show_envvar: bool = False, 

2901 deprecated: bool | str = False, 

2902 **attrs: t.Any, 

2903 ) -> None: 

2904 if help: 

2905 help = inspect.cleandoc(help) 

2906 

2907 super().__init__( 

2908 param_decls, type=type, multiple=multiple, deprecated=deprecated, **attrs 

2909 ) 

2910 

2911 if prompt is True: 

2912 if not self.name: 

2913 raise TypeError("'name' is required with 'prompt=True'.") 

2914 

2915 prompt_text = self.name.replace("_", " ").capitalize() 

2916 elif prompt is False: 

2917 prompt_text = None 

2918 else: 

2919 prompt_text = prompt 

2920 

2921 if deprecated: 

2922 label = _format_deprecated_label(deprecated) 

2923 help = f"{help} {label}" if help else label 

2924 

2925 self.prompt = prompt_text 

2926 self.confirmation_prompt = confirmation_prompt 

2927 self.prompt_required = prompt_required 

2928 self.hide_input = hide_input 

2929 self.hidden = hidden 

2930 

2931 # The _flag_needs_value property tells the parser that this option is a flag 

2932 # that cannot be used standalone and needs a value. With this information, the 

2933 # parser can determine whether to consider the next user-provided argument in 

2934 # the CLI as a value for this flag or as a new option. 

2935 # If prompt is enabled but not required, then it opens the possibility for the 

2936 # option to gets its value from the user. 

2937 self._flag_needs_value = self.prompt is not None and not self.prompt_required 

2938 

2939 # Auto-detect if this is a flag or not. 

2940 if is_flag is None: 

2941 # Implicitly a flag because flag_value was set. 

2942 if flag_value is not UNSET: 

2943 is_flag = True 

2944 # Not a flag, but when used as a flag it shows a prompt. 

2945 elif self._flag_needs_value: 

2946 is_flag = False 

2947 # Implicitly a flag because secondary options names were given. 

2948 elif self.secondary_opts: 

2949 is_flag = True 

2950 

2951 # The option is explicitly not a flag, but to determine whether or not it needs 

2952 # value, we need to check if `flag_value` or `default` was set. Either one is 

2953 # sufficient. 

2954 # Ref: https://github.com/pallets/click/issues/3084 

2955 elif is_flag is False and not self._flag_needs_value: 

2956 self._flag_needs_value = flag_value is not UNSET or self.default is UNSET 

2957 

2958 if is_flag: 

2959 # Set missing default for flags if not explicitly required or prompted. 

2960 if self.default is UNSET and not self.required and not self.prompt: 

2961 if multiple: 

2962 self.default = () 

2963 

2964 # Auto-detect the type of the flag based on the flag_value. 

2965 if type is None: 

2966 # A flag without a flag_value is a boolean flag. 

2967 if flag_value is UNSET: 

2968 self.type: types.ParamType[t.Any] = types.BoolParamType() 

2969 # If the flag value is a boolean, use BoolParamType. 

2970 elif isinstance(flag_value, bool): 

2971 self.type = types.BoolParamType() 

2972 # Otherwise, guess the type from the flag value. 

2973 else: 

2974 guessed = types.convert_type(None, flag_value) 

2975 if ( 

2976 isinstance(guessed, types.StringParamType) 

2977 and not isinstance(flag_value, str) 

2978 and flag_value is not None 

2979 ): 

2980 # The flag_value type couldn't be auto-detected 

2981 # (not str, int, float, or bool). Since flag_value 

2982 # is a programmer-provided Python object, not CLI 

2983 # input, pass it through unchanged instead of 

2984 # stringifying it. 

2985 self.type = types.UNPROCESSED 

2986 else: 

2987 self.type = guessed 

2988 

2989 self.is_flag = bool(is_flag) 

2990 self.is_bool_flag = self.is_flag and isinstance(self.type, types.BoolParamType) 

2991 self.flag_value = flag_value 

2992 

2993 # Set boolean flag default to False if unset and not required. 

2994 if self.is_bool_flag: 

2995 if self.default is UNSET and not self.required: 

2996 self.default = False 

2997 

2998 # The alignment of default to the flag_value is resolved lazily in 

2999 # get_default() to prevent callable flag_values (like classes) from 

3000 # being instantiated. Refs: 

3001 # https://github.com/pallets/click/issues/3121 

3002 # https://github.com/pallets/click/issues/3024#issuecomment-3146199461 

3003 # https://github.com/pallets/click/pull/3030/commits/06847da 

3004 

3005 # Set the default flag_value if it is not set. 

3006 if self.flag_value is UNSET: 

3007 if self.is_flag: 

3008 self.flag_value = True 

3009 else: 

3010 self.flag_value = None 

3011 

3012 # Counting. 

3013 self.count = count 

3014 if count: 

3015 if type is None: 

3016 self.type = types.IntRange(min=0) 

3017 if self.default is UNSET: 

3018 self.default = 0 

3019 

3020 self.allow_from_autoenv = allow_from_autoenv 

3021 self.help = help 

3022 self.show_default = show_default 

3023 self.show_choices = show_choices 

3024 self.show_envvar = show_envvar 

3025 

3026 if __debug__: 

3027 if deprecated and prompt: 

3028 raise ValueError("`deprecated` options cannot use `prompt`.") 

3029 

3030 if self.nargs == -1: 

3031 raise TypeError("nargs=-1 is not supported for options.") 

3032 

3033 if not self.is_bool_flag and self.secondary_opts: 

3034 raise TypeError("Secondary flag is not valid for non-boolean flag.") 

3035 

3036 if self.is_bool_flag and self.hide_input and self.prompt is not None: 

3037 raise TypeError( 

3038 "'prompt' with 'hide_input' is not valid for boolean flag." 

3039 ) 

3040 

3041 if self.count: 

3042 if self.multiple: 

3043 raise TypeError("'count' is not valid with 'multiple'.") 

3044 

3045 if self.is_flag: 

3046 raise TypeError("'count' is not valid with 'is_flag'.") 

3047 

3048 def to_info_dict(self) -> dict[str, t.Any]: 

3049 """ 

3050 .. versionchanged:: 8.3.0 

3051 Returns ``None`` for the :attr:`flag_value` if it was not set. 

3052 """ 

3053 info_dict = super().to_info_dict() 

3054 info_dict.update( 

3055 help=self.help, 

3056 prompt=self.prompt, 

3057 is_flag=self.is_flag, 

3058 # We explicitly hide the :attr:`UNSET` value to the user, as we choose to 

3059 # make it an implementation detail. And because ``to_info_dict`` has been 

3060 # designed for documentation purposes, we return ``None`` instead. 

3061 flag_value=self.flag_value if self.flag_value is not UNSET else None, 

3062 count=self.count, 

3063 hidden=self.hidden, 

3064 ) 

3065 return info_dict 

3066 

3067 def get_default( 

3068 self, ctx: Context, call: bool = True 

3069 ) -> t.Any | t.Callable[[], t.Any] | None: 

3070 """Return the default value for this option. 

3071 

3072 For non-boolean flag options, ``default=True`` is treated as a sentinel 

3073 meaning "activate this flag by default" and is resolved to 

3074 :attr:`flag_value`. For example, with ``--upper/--lower`` feature 

3075 switches where ``flag_value="upper"`` and ``default=True``, the default 

3076 resolves to ``"upper"``. 

3077 

3078 .. caution:: 

3079 This substitution only applies to non-boolean flags 

3080 (:attr:`is_bool_flag` is ``False``). For boolean flags, ``True`` is 

3081 a legitimate Python value and ``default=True`` is returned as-is. 

3082 

3083 .. versionchanged:: 8.3.3 

3084 ``default=True`` is no longer substituted with ``flag_value`` for 

3085 boolean flags, fixing negative boolean flags like 

3086 ``flag_value=False, default=True``. 

3087 """ 

3088 value = super().get_default(ctx, call=False) 

3089 

3090 # Resolve default=True to flag_value lazily (here instead of 

3091 # __init__) to prevent callable flag_values (like classes) from 

3092 # being instantiated by the callable check below. 

3093 if value is True and self.is_flag and not self.is_bool_flag: 

3094 value = self.flag_value 

3095 elif call and callable(value): 

3096 value = value() 

3097 

3098 return value 

3099 

3100 def get_error_hint(self, ctx: Context | None) -> str: 

3101 result = super().get_error_hint(ctx) 

3102 if self.show_envvar and self.envvar is not None: 

3103 result += f" (env var: '{self.envvar}')" 

3104 return result 

3105 

3106 def _parse_decls( 

3107 self, decls: cabc.Sequence[str], expose_value: bool 

3108 ) -> tuple[str, list[str], list[str]]: 

3109 opts = [] 

3110 secondary_opts = [] 

3111 name = None 

3112 possible_names = [] 

3113 

3114 for decl in decls: 

3115 if decl.isidentifier(): 

3116 if name is not None: 

3117 raise TypeError(_("Name '{name}' defined twice").format(name=name)) 

3118 name = decl 

3119 else: 

3120 split_char = ";" if decl[:1] == "/" else "/" 

3121 if split_char in decl: 

3122 first, second = decl.split(split_char, 1) 

3123 first = first.rstrip() 

3124 if first: 

3125 possible_names.append(_split_opt(first)) 

3126 opts.append(first) 

3127 second = second.lstrip() 

3128 if second: 

3129 secondary_opts.append(second.lstrip()) 

3130 if first == second: 

3131 raise ValueError( 

3132 _( 

3133 "Boolean option {decl!r} cannot use the" 

3134 " same flag for true/false." 

3135 ).format(decl=decl) 

3136 ) 

3137 else: 

3138 possible_names.append(_split_opt(decl)) 

3139 opts.append(decl) 

3140 

3141 if name is None and possible_names: 

3142 possible_names.sort(key=lambda x: -len(x[0])) # group long options first 

3143 name = possible_names[0][1].replace("-", "_").lower() 

3144 if not name.isidentifier(): 

3145 name = None 

3146 

3147 if name is None: 

3148 if not expose_value: 

3149 return "", opts, secondary_opts 

3150 raise TypeError( 

3151 _( 

3152 "Could not determine name for option with declarations {decls!r}" 

3153 ).format(decls=decls) 

3154 ) 

3155 

3156 if not opts and not secondary_opts: 

3157 raise TypeError( 

3158 _( 

3159 "No options defined but a name was passed ({name})." 

3160 " Did you mean to declare an argument instead? Did" 

3161 " you mean to pass '--{name}'?" 

3162 ).format(name=name) 

3163 ) 

3164 

3165 return name, opts, secondary_opts 

3166 

3167 def add_to_parser(self, parser: _OptionParser, ctx: Context) -> None: 

3168 if self.multiple: 

3169 action = "append" 

3170 elif self.count: 

3171 action = "count" 

3172 else: 

3173 action = "store" 

3174 

3175 if self.is_flag: 

3176 action = f"{action}_const" 

3177 

3178 if self.is_bool_flag and self.secondary_opts: 

3179 parser.add_option( 

3180 obj=self, opts=self.opts, dest=self.name, action=action, const=True 

3181 ) 

3182 parser.add_option( 

3183 obj=self, 

3184 opts=self.secondary_opts, 

3185 dest=self.name, 

3186 action=action, 

3187 const=False, 

3188 ) 

3189 else: 

3190 parser.add_option( 

3191 obj=self, 

3192 opts=self.opts, 

3193 dest=self.name, 

3194 action=action, 

3195 const=self.flag_value, 

3196 ) 

3197 else: 

3198 parser.add_option( 

3199 obj=self, 

3200 opts=self.opts, 

3201 dest=self.name, 

3202 action=action, 

3203 nargs=self.nargs, 

3204 ) 

3205 

3206 def get_help_record(self, ctx: Context) -> tuple[str, str] | None: 

3207 if self.hidden: 

3208 return None 

3209 

3210 any_prefix_is_slash = False 

3211 

3212 def _write_opts(opts: cabc.Sequence[str]) -> str: 

3213 nonlocal any_prefix_is_slash 

3214 

3215 rv, any_slashes = join_options(opts) 

3216 

3217 if any_slashes: 

3218 any_prefix_is_slash = True 

3219 

3220 if not self.is_flag and not self.count: 

3221 rv += f" {self.make_metavar(ctx=ctx)}" 

3222 

3223 return rv 

3224 

3225 rv = [_write_opts(self.opts)] 

3226 

3227 if self.secondary_opts: 

3228 rv.append(_write_opts(self.secondary_opts)) 

3229 

3230 help = self.help or "" 

3231 

3232 extra = self.get_help_extra(ctx) 

3233 extra_items = [] 

3234 if "envvars" in extra: 

3235 extra_items.append( 

3236 _("env var: {var}").format(var=", ".join(extra["envvars"])) 

3237 ) 

3238 if "default" in extra: 

3239 extra_items.append(_("default: {default}").format(default=extra["default"])) 

3240 if "range" in extra: 

3241 extra_items.append(extra["range"]) 

3242 if "required" in extra: 

3243 extra_items.append(_(extra["required"])) 

3244 

3245 if extra_items: 

3246 extra_str = "; ".join(extra_items) 

3247 help = f"{help} [{extra_str}]" if help else f"[{extra_str}]" 

3248 

3249 return ("; " if any_prefix_is_slash else " / ").join(rv), help 

3250 

3251 def get_help_extra(self, ctx: Context) -> types.OptionHelpExtra: 

3252 extra: types.OptionHelpExtra = {} 

3253 

3254 if self.show_envvar: 

3255 envvar = self.envvar 

3256 

3257 if envvar is None: 

3258 if ( 

3259 self.allow_from_autoenv 

3260 and ctx.auto_envvar_prefix is not None 

3261 and self.name 

3262 ): 

3263 envvar = f"{ctx.auto_envvar_prefix}_{self.name.upper()}" 

3264 

3265 if envvar is not None: 

3266 if isinstance(envvar, str): 

3267 extra["envvars"] = (envvar,) 

3268 else: 

3269 extra["envvars"] = tuple(str(d) for d in envvar) 

3270 

3271 # Temporarily enable resilient parsing to avoid type casting 

3272 # failing for the default. Might be possible to extend this to 

3273 # help formatting in general. 

3274 resilient = ctx.resilient_parsing 

3275 ctx.resilient_parsing = True 

3276 

3277 try: 

3278 default_value = self.get_default(ctx, call=False) 

3279 finally: 

3280 ctx.resilient_parsing = resilient 

3281 

3282 show_default = False 

3283 show_default_is_str = False 

3284 

3285 if self.show_default is not None: 

3286 if isinstance(self.show_default, str): 

3287 show_default_is_str = show_default = True 

3288 else: 

3289 show_default = self.show_default 

3290 elif ctx.show_default is not None: 

3291 show_default = ctx.show_default 

3292 

3293 if show_default_is_str or ( 

3294 show_default and (default_value not in (None, UNSET)) 

3295 ): 

3296 if show_default_is_str: 

3297 default_string = f"({self.show_default})" 

3298 elif isinstance(default_value, (list, tuple)): 

3299 default_string = ", ".join(str(d) for d in default_value) 

3300 elif isinstance(default_value, enum.Enum): 

3301 default_string = default_value.name 

3302 elif inspect.isfunction(default_value): 

3303 default_string = _("(dynamic)") 

3304 elif self.is_bool_flag and self.secondary_opts: 

3305 # For boolean flags that have distinct True/False opts, 

3306 # use the opt without prefix instead of the value. 

3307 default_string = _split_opt( 

3308 (self.opts if default_value else self.secondary_opts)[0] 

3309 )[1] 

3310 elif self.is_bool_flag and not self.secondary_opts and not default_value: 

3311 default_string = "" 

3312 elif isinstance(default_value, str) and default_value == "": 

3313 default_string = '""' 

3314 else: 

3315 default_string = str(default_value) 

3316 

3317 if default_string: 

3318 extra["default"] = default_string 

3319 

3320 if ( 

3321 isinstance(self.type, types._NumberRangeBase) 

3322 # skip count with default range type 

3323 and not (self.count and self.type.min == 0 and self.type.max is None) 

3324 ): 

3325 range_str = self.type._describe_range() 

3326 

3327 if range_str: 

3328 extra["range"] = range_str 

3329 

3330 if self.required: 

3331 extra["required"] = "required" 

3332 

3333 return extra 

3334 

3335 def prompt_for_value(self, ctx: Context) -> t.Any: 

3336 """This is an alternative flow that can be activated in the full 

3337 value processing if a value does not exist. It will prompt the 

3338 user until a valid value exists and then returns the processed 

3339 value as result. 

3340 """ 

3341 assert self.prompt is not None 

3342 

3343 # Calculate the default before prompting anything to lock in the value before 

3344 # attempting any user interaction. 

3345 default = self.get_default(ctx) 

3346 

3347 # A boolean flag can use a simplified [y/n] confirmation prompt. 

3348 if self.is_bool_flag: 

3349 # If we have no boolean default, we force the user to explicitly provide 

3350 # one. 

3351 if default in (UNSET, None): 

3352 default = None 

3353 # Nothing prevent you to declare an option that is simultaneously: 

3354 # 1) auto-detected as a boolean flag, 

3355 # 2) allowed to prompt, and 

3356 # 3) still declare a non-boolean default. 

3357 # This forced casting into a boolean is necessary to align any non-boolean 

3358 # default to the prompt, which is going to be a [y/n]-style confirmation 

3359 # because the option is still a boolean flag. That way, instead of [y/n], 

3360 # we get [Y/n] or [y/N] depending on the truthy value of the default. 

3361 # Refs: https://github.com/pallets/click/pull/3030#discussion_r2289180249 

3362 else: 

3363 default = bool(default) 

3364 return confirm(self.prompt, default) 

3365 

3366 # If show_default is given, provide this to `prompt` as well, 

3367 # otherwise we use `prompt`'s default behavior 

3368 prompt_kwargs: t.Any = {} 

3369 if self.show_default is not None: 

3370 prompt_kwargs["show_default"] = self.show_default 

3371 

3372 return prompt( 

3373 self.prompt, 

3374 # Use ``None`` to inform the prompt() function to reiterate until a valid 

3375 # value is provided by the user if we have no default. 

3376 default=None if default is UNSET else default, 

3377 type=self.type, 

3378 hide_input=self.hide_input, 

3379 show_choices=self.show_choices, 

3380 confirmation_prompt=self.confirmation_prompt, 

3381 value_proc=lambda x: self.process_value(ctx, x), 

3382 **prompt_kwargs, 

3383 ) 

3384 

3385 def resolve_envvar_value(self, ctx: Context) -> str | None: 

3386 """:class:`Option` resolves its environment variable the same way as 

3387 :func:`Parameter.resolve_envvar_value`, but it also supports 

3388 :attr:`Context.auto_envvar_prefix`. If we could not find an environment from 

3389 the :attr:`envvar` property, we fallback on :attr:`Context.auto_envvar_prefix` 

3390 to build dynamiccaly the environment variable name using the 

3391 :python:`{ctx.auto_envvar_prefix}_{self.name.upper()}` template. 

3392 

3393 :meta private: 

3394 """ 

3395 rv = super().resolve_envvar_value(ctx) 

3396 

3397 if rv is not None: 

3398 return rv 

3399 

3400 if self.allow_from_autoenv and ctx.auto_envvar_prefix is not None and self.name: 

3401 envvar = f"{ctx.auto_envvar_prefix}_{self.name.upper()}" 

3402 rv = os.environ.get(envvar) 

3403 

3404 if rv: 

3405 return rv 

3406 

3407 return None 

3408 

3409 def value_from_envvar(self, ctx: Context) -> t.Any: 

3410 """For :class:`Option`, this method processes the raw environment variable 

3411 string the same way as :func:`Parameter.value_from_envvar` does. 

3412 

3413 But in the case of non-boolean flags, the value is analyzed to determine if the 

3414 flag is activated or not, and returns a boolean of its activation, or the 

3415 :attr:`flag_value` if the latter is set. 

3416 

3417 This method also takes care of repeated options (i.e. options with 

3418 :attr:`multiple` set to ``True``). 

3419 

3420 :meta private: 

3421 """ 

3422 rv = self.resolve_envvar_value(ctx) 

3423 

3424 # Absent environment variable or an empty string is interpreted as unset. 

3425 if rv is None: 

3426 return None 

3427 

3428 # Non-boolean flags are more liberal in what they accept. But a flag being a 

3429 # flag, its envvar value still needs to be analyzed to determine if the flag is 

3430 # activated or not. 

3431 if self.is_flag and not self.is_bool_flag: 

3432 # If the flag_value is set and match the envvar value, return it 

3433 # directly. 

3434 if self.flag_value is not UNSET and rv == self.flag_value: 

3435 return self.flag_value 

3436 # Analyze the envvar value as a boolean to know if the flag is 

3437 # activated or not. 

3438 return types.BoolParamType.str_to_bool(rv) 

3439 

3440 # Split the envvar value if it is allowed to be repeated. 

3441 value_depth = (self.nargs != 1) + bool(self.multiple) 

3442 if value_depth > 0: 

3443 multi_rv = self.type.split_envvar_value(rv) 

3444 if self.multiple and self.nargs != 1: 

3445 multi_rv = batch(multi_rv, self.nargs) # type: ignore[assignment] 

3446 

3447 return multi_rv 

3448 

3449 return rv 

3450 

3451 def consume_value( 

3452 self, ctx: Context, opts: cabc.Mapping[str, Parameter] 

3453 ) -> tuple[t.Any, ParameterSource]: 

3454 """For :class:`Option`, the value can be collected from an interactive prompt 

3455 if the option is a flag that needs a value (and the :attr:`prompt` property is 

3456 set). 

3457 

3458 Additionally, this method handles flag option that are activated without a 

3459 value, in which case the :attr:`flag_value` is returned. 

3460 

3461 :meta private: 

3462 """ 

3463 value, source = super().consume_value(ctx, opts) 

3464 

3465 # The parser will emit a sentinel value if the option is allowed to as a flag 

3466 # without a value. 

3467 if value is FLAG_NEEDS_VALUE: 

3468 # If the option allows for a prompt, we start an interaction with the user. 

3469 if self.prompt is not None and not ctx.resilient_parsing: 

3470 value = self.prompt_for_value(ctx) 

3471 source = ParameterSource.PROMPT 

3472 # Else the flag takes its flag_value as value. 

3473 else: 

3474 value = self.flag_value 

3475 source = ParameterSource.COMMANDLINE 

3476 

3477 # A flag which is activated always returns the flag value, unless the value 

3478 # comes from the explicitly sets default. 

3479 elif ( 

3480 self.is_flag 

3481 and value is True 

3482 and not self.is_bool_flag 

3483 and source < ParameterSource.DEFAULT_MAP 

3484 ): 

3485 value = self.flag_value 

3486 

3487 # Re-interpret a multiple option which has been sent as-is by the parser. 

3488 # Here we replace each occurrence of value-less flags (marked by the 

3489 # FLAG_NEEDS_VALUE sentinel) with the flag_value. 

3490 elif ( 

3491 self.multiple 

3492 and value is not UNSET 

3493 and isinstance(value, cabc.Iterable) 

3494 and source < ParameterSource.DEFAULT_MAP 

3495 and any(v is FLAG_NEEDS_VALUE for v in value) 

3496 ): 

3497 value = [self.flag_value if v is FLAG_NEEDS_VALUE else v for v in value] 

3498 source = ParameterSource.COMMANDLINE 

3499 

3500 # The value wasn't set, or used the param's default, prompt for one to the user 

3501 # if prompting is enabled. 

3502 elif ( 

3503 (value is UNSET or source >= ParameterSource.DEFAULT_MAP) 

3504 and self.prompt is not None 

3505 and (self.required or self.prompt_required) 

3506 and not ctx.resilient_parsing 

3507 ): 

3508 value = self.prompt_for_value(ctx) 

3509 source = ParameterSource.PROMPT 

3510 

3511 return value, source 

3512 

3513 def process_value(self, ctx: Context, value: t.Any) -> t.Any: 

3514 # process_value has to be overridden on Options in order to capture 

3515 # `value == UNSET` cases before `type_cast_value()` gets called. 

3516 # 

3517 # Refs: 

3518 # https://github.com/pallets/click/issues/3069 

3519 if self.is_flag and not self.required and self.is_bool_flag and value is UNSET: 

3520 value = False 

3521 

3522 if self.callback is not None: 

3523 value = self.callback(ctx, self, value) 

3524 

3525 return value 

3526 

3527 # in the normal case, rely on Parameter.process_value 

3528 return super().process_value(ctx, value) 

3529 

3530 

3531class Argument(Parameter): 

3532 """Arguments are positional parameters to a command. They generally 

3533 provide fewer features than options but can have infinite ``nargs`` 

3534 and are required by default. 

3535 

3536 All parameters are passed onwards to the constructor of :class:`Parameter`. 

3537 """ 

3538 

3539 param_type_name = "argument" 

3540 

3541 def __init__( 

3542 self, 

3543 param_decls: cabc.Sequence[str], 

3544 required: bool | None = None, 

3545 **attrs: t.Any, 

3546 ) -> None: 

3547 # Auto-detect the requirement status of the argument if not explicitly set. 

3548 if required is None: 

3549 # The argument gets automatically required if it has no explicit default 

3550 # value set and is setup to match at least one value. 

3551 if attrs.get("default", UNSET) is UNSET: 

3552 required = attrs.get("nargs", 1) > 0 

3553 # If the argument has a default value, it is not required. 

3554 else: 

3555 required = False 

3556 

3557 if "multiple" in attrs: 

3558 raise TypeError("__init__() got an unexpected keyword argument 'multiple'.") 

3559 

3560 super().__init__(param_decls, required=required, **attrs) 

3561 

3562 @property 

3563 def human_readable_name(self) -> str: 

3564 if self.metavar is not None: 

3565 return self.metavar 

3566 return self.name.upper() 

3567 

3568 def make_metavar(self, ctx: Context) -> str: 

3569 if self.metavar is not None: 

3570 return self.metavar 

3571 var = self.type.get_metavar(param=self, ctx=ctx) 

3572 if not var: 

3573 var = self.name.upper() 

3574 # Types like ``Choice`` and ``DateTime`` already surround their metavar 

3575 # with square brackets to enumerate the allowed values. Reuse those 

3576 # outer brackets as the optional-argument indicator instead of wrapping 

3577 # the metavar in a second pair, which would produce ``[[a|b|c]]``. 

3578 already_bracketed = var.startswith("[") and var.endswith("]") 

3579 if self.deprecated: 

3580 var += "!" 

3581 if not self.required and not already_bracketed: 

3582 var = f"[{var}]" 

3583 if self.nargs != 1: 

3584 var += "..." 

3585 return var 

3586 

3587 def _parse_decls( 

3588 self, decls: cabc.Sequence[str], expose_value: bool 

3589 ) -> tuple[str, list[str], list[str]]: 

3590 if not decls: 

3591 if not expose_value: 

3592 return "", [], [] 

3593 raise TypeError("Argument is marked as exposed, but does not have a name.") 

3594 if len(decls) == 1: 

3595 name = arg = decls[0] 

3596 name = name.replace("-", "_").lower() 

3597 else: 

3598 raise TypeError( 

3599 _( 

3600 "Arguments take exactly one parameter declaration, got" 

3601 " {length}: {decls}." 

3602 ).format(length=len(decls), decls=decls) 

3603 ) 

3604 return name, [arg], [] 

3605 

3606 def get_usage_pieces(self, ctx: Context) -> list[str]: 

3607 return [self.make_metavar(ctx)] 

3608 

3609 def get_error_hint(self, ctx: Context | None) -> str: 

3610 if ctx is not None: 

3611 return f"'{self.make_metavar(ctx)}'" 

3612 return f"'{self.human_readable_name}'" 

3613 

3614 def add_to_parser(self, parser: _OptionParser, ctx: Context) -> None: 

3615 parser.add_argument(dest=self.name, nargs=self.nargs, obj=self) 

3616 

3617 

3618def __getattr__(name: str) -> object: 

3619 import warnings 

3620 

3621 if name == "BaseCommand": 

3622 warnings.warn( 

3623 "'BaseCommand' is deprecated and will be removed in Click 9.0. Use" 

3624 " 'Command' instead.", 

3625 DeprecationWarning, 

3626 stacklevel=2, 

3627 ) 

3628 return _BaseCommand 

3629 

3630 if name == "MultiCommand": 

3631 warnings.warn( 

3632 "'MultiCommand' is deprecated and will be removed in Click 9.0. Use" 

3633 " 'Group' instead.", 

3634 DeprecationWarning, 

3635 stacklevel=2, 

3636 ) 

3637 return _MultiCommand 

3638 

3639 raise AttributeError(name)