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

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

1261 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 .shell_completion import CompletionItem 

52 

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

54V = t.TypeVar("V") 

55 

56 

57def _complete_visible_commands( 

58 ctx: Context, incomplete: str 

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

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

61 incomplete value and aren't hidden. 

62 

63 :param ctx: Invocation context for the group. 

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

65 """ 

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

67 

68 for name in multi.list_commands(ctx): 

69 if name.startswith(incomplete): 

70 command = multi.get_command(ctx, name) 

71 

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

73 yield name, command 

74 

75 

76def _check_nested_chain( 

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

78) -> None: 

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

80 return 

81 

82 if register: 

83 message = ( 

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

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

86 ) 

87 else: 

88 message = ( 

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

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

91 ) 

92 

93 raise RuntimeError(message) 

94 

95 

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

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

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

99 if isinstance(deprecated, str): 

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

101 return f"({label})" 

102 

103 

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

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

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

107 """ 

108 if isinstance(deprecated, str): 

109 return f" {deprecated}" 

110 return "" 

111 

112 

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

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

115 

116 

117@contextmanager 

118def augment_usage_errors( 

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

120) -> cabc.Iterator[None]: 

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

122 try: 

123 yield 

124 except BadParameter as e: 

125 if e.ctx is None: 

126 e.ctx = ctx 

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

128 e.param = param 

129 raise 

130 except UsageError as e: 

131 if e.ctx is None: 

132 e.ctx = ctx 

133 raise 

134 

135 

136def iter_params_for_processing( 

137 invocation_order: cabc.Sequence[Parameter], 

138 declaration_order: cabc.Sequence[Parameter], 

139) -> list[Parameter]: 

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

141 

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

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

144 

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

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

147 

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

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

150 """ 

151 

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

153 try: 

154 idx: float = invocation_order.index(item) 

155 except ValueError: 

156 idx = float("inf") 

157 

158 return not item.is_eager, idx 

159 

160 return sorted(declaration_order, key=sort_key) 

161 

162 

163class ParameterSource(enum.IntEnum): 

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

165 parameter's value. 

166 

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

168 source for a parameter by name. 

169 

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

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

172 

173 .. code-block:: python 

174 

175 source = ctx.get_parameter_source("port") 

176 if source < click.ParameterSource.DEFAULT_MAP: 

177 ... # value was explicitly set 

178 

179 .. versionchanged:: 8.3.3 

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

181 least explicit. Supports comparison operators. 

182 

183 .. versionchanged:: 8.0 

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

185 

186 .. versionchanged:: 8.0 

187 Added the ``PROMPT`` value. 

188 """ 

189 

190 PROMPT = enum.auto() 

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

192 COMMANDLINE = enum.auto() 

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

194 ENVIRONMENT = enum.auto() 

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

196 DEFAULT_MAP = enum.auto() 

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

198 DEFAULT = enum.auto() 

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

200 

201 

202class Context: 

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

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

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

206 

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

208 control special execution features such as reading data from 

209 environment variables. 

210 

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

212 :meth:`close` on teardown. 

213 

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

215 :param parent: the parent context. 

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

217 is the most descriptive name for the script or 

218 command. For the toplevel script it is usually 

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

220 the name of the script. 

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

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

223 variables. If this is `None` then reading 

224 from environment variables is disabled. This 

225 does not affect manually set environment 

226 variables which are always read. 

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

228 for parameters. 

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

230 inherit from parent context. If no context 

231 defines the terminal width then auto 

232 detection will be applied. 

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

234 Click (this currently only affects help 

235 pages). This defaults to 80 characters if 

236 not overridden. In other words: even if the 

237 terminal is larger than that, Click will not 

238 format things wider than 80 characters by 

239 default. In addition to that, formatters might 

240 add some safety mapping on the right. 

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

242 parse without any interactivity or callback 

243 invocation. Default values will also be 

244 ignored. This is useful for implementing 

245 things such as completion support. 

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

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

248 kept on the context. The default is to inherit 

249 from the command. 

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

251 and arguments cannot be mixed. The 

252 default is to inherit from the command. 

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

254 not know and keeps them for later 

255 processing. 

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

257 the default help parameter is named. The 

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

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

260 normalize tokens (options, choices, 

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

262 implement case insensitive behavior. 

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

264 default is autodetection. This is only needed if ANSI 

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

266 default not the case. This for instance would affect 

267 help output. 

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

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

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

271 specific command. 

272 

273 .. versionchanged:: 8.2 

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

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

276 

277 .. versionchanged:: 8.1 

278 The ``show_default`` parameter is overridden by 

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

280 

281 .. versionchanged:: 8.0 

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

283 parent context. 

284 

285 .. versionchanged:: 7.1 

286 Added the ``show_default`` parameter. 

287 

288 .. versionchanged:: 4.0 

289 Added the ``color``, ``ignore_unknown_options``, and 

290 ``max_content_width`` parameters. 

291 

292 .. versionchanged:: 3.0 

293 Added the ``allow_extra_args`` and ``allow_interspersed_args`` 

294 parameters. 

295 

296 .. versionchanged:: 2.0 

297 Added the ``resilient_parsing``, ``help_option_names``, and 

298 ``token_normalize_func`` parameters. 

299 """ 

300 

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

302 #: 

303 #: .. versionadded:: 8.0 

304 formatter_class: type[HelpFormatter] = HelpFormatter 

305 

306 def __init__( 

307 self, 

308 command: Command, 

309 parent: Context | None = None, 

310 info_name: str | None = None, 

311 obj: t.Any | None = None, 

312 auto_envvar_prefix: str | None = None, 

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

314 terminal_width: int | None = None, 

315 max_content_width: int | None = None, 

316 resilient_parsing: bool = False, 

317 allow_extra_args: bool | None = None, 

318 allow_interspersed_args: bool | None = None, 

319 ignore_unknown_options: bool | None = None, 

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

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

322 color: bool | None = None, 

323 show_default: bool | None = None, 

324 ) -> None: 

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

326 self.parent = parent 

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

328 self.command = command 

329 #: the descriptive information name 

330 self.info_name = info_name 

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

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

333 self.params: dict[str, t.Any] = {} 

334 #: the leftover arguments. 

335 self.args: list[str] = [] 

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

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

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

339 #: to implement nested parsing. 

340 self._protected_args: list[str] = [] 

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

342 self._opt_prefixes: set[str] = set(parent._opt_prefixes) if parent else set() 

343 

344 if obj is None and parent is not None: 

345 obj = parent.obj 

346 

347 #: the user object stored. 

348 self.obj: t.Any = obj 

349 self._meta: dict[str, t.Any] = getattr(parent, "meta", {}) 

350 

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

352 if ( 

353 default_map is None 

354 and info_name is not None 

355 and parent is not None 

356 and parent.default_map is not None 

357 ): 

358 default_map = parent.default_map.get(info_name) 

359 

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

361 

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

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

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

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

366 #: the name of the subcommand to execute. 

367 #: 

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

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

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

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

372 self.invoked_subcommand: str | None = None 

373 

374 if terminal_width is None and parent is not None: 

375 terminal_width = parent.terminal_width 

376 

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

378 self.terminal_width: int | None = terminal_width 

379 

380 if max_content_width is None and parent is not None: 

381 max_content_width = parent.max_content_width 

382 

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

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

385 self.max_content_width: int | None = max_content_width 

386 

387 if allow_extra_args is None: 

388 allow_extra_args = command.allow_extra_args 

389 

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

391 #: fail on parsing. 

392 #: 

393 #: .. versionadded:: 3.0 

394 self.allow_extra_args = allow_extra_args 

395 

396 if allow_interspersed_args is None: 

397 allow_interspersed_args = command.allow_interspersed_args 

398 

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

400 #: options or not. 

401 #: 

402 #: .. versionadded:: 3.0 

403 self.allow_interspersed_args: bool = allow_interspersed_args 

404 

405 if ignore_unknown_options is None: 

406 ignore_unknown_options = command.ignore_unknown_options 

407 

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

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

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

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

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

413 #: forward all arguments. 

414 #: 

415 #: .. versionadded:: 4.0 

416 self.ignore_unknown_options: bool = ignore_unknown_options 

417 

418 if help_option_names is None: 

419 if parent is not None: 

420 help_option_names = parent.help_option_names 

421 else: 

422 help_option_names = ["--help"] 

423 

424 #: The names for the help options. 

425 self.help_option_names: list[str] = help_option_names 

426 

427 if token_normalize_func is None and parent is not None: 

428 token_normalize_func = parent.token_normalize_func 

429 

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

431 #: options, choices, commands etc. 

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

433 

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

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

436 #: will be ignored. Useful for completion. 

437 self.resilient_parsing: bool = resilient_parsing 

438 

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

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

441 # prefix automatically. 

442 if auto_envvar_prefix is None: 

443 if ( 

444 parent is not None 

445 and parent.auto_envvar_prefix is not None 

446 and self.info_name is not None 

447 ): 

448 auto_envvar_prefix = ( 

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

450 ) 

451 else: 

452 auto_envvar_prefix = auto_envvar_prefix.upper() 

453 

454 if auto_envvar_prefix is not None: 

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

456 

457 self.auto_envvar_prefix: str | None = auto_envvar_prefix 

458 

459 if color is None and parent is not None: 

460 color = parent.color 

461 

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

463 self.color: bool | None = color 

464 

465 if show_default is None and parent is not None: 

466 show_default = parent.show_default 

467 

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

469 self.show_default: bool | None = show_default 

470 

471 self._close_callbacks: list[t.Callable[[], t.Any]] = [] 

472 self._depth = 0 

473 self._parameter_source: dict[str, ParameterSource] = {} 

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

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

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

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

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

479 self._param_default_explicit: dict[str, bool] = {} 

480 self._exit_stack = ExitStack() 

481 

482 @property 

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

484 import warnings 

485 

486 warnings.warn( 

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

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

489 DeprecationWarning, 

490 stacklevel=2, 

491 ) 

492 return self._protected_args 

493 

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

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

496 user-facing documentation. This traverses the entire CLI 

497 structure. 

498 

499 .. code-block:: python 

500 

501 with Context(cli) as ctx: 

502 info = ctx.to_info_dict() 

503 

504 .. versionadded:: 8.0 

505 """ 

506 return { 

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

508 "info_name": self.info_name, 

509 "allow_extra_args": self.allow_extra_args, 

510 "allow_interspersed_args": self.allow_interspersed_args, 

511 "ignore_unknown_options": self.ignore_unknown_options, 

512 "auto_envvar_prefix": self.auto_envvar_prefix, 

513 } 

514 

515 def __enter__(self) -> Context: 

516 self._depth += 1 

517 push_context(self) 

518 return self 

519 

520 def __exit__( 

521 self, 

522 exc_type: type[BaseException] | None, 

523 exc_value: BaseException | None, 

524 tb: TracebackType | None, 

525 ) -> bool | None: 

526 self._depth -= 1 

527 exit_result: bool | None = None 

528 if self._depth == 0: 

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

530 pop_context() 

531 

532 return exit_result 

533 

534 @contextmanager 

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

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

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

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

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

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

541 

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

543 used as a context manager. 

544 

545 Example usage:: 

546 

547 with ctx.scope(): 

548 assert get_current_context() is ctx 

549 

550 This is equivalent:: 

551 

552 with ctx: 

553 assert get_current_context() is ctx 

554 

555 .. versionadded:: 5.0 

556 

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

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

559 some situations the context only wants to be 

560 temporarily pushed in which case this can be disabled. 

561 Nested pushes automatically defer the cleanup. 

562 """ 

563 if not cleanup: 

564 self._depth += 1 

565 try: 

566 with self as rv: 

567 yield rv 

568 finally: 

569 if not cleanup: 

570 self._depth -= 1 

571 

572 @property 

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

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

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

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

577 that code to manage this dictionary well. 

578 

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

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

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

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

583 the system. 

584 

585 Example usage:: 

586 

587 LANG_KEY = f'{__name__}.lang' 

588 

589 def set_language(value): 

590 ctx = get_current_context() 

591 ctx.meta[LANG_KEY] = value 

592 

593 def get_language(): 

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

595 

596 .. versionadded:: 5.0 

597 """ 

598 return self._meta 

599 

600 def make_formatter(self) -> HelpFormatter: 

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

602 usage output. 

603 

604 To quickly customize the formatter class used without overriding 

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

606 

607 .. versionchanged:: 8.0 

608 Added the :attr:`formatter_class` attribute. 

609 """ 

610 return self.formatter_class( 

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

612 ) 

613 

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

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

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

617 popped. 

618 

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

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

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

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

623 

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

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

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

627 

628 .. code-block:: python 

629 

630 @click.group() 

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

632 @click.pass_context 

633 def cli(ctx): 

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

635 

636 :param context_manager: The context manager to enter. 

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

638 

639 .. versionadded:: 8.0 

640 """ 

641 return self._exit_stack.enter_context(context_manager) 

642 

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

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

645 

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

647 execution. Resources that support Python's context manager 

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

649 registered with :meth:`with_resource` instead. 

650 

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

652 """ 

653 return self._exit_stack.callback(f) 

654 

655 def close(self) -> None: 

656 """Invoke all close callbacks registered with 

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

658 with :meth:`with_resource`. 

659 """ 

660 self._close_with_exception_info(None, None, None) 

661 

662 def _close_with_exception_info( 

663 self, 

664 exc_type: type[BaseException] | None, 

665 exc_value: BaseException | None, 

666 tb: TracebackType | None, 

667 ) -> bool | None: 

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

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

670 using :meth;`with_resource` 

671 

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

673 """ 

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

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

676 self._exit_stack = ExitStack() 

677 

678 return exit_result 

679 

680 @property 

681 def command_path(self) -> str: 

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

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

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

685 """ 

686 rv = "" 

687 if self.info_name is not None: 

688 rv = self.info_name 

689 if self.parent is not None: 

690 parent_command_path = [self.parent.command_path] 

691 

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

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

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

695 

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

697 return rv.lstrip() 

698 

699 def find_root(self) -> Context: 

700 """Finds the outermost context.""" 

701 node = self 

702 while node.parent is not None: 

703 node = node.parent 

704 return node 

705 

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

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

708 node: Context | None = self 

709 

710 while node is not None: 

711 if isinstance(node.obj, object_type): 

712 return node.obj 

713 

714 node = node.parent 

715 

716 return None 

717 

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

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

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

721 """ 

722 rv = self.find_object(object_type) 

723 if rv is None: 

724 self.obj = rv = object_type() 

725 return rv 

726 

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

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

729 

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

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

732 :data:`UNSET` sentinel. 

733 """ 

734 return ( 

735 name is not None 

736 and self.default_map is not None 

737 and name in self.default_map 

738 and self.default_map[name] is not UNSET 

739 ) 

740 

741 @t.overload 

742 def lookup_default( 

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

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

745 

746 @t.overload 

747 def lookup_default( 

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

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

750 

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

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

753 

754 :param name: Name of the parameter. 

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

756 return the callable instead. 

757 

758 .. versionchanged:: 8.0 

759 Added the ``call`` parameter. 

760 """ 

761 if not self._default_map_has(name): 

762 return None 

763 

764 # Assert to make the type checker happy. 

765 assert self.default_map is not None 

766 value = self.default_map[name] 

767 

768 if call and callable(value): 

769 return value() 

770 

771 return value 

772 

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

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

775 message. 

776 

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

778 """ 

779 raise UsageError(message, self) 

780 

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

782 """Aborts the script.""" 

783 raise Abort() 

784 

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

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

787 

788 .. versionchanged:: 8.2 

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

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

791 """ 

792 self.close() 

793 raise Exit(code) 

794 

795 def get_usage(self) -> str: 

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

797 context and command. 

798 """ 

799 return self.command.get_usage(self) 

800 

801 def get_help(self) -> str: 

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

803 context and command. 

804 """ 

805 return self.command.get_help(self) 

806 

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

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

809 for a new command. 

810 

811 :meta private: 

812 """ 

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

814 

815 @t.overload 

816 def invoke( 

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

818 ) -> V: ... 

819 

820 @t.overload 

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

822 

823 def invoke( 

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

825 ) -> t.Any | V: 

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

827 are two ways to invoke this method: 

828 

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

830 keyword arguments are forwarded directly to the function. 

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

832 arguments are forwarded as well but proper click parameters 

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

834 will fill in defaults. 

835 

836 .. versionchanged:: 8.0 

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

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

839 

840 .. versionchanged:: 3.2 

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

842 """ 

843 if isinstance(callback, Command): 

844 other_cmd = callback 

845 

846 if other_cmd.callback is None: 

847 raise TypeError( 

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

849 ) 

850 else: 

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

852 

853 ctx = self._make_sub_context(other_cmd) 

854 

855 for param in other_cmd.params: 

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

857 default_value = param.get_default(ctx) 

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

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

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

861 # instead. Refs: 

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

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

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

865 if default_value is UNSET: 

866 default_value = None 

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

868 

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

870 # them on in subsequent calls. 

871 ctx.params.update(kwargs) 

872 else: 

873 ctx = self 

874 

875 with augment_usage_errors(self): 

876 with ctx: 

877 return callback(*args, **kwargs) 

878 

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

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

881 arguments from the current context if the other command expects 

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

883 

884 .. versionchanged:: 8.0 

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

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

887 """ 

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

889 if not isinstance(cmd, Command): 

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

891 

892 for param in self.params: 

893 if param not in kwargs: 

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

895 

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

897 

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

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

900 from which the value of the parameter was obtained. 

901 

902 :param name: The name of the parameter. 

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

904 """ 

905 self._parameter_source[name] = source 

906 

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

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

909 from which the value of the parameter was obtained. 

910 

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

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

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

914 value was actually taken from the default. 

915 

916 :param name: The name of the parameter. 

917 :rtype: ParameterSource 

918 

919 .. versionchanged:: 8.0 

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

921 source. 

922 """ 

923 return self._parameter_source.get(name) 

924 

925 

926class Command: 

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

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

929 more parsing to commands nested below it. 

930 

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

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

933 passed to the context object. 

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

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

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

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

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

939 help page after everything else. 

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

941 shown on the command listing of the parent command. 

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

943 option. This can be disabled by this parameter. 

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

945 provided. This option is disabled by default. 

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

947 if no arguments are passed 

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

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

950 indicating that the command is deprecated and highlights 

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

952 by using a string as the value. 

953 

954 .. versionchanged:: 8.2 

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

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

957 deprecation message. 

958 

959 .. versionchanged:: 8.1 

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

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

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

963 

964 .. versionchanged:: 8.0 

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

966 

967 .. versionchanged:: 7.1 

968 Added the ``no_args_is_help`` parameter. 

969 

970 .. versionchanged:: 2.0 

971 Added the ``context_settings`` parameter. 

972 """ 

973 

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

975 #: 

976 #: .. versionadded:: 8.0 

977 context_class: type[Context] = Context 

978 

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

980 allow_extra_args = False 

981 

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

983 allow_interspersed_args = True 

984 

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

986 ignore_unknown_options = False 

987 

988 def __init__( 

989 self, 

990 name: str | None, 

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

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

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

994 help: str | None = None, 

995 epilog: str | None = None, 

996 short_help: str | None = None, 

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

998 add_help_option: bool = True, 

999 no_args_is_help: bool = False, 

1000 hidden: bool = False, 

1001 deprecated: bool | str = False, 

1002 ) -> None: 

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

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

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

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

1007 self.name = name 

1008 

1009 if context_settings is None: 

1010 context_settings = {} 

1011 

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

1013 self.context_settings: cabc.MutableMapping[str, t.Any] = context_settings 

1014 

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

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

1017 self.callback = callback 

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

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

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

1021 self.params: list[Parameter] = params or [] 

1022 self.help = help 

1023 self.epilog = epilog 

1024 self.options_metavar = options_metavar 

1025 self.short_help = short_help 

1026 self.add_help_option = add_help_option 

1027 self._help_option = None 

1028 self.no_args_is_help = no_args_is_help 

1029 self.hidden = hidden 

1030 self.deprecated = deprecated 

1031 

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

1033 return { 

1034 "name": self.name, 

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

1036 "help": self.help, 

1037 "epilog": self.epilog, 

1038 "short_help": self.short_help, 

1039 "hidden": self.hidden, 

1040 "deprecated": self.deprecated, 

1041 } 

1042 

1043 def __repr__(self) -> str: 

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

1045 

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

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

1048 

1049 Calls :meth:`format_usage` internally. 

1050 """ 

1051 formatter = ctx.make_formatter() 

1052 self.format_usage(ctx, formatter) 

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

1054 

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

1056 params = self.params 

1057 help_option = self.get_help_option(ctx) 

1058 

1059 if help_option is not None: 

1060 params = [*params, help_option] 

1061 

1062 if __debug__: 

1063 import warnings 

1064 

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

1066 opts_counter = Counter(opts) 

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

1068 

1069 for duplicate_opt in duplicate_opts: 

1070 warnings.warn( 

1071 ( 

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

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

1074 ), 

1075 stacklevel=3, 

1076 ) 

1077 

1078 return params 

1079 

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

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

1082 

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

1084 """ 

1085 pieces = self.collect_usage_pieces(ctx) 

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

1087 

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

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

1090 it as a list of strings. 

1091 """ 

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

1093 

1094 for param in self.get_params(ctx): 

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

1096 

1097 return rv 

1098 

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

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

1101 all_names = set(ctx.help_option_names) 

1102 for param in self.params: 

1103 all_names.difference_update(param.opts) 

1104 all_names.difference_update(param.secondary_opts) 

1105 return list(all_names) 

1106 

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

1108 """Returns the help option object. 

1109 

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

1111 

1112 .. versionchanged:: 8.1.8 

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

1114 """ 

1115 help_option_names = self.get_help_option_names(ctx) 

1116 

1117 if not help_option_names or not self.add_help_option: 

1118 return None 

1119 

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

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

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

1123 # object comparison. 

1124 if self._help_option is None: 

1125 # Avoid circular import. 

1126 from .decorators import help_option 

1127 

1128 # Apply help_option decorator and pop resulting option 

1129 help_option(*help_option_names)(self) 

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

1131 

1132 return self._help_option 

1133 

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

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

1136 parser = _OptionParser(ctx) 

1137 for param in self.get_params(ctx): 

1138 param.add_to_parser(parser, ctx) 

1139 return parser 

1140 

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

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

1143 

1144 Calls :meth:`format_help` internally. 

1145 """ 

1146 formatter = ctx.make_formatter() 

1147 self.format_help(ctx, formatter) 

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

1149 

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

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

1152 long help string. 

1153 """ 

1154 if self.short_help: 

1155 text = inspect.cleandoc(self.short_help) 

1156 elif self.help: 

1157 text = make_default_short_help(self.help, limit) 

1158 else: 

1159 text = "" 

1160 

1161 if self.deprecated: 

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

1163 

1164 return text.strip() 

1165 

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

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

1168 

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

1170 

1171 This calls the following methods: 

1172 

1173 - :meth:`format_usage` 

1174 - :meth:`format_help_text` 

1175 - :meth:`format_options` 

1176 - :meth:`format_epilog` 

1177 """ 

1178 self.format_usage(ctx, formatter) 

1179 self.format_help_text(ctx, formatter) 

1180 self.format_options(ctx, formatter) 

1181 self.format_epilog(ctx, formatter) 

1182 

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

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

1185 if self.help is not None: 

1186 # truncate the help text to the first form feed 

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

1188 else: 

1189 text = "" 

1190 

1191 if self.deprecated: 

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

1193 

1194 if text: 

1195 formatter.write_paragraph() 

1196 

1197 with formatter.indentation(): 

1198 formatter.write_text(text) 

1199 

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

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

1202 opts = [] 

1203 for param in self.get_params(ctx): 

1204 rv = param.get_help_record(ctx) 

1205 if rv is not None: 

1206 opts.append(rv) 

1207 

1208 if opts: 

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

1210 formatter.write_dl(opts) 

1211 

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

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

1214 if self.epilog: 

1215 epilog = inspect.cleandoc(self.epilog) 

1216 formatter.write_paragraph() 

1217 

1218 with formatter.indentation(): 

1219 formatter.write_text(epilog) 

1220 

1221 def make_context( 

1222 self, 

1223 info_name: str | None, 

1224 args: list[str], 

1225 parent: Context | None = None, 

1226 **extra: t.Any, 

1227 ) -> Context: 

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

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

1230 invoke the actual command callback though. 

1231 

1232 To quickly customize the context class used without overriding 

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

1234 

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

1236 is the most descriptive name for the script or 

1237 command. For the toplevel script it's usually 

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

1239 the name of the command. 

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

1241 :param parent: the parent context if available. 

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

1243 constructor. 

1244 

1245 .. versionchanged:: 8.0 

1246 Added the :attr:`context_class` attribute. 

1247 """ 

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

1249 if key not in extra: 

1250 extra[key] = value 

1251 

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

1253 

1254 with ctx.scope(cleanup=False): 

1255 self.parse_args(ctx, args) 

1256 return ctx 

1257 

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

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

1260 raise NoArgsIsHelpError(ctx) 

1261 

1262 parser = self.make_parser(ctx) 

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

1264 

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

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

1267 

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

1269 # the `UNSET` sentinel. 

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

1271 # 

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

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

1274 # Refs: 

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

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

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

1278 if value is UNSET: 

1279 ctx.params[name] = None 

1280 

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

1282 ctx.fail( 

1283 ngettext( 

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

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

1286 len(args), 

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

1288 ) 

1289 

1290 ctx.args = args 

1291 ctx._opt_prefixes.update(parser._opt_prefixes) 

1292 return args 

1293 

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

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

1296 in the right way. 

1297 """ 

1298 if self.deprecated: 

1299 message = _( 

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

1301 ).format( 

1302 name=self.name, 

1303 extra_message=_format_deprecated_suffix(self.deprecated), 

1304 ) 

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

1306 

1307 if self.callback is not None: 

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

1309 

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

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

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

1313 

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

1315 commands are valid at any point during command completion. 

1316 

1317 :param ctx: Invocation context for this command. 

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

1319 

1320 .. versionadded:: 8.0 

1321 """ 

1322 from click.shell_completion import CompletionItem 

1323 

1324 results: list[CompletionItem] = [] 

1325 

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

1327 for param in self.get_params(ctx): 

1328 if ( 

1329 not isinstance(param, Option) 

1330 or param.hidden 

1331 or ( 

1332 not param.multiple 

1333 and ctx.get_parameter_source(param.name) 

1334 is ParameterSource.COMMANDLINE 

1335 ) 

1336 ): 

1337 continue 

1338 

1339 results.extend( 

1340 CompletionItem(name, help=param.help) 

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

1342 if name.startswith(incomplete) 

1343 ) 

1344 

1345 while ctx.parent is not None: 

1346 ctx = ctx.parent 

1347 

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

1349 results.extend( 

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

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

1352 if name not in ctx._protected_args 

1353 ) 

1354 

1355 return results 

1356 

1357 @t.overload 

1358 def main( 

1359 self, 

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

1361 prog_name: str | None = None, 

1362 complete_var: str | None = None, 

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

1364 **extra: t.Any, 

1365 ) -> t.NoReturn: ... 

1366 

1367 @t.overload 

1368 def main( 

1369 self, 

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

1371 prog_name: str | None = None, 

1372 complete_var: str | None = None, 

1373 standalone_mode: bool = ..., 

1374 **extra: t.Any, 

1375 ) -> t.Any: ... 

1376 

1377 def main( 

1378 self, 

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

1380 prog_name: str | None = None, 

1381 complete_var: str | None = None, 

1382 standalone_mode: bool = True, 

1383 windows_expand_args: bool = True, 

1384 **extra: t.Any, 

1385 ) -> t.Any: 

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

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

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

1389 needs to be caught. 

1390 

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

1392 a :class:`Command`. 

1393 

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

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

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

1397 the program name is constructed by taking the file 

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

1399 :param complete_var: the environment variable that controls the 

1400 bash completion support. The default is 

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

1402 uppercase. 

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

1404 in standalone mode. Click will then 

1405 handle exceptions and convert them into 

1406 error messages and the function will never 

1407 return but shut down the interpreter. If 

1408 this is set to `False` they will be 

1409 propagated to the caller and the return 

1410 value of this function is the return value 

1411 of :meth:`invoke`. 

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

1413 env vars in command line args on Windows. 

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

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

1416 

1417 .. versionchanged:: 8.0.1 

1418 Added the ``windows_expand_args`` parameter to allow 

1419 disabling command line arg expansion on Windows. 

1420 

1421 .. versionchanged:: 8.0 

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

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

1424 

1425 .. versionchanged:: 3.0 

1426 Added the ``standalone_mode`` parameter. 

1427 """ 

1428 if args is None: 

1429 args = sys.argv[1:] 

1430 

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

1432 args = _expand_args(args) 

1433 else: 

1434 args = list(args) 

1435 

1436 if prog_name is None: 

1437 prog_name = _detect_program_name() 

1438 

1439 # Process shell completion requests and exit early. 

1440 self._main_shell_completion(extra, prog_name, complete_var) 

1441 

1442 try: 

1443 try: 

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

1445 rv = self.invoke(ctx) 

1446 if not standalone_mode: 

1447 return rv 

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

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

1450 # has obvious effects 

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

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

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

1454 # by its truthiness/falsiness 

1455 ctx.exit() 

1456 except (EOFError, KeyboardInterrupt) as e: 

1457 echo(file=sys.stderr) 

1458 raise Abort() from e 

1459 except ClickException as e: 

1460 if not standalone_mode: 

1461 raise 

1462 e.show() 

1463 sys.exit(e.exit_code) 

1464 except OSError as e: 

1465 if e.errno == errno.EPIPE: 

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

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

1468 sys.exit(1) 

1469 else: 

1470 raise 

1471 except Exit as e: 

1472 if standalone_mode: 

1473 sys.exit(e.exit_code) 

1474 else: 

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

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

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

1478 # would return its result 

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

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

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

1482 # tell the difference between the two 

1483 return e.exit_code 

1484 except Abort: 

1485 if not standalone_mode: 

1486 raise 

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

1488 sys.exit(1) 

1489 

1490 def _main_shell_completion( 

1491 self, 

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

1493 prog_name: str, 

1494 complete_var: str | None = None, 

1495 ) -> None: 

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

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

1498 program is invoked. 

1499 

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

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

1502 the completion instruction. Defaults to 

1503 ``_{PROG_NAME}_COMPLETE``. 

1504 

1505 .. versionchanged:: 8.2.0 

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

1507 """ 

1508 if complete_var is None: 

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

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

1511 

1512 instruction = os.environ.get(complete_var) 

1513 

1514 if not instruction: 

1515 return 

1516 

1517 from .shell_completion import shell_complete 

1518 

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

1520 sys.exit(rv) 

1521 

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

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

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

1525 

1526 

1527class _FakeSubclassCheck(type): 

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

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

1530 

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

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

1533 

1534 

1535class _BaseCommand(Command, metaclass=_FakeSubclassCheck): 

1536 """ 

1537 .. deprecated:: 8.2 

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

1539 """ 

1540 

1541 

1542class Group(Command): 

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

1544 

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

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

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

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

1549 subcommand is not given. 

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

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

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

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

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

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

1556 matched, and so on. 

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

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

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

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

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

1562 ``chain`` is enabled. 

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

1564 

1565 .. versionchanged:: 8.0 

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

1567 

1568 .. versionchanged:: 8.2 

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

1570 """ 

1571 

1572 allow_extra_args = True 

1573 allow_interspersed_args = False 

1574 

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

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

1577 #: subcommands use a custom command class. 

1578 #: 

1579 #: .. versionadded:: 8.0 

1580 command_class: type[Command] | None = None 

1581 

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

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

1584 #: subgroups use a custom group class. 

1585 #: 

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

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

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

1589 #: custom groups. 

1590 #: 

1591 #: .. versionadded:: 8.0 

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

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

1594 

1595 def __init__( 

1596 self, 

1597 name: str | None = None, 

1598 commands: cabc.MutableMapping[str, Command] 

1599 | cabc.Sequence[Command] 

1600 | None = None, 

1601 invoke_without_command: bool = False, 

1602 no_args_is_help: bool | None = None, 

1603 subcommand_metavar: str | None = None, 

1604 chain: bool = False, 

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

1606 **kwargs: t.Any, 

1607 ) -> None: 

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

1609 

1610 if commands is None: 

1611 commands = {} 

1612 elif isinstance(commands, abc.Sequence): 

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

1614 

1615 #: The registered subcommands by their exported names. 

1616 self.commands: cabc.MutableMapping[str, Command] = commands 

1617 

1618 if no_args_is_help is None: 

1619 no_args_is_help = not invoke_without_command 

1620 

1621 self.no_args_is_help = no_args_is_help 

1622 self.invoke_without_command = invoke_without_command 

1623 

1624 if subcommand_metavar is None: 

1625 if chain: 

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

1627 else: 

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

1629 

1630 self.subcommand_metavar = subcommand_metavar 

1631 self.chain = chain 

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

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

1634 self._result_callback = result_callback 

1635 

1636 if self.chain: 

1637 for param in self.params: 

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

1639 raise RuntimeError( 

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

1641 ) 

1642 

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

1644 info_dict = super().to_info_dict(ctx) 

1645 commands = {} 

1646 

1647 for name in self.list_commands(ctx): 

1648 command = self.get_command(ctx, name) 

1649 

1650 if command is None: 

1651 continue 

1652 

1653 sub_ctx = ctx._make_sub_context(command) 

1654 

1655 with sub_ctx.scope(cleanup=False): 

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

1657 

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

1659 return info_dict 

1660 

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

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

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

1664 """ 

1665 name = name or cmd.name 

1666 if name is None: 

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

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

1669 self.commands[name] = cmd 

1670 

1671 @t.overload 

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

1673 

1674 @t.overload 

1675 def command( 

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

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

1678 

1679 def command( 

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

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

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

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

1684 immediately registers the created command with this group by 

1685 calling :meth:`add_command`. 

1686 

1687 To customize the command class used, set the 

1688 :attr:`command_class` attribute. 

1689 

1690 .. versionchanged:: 8.1 

1691 This decorator can be applied without parentheses. 

1692 

1693 .. versionchanged:: 8.0 

1694 Added the :attr:`command_class` attribute. 

1695 """ 

1696 from .decorators import command 

1697 

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

1699 

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

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

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

1703 ) 

1704 (func,) = args 

1705 args = () 

1706 

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

1708 kwargs["cls"] = self.command_class 

1709 

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

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

1712 self.add_command(cmd) 

1713 return cmd 

1714 

1715 if func is not None: 

1716 return decorator(func) 

1717 

1718 return decorator 

1719 

1720 @t.overload 

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

1722 

1723 @t.overload 

1724 def group( 

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

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

1727 

1728 def group( 

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

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

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

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

1733 immediately registers the created group with this group by 

1734 calling :meth:`add_command`. 

1735 

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

1737 attribute. 

1738 

1739 .. versionchanged:: 8.1 

1740 This decorator can be applied without parentheses. 

1741 

1742 .. versionchanged:: 8.0 

1743 Added the :attr:`group_class` attribute. 

1744 """ 

1745 from .decorators import group 

1746 

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

1748 

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

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

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

1752 ) 

1753 (func,) = args 

1754 args = () 

1755 

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

1757 if self.group_class is type: 

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

1759 else: 

1760 kwargs["cls"] = self.group_class 

1761 

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

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

1764 self.add_command(cmd) 

1765 return cmd 

1766 

1767 if func is not None: 

1768 return decorator(func) 

1769 

1770 return decorator 

1771 

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

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

1774 result callback is already registered this will chain them but 

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

1776 callback is invoked with the return value of the subcommand 

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

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

1779 to the main callback. 

1780 

1781 Example:: 

1782 

1783 @click.group() 

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

1785 def cli(input): 

1786 return 42 

1787 

1788 @cli.result_callback() 

1789 def process_result(result, input): 

1790 return result + input 

1791 

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

1793 callback will be removed. 

1794 

1795 .. versionchanged:: 8.0 

1796 Renamed from ``resultcallback``. 

1797 

1798 .. versionadded:: 3.0 

1799 """ 

1800 

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

1802 old_callback = self._result_callback 

1803 

1804 if old_callback is None or replace: 

1805 self._result_callback = f 

1806 return f 

1807 

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

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

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

1811 

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

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

1814 

1815 return decorator 

1816 

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

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

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

1820 """ 

1821 return self.commands.get(cmd_name) 

1822 

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

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

1825 return sorted(self.commands) 

1826 

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

1828 rv = super().collect_usage_pieces(ctx) 

1829 rv.append(self.subcommand_metavar) 

1830 return rv 

1831 

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

1833 super().format_options(ctx, formatter) 

1834 self.format_commands(ctx, formatter) 

1835 

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

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

1838 after the options. 

1839 """ 

1840 commands = [] 

1841 for subcommand in self.list_commands(ctx): 

1842 cmd = self.get_command(ctx, subcommand) 

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

1844 if cmd is None: 

1845 continue 

1846 if cmd.hidden: 

1847 continue 

1848 

1849 commands.append((subcommand, cmd)) 

1850 

1851 # allow for 3 times the default spacing 

1852 if len(commands): 

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

1854 

1855 rows = [] 

1856 for subcommand, cmd in commands: 

1857 help = cmd.get_short_help_str(limit) 

1858 rows.append((subcommand, help)) 

1859 

1860 if rows: 

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

1862 formatter.write_dl(rows) 

1863 

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

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

1866 raise NoArgsIsHelpError(ctx) 

1867 

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

1869 

1870 if self.chain: 

1871 ctx._protected_args = rest 

1872 ctx.args = [] 

1873 elif rest: 

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

1875 

1876 return ctx.args 

1877 

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

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

1880 if self._result_callback is not None: 

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

1882 return value 

1883 

1884 if not ctx._protected_args: 

1885 if self.invoke_without_command: 

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

1887 # invoked with the group return value for regular 

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

1889 with ctx: 

1890 rv = super().invoke(ctx) 

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

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

1893 

1894 # Fetch args back out 

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

1896 ctx.args = [] 

1897 ctx._protected_args = [] 

1898 

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

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

1901 # name of the command to invoke. 

1902 if not self.chain: 

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

1904 # resources until the result processor has worked. 

1905 with ctx: 

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

1907 assert cmd is not None 

1908 ctx.invoked_subcommand = cmd_name 

1909 super().invoke(ctx) 

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

1911 with sub_ctx: 

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

1913 

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

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

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

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

1918 # but nothing else. 

1919 with ctx: 

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

1921 super().invoke(ctx) 

1922 

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

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

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

1926 contexts = [] 

1927 while args: 

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

1929 assert cmd is not None 

1930 sub_ctx = cmd.make_context( 

1931 cmd_name, 

1932 args, 

1933 parent=ctx, 

1934 allow_extra_args=True, 

1935 allow_interspersed_args=False, 

1936 ) 

1937 contexts.append(sub_ctx) 

1938 args, sub_ctx.args = sub_ctx.args, [] 

1939 

1940 rv = [] 

1941 for sub_ctx in contexts: 

1942 with sub_ctx: 

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

1944 return _process_result(rv) 

1945 

1946 def resolve_command( 

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

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

1949 cmd_name = make_str(args[0]) 

1950 

1951 # Get the command 

1952 cmd = self.get_command(ctx, cmd_name) 

1953 

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

1955 # function available, we try with that one. 

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

1957 cmd_name = ctx.token_normalize_func(cmd_name) 

1958 cmd = self.get_command(ctx, cmd_name) 

1959 

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

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

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

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

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

1965 # place. 

1966 if cmd is None and not ctx.resilient_parsing: 

1967 if _split_opt(cmd_name)[0]: 

1968 self.parse_args(ctx, args) 

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

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

1971 

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

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

1974 at the names of options, subcommands, and chained 

1975 multi-commands. 

1976 

1977 :param ctx: Invocation context for this command. 

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

1979 

1980 .. versionadded:: 8.0 

1981 """ 

1982 from click.shell_completion import CompletionItem 

1983 

1984 results = [ 

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

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

1987 ] 

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

1989 return results 

1990 

1991 

1992class _MultiCommand(Group, metaclass=_FakeSubclassCheck): 

1993 """ 

1994 .. deprecated:: 8.2 

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

1996 """ 

1997 

1998 

1999class CommandCollection(Group): 

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

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

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

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

2004 commands in many groups into this one group. 

2005 

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

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

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

2009 

2010 .. versionchanged:: 8.2 

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

2012 group, then each of its sources. 

2013 """ 

2014 

2015 def __init__( 

2016 self, 

2017 name: str | None = None, 

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

2019 **kwargs: t.Any, 

2020 ) -> None: 

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

2022 #: The list of registered groups. 

2023 self.sources: list[Group] = sources or [] 

2024 

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

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

2027 self.sources.append(group) 

2028 

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

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

2031 

2032 if rv is not None: 

2033 return rv 

2034 

2035 for source in self.sources: 

2036 rv = source.get_command(ctx, cmd_name) 

2037 

2038 if rv is not None: 

2039 if self.chain: 

2040 _check_nested_chain(self, cmd_name, rv) 

2041 

2042 return rv 

2043 

2044 return None 

2045 

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

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

2048 

2049 for source in self.sources: 

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

2051 

2052 return sorted(rv) 

2053 

2054 

2055def _check_iter(value: t.Any) -> cabc.Iterator[t.Any]: 

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

2057 error, or return an iterator over the value. 

2058 """ 

2059 if isinstance(value, str): 

2060 raise TypeError 

2061 

2062 return iter(value) 

2063 

2064 

2065class Parameter(ABC): 

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

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

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

2069 intentionally not finalized. 

2070 

2071 Some settings are supported by both options and arguments. 

2072 

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

2074 argument. This is a list of flags or argument 

2075 names. 

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

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

2078 automatically if supported. 

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

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

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

2082 without any arguments. 

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

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

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

2086 including prompts. 

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

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

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

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

2091 parameters are collected. 

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

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

2094 to the command callback and stored on the context, 

2095 otherwise it's skipped. 

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

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

2098 order of processing. 

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

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

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

2102 :param shell_complete: A function that returns custom shell 

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

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

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

2106 strings. 

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

2108 indicating that the argument is deprecated and highlights 

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

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

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

2112 

2113 .. versionchanged:: 8.2.0 

2114 Introduction of ``deprecated``. 

2115 

2116 .. versionchanged:: 8.2 

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

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

2119 

2120 .. versionchanged:: 8.2 

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

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

2123 

2124 .. versionchanged:: 8.0 

2125 ``process_value`` validates required parameters and bounded 

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

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

2128 ``full_process_value`` is removed. 

2129 

2130 .. versionchanged:: 8.0 

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

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

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

2134 new requirements. 

2135 

2136 .. versionchanged:: 8.0 

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

2138 tuples. 

2139 

2140 .. versionchanged:: 8.0 

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

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

2143 default to ``()``. 

2144 

2145 .. versionchanged:: 7.1 

2146 Empty environment variables are ignored rather than taking the 

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

2148 variables if they can't unset them. 

2149 

2150 .. versionchanged:: 2.0 

2151 Changed signature for parameter callback to also be passed the 

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

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

2154 """ 

2155 

2156 param_type_name = "parameter" 

2157 

2158 def __init__( 

2159 self, 

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

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

2162 required: bool = False, 

2163 # XXX The default historically embed two concepts: 

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

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

2166 # self.name, like flag options), 

2167 # - and the actual value of the default. 

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

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

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

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

2172 # Parameter.is_default and Parameter.default_value. 

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

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

2175 nargs: int | None = None, 

2176 multiple: bool = False, 

2177 metavar: str | None = None, 

2178 expose_value: bool = True, 

2179 is_eager: bool = False, 

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

2181 shell_complete: t.Callable[ 

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

2183 ] 

2184 | None = None, 

2185 deprecated: bool | str = False, 

2186 ) -> None: 

2187 self.name: str 

2188 self.opts: list[str] 

2189 self.secondary_opts: list[str] 

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

2191 param_decls or (), expose_value 

2192 ) 

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

2194 

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

2196 # information available. 

2197 if nargs is None: 

2198 if self.type.is_composite: 

2199 nargs = self.type.arity 

2200 else: 

2201 nargs = 1 

2202 

2203 self.required = required 

2204 self.callback = callback 

2205 self.nargs = nargs 

2206 self.multiple = multiple 

2207 self.expose_value = expose_value 

2208 self.default: t.Any | t.Callable[[], t.Any] | None = default 

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

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

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

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

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

2214 self._default_explicit: bool = default is not UNSET 

2215 self.is_eager = is_eager 

2216 self.metavar = metavar 

2217 self.envvar = envvar 

2218 self._custom_shell_complete = shell_complete 

2219 self.deprecated = deprecated 

2220 

2221 if __debug__: 

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

2223 raise ValueError( 

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

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

2226 ) 

2227 

2228 if required and deprecated: 

2229 raise ValueError( 

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

2231 "is deprecated and still required. A deprecated " 

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

2233 ) 

2234 

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

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

2237 user-facing documentation. 

2238 

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

2240 CLI structure. 

2241 

2242 .. versionchanged:: 8.3.0 

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

2244 

2245 .. versionadded:: 8.0 

2246 """ 

2247 return { 

2248 "name": self.name, 

2249 "param_type_name": self.param_type_name, 

2250 "opts": self.opts, 

2251 "secondary_opts": self.secondary_opts, 

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

2253 "required": self.required, 

2254 "nargs": self.nargs, 

2255 "multiple": self.multiple, 

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

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

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

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

2260 "envvar": self.envvar, 

2261 } 

2262 

2263 def __repr__(self) -> str: 

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

2265 

2266 @abstractmethod 

2267 def _parse_decls( 

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

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

2270 

2271 @property 

2272 def human_readable_name(self) -> str: 

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

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

2275 """ 

2276 return self.name 

2277 

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

2279 if self.metavar is not None: 

2280 return self.metavar 

2281 

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

2283 

2284 if metavar is None: 

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

2286 

2287 if self.nargs != 1: 

2288 metavar += "..." 

2289 

2290 return metavar 

2291 

2292 @t.overload 

2293 def get_default( 

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

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

2296 

2297 @t.overload 

2298 def get_default( 

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

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

2301 

2302 def get_default( 

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

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

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

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

2307 

2308 :param ctx: Current context. 

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

2310 return the callable instead. 

2311 

2312 .. versionchanged:: 8.0.2 

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

2314 

2315 .. versionchanged:: 8.0.1 

2316 Type casting can fail in resilient parsing mode. Invalid 

2317 defaults will not prevent showing help text. 

2318 

2319 .. versionchanged:: 8.0 

2320 Looks at ``ctx.default_map`` first. 

2321 

2322 .. versionchanged:: 8.0 

2323 Added the ``call`` parameter. 

2324 """ 

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

2326 

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

2328 value = self.default 

2329 

2330 if call and callable(value): 

2331 value = value() 

2332 

2333 return value 

2334 

2335 @abstractmethod 

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

2337 

2338 def consume_value( 

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

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

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

2342 

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

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

2345 default value. In that order of precedence. 

2346 

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

2348 

2349 :meta private: 

2350 """ 

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

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

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

2354 # parser, otherwise it left unset by default. 

2355 source = ( 

2356 ParameterSource.COMMANDLINE 

2357 if value is not UNSET 

2358 else ParameterSource.DEFAULT 

2359 ) 

2360 

2361 if value is UNSET: 

2362 envvar_value = self.value_from_envvar(ctx) 

2363 if envvar_value is not None: 

2364 value = envvar_value 

2365 source = ParameterSource.ENVIRONMENT 

2366 

2367 if value is UNSET: 

2368 default_map_value = ctx.lookup_default(self.name) 

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

2370 value = default_map_value 

2371 source = ParameterSource.DEFAULT_MAP 

2372 

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

2374 # parameters, matching value_from_envvar behavior. 

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

2376 value = self.type.split_envvar_value(value) 

2377 

2378 if value is UNSET: 

2379 default_value = self.get_default(ctx) 

2380 if default_value is not UNSET: 

2381 value = default_value 

2382 source = ParameterSource.DEFAULT 

2383 

2384 return value, source 

2385 

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

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

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

2389 """ 

2390 if value is None: 

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

2392 return () 

2393 else: 

2394 return value 

2395 

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

2397 try: 

2398 return _check_iter(value) 

2399 except TypeError: 

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

2401 # the parser should construct an iterable when parsing 

2402 # the command line. 

2403 raise BadParameter( 

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

2405 ) from None 

2406 

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

2408 

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

2410 

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

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

2413 

2414 elif self.nargs == -1: 

2415 

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

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

2418 

2419 else: # nargs > 1 

2420 

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

2422 value = tuple(check_iter(value)) 

2423 

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

2425 raise BadParameter( 

2426 ngettext( 

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

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

2429 len(value), 

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

2431 ctx=ctx, 

2432 param=self, 

2433 ) 

2434 

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

2436 

2437 if self.multiple: 

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

2439 

2440 return convert(value) 

2441 

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

2443 """A value is considered missing if: 

2444 

2445 - it is :attr:`UNSET`, 

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

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

2448 set). 

2449 

2450 :meta private: 

2451 """ 

2452 if value is UNSET: 

2453 return True 

2454 

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

2456 return True 

2457 

2458 return False 

2459 

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

2461 """Process the value of this parameter: 

2462 

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

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

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

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

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

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

2469 the :attr:`UNSET` sentinel. 

2470 

2471 :meta private: 

2472 """ 

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

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

2475 # 

2476 # Refs: 

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

2478 if value is UNSET: 

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

2480 value = () 

2481 else: 

2482 value = self.type_cast_value(ctx, value) 

2483 

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

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

2486 

2487 if self.callback is not None: 

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

2489 # to None. 

2490 if value is UNSET: 

2491 value = None 

2492 

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

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

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

2496 if not unset_keys: 

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

2498 

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

2500 # to hide UNSET values as None. 

2501 # 

2502 # Refs: 

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

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

2505 else: 

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

2507 # context is temporarily modified. 

2508 with ctx: 

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

2510 ctx.params.update(unset_keys) 

2511 # Feed these fake context parameters to the callback. 

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

2513 # Restore the UNSET values in the context parameters. 

2514 ctx.params.update( 

2515 { 

2516 k: UNSET 

2517 for k in unset_keys 

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

2519 # the callback modified other parameters. 

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

2521 } 

2522 ) 

2523 

2524 return value 

2525 

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

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

2528 parameter. 

2529 

2530 Environment variables values are `always returned as strings 

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

2532 

2533 This method returns ``None`` if: 

2534 

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

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

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

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

2539 

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

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

2542 

2543 .. caution:: 

2544 

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

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

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

2548 

2549 :meta private: 

2550 """ 

2551 if not self.envvar: 

2552 return None 

2553 

2554 if isinstance(self.envvar, str): 

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

2556 

2557 if rv: 

2558 return rv 

2559 else: 

2560 for envvar in self.envvar: 

2561 rv = os.environ.get(envvar) 

2562 

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

2564 if rv: 

2565 return rv 

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

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

2568 

2569 return None 

2570 

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

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

2573 

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

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

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

2577 

2578 :meta private: 

2579 """ 

2580 rv = self.resolve_envvar_value(ctx) 

2581 

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

2583 return self.type.split_envvar_value(rv) 

2584 

2585 return rv 

2586 

2587 def handle_parse_result( 

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

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

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

2591 

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

2593 comes from. 

2594 

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

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

2597 a default). 

2598 

2599 :meta private: 

2600 """ 

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

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

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

2604 # the slot (if any). 

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

2606 existing_source = ctx.get_parameter_source(self.name) 

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

2608 

2609 with augment_usage_errors(ctx, param=self): 

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

2611 

2612 # Display a deprecation warning if necessary. 

2613 if ( 

2614 self.deprecated 

2615 and value is not UNSET 

2616 and source < ParameterSource.DEFAULT_MAP 

2617 ): 

2618 message = _( 

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

2620 "{extra_message}" 

2621 ).format( 

2622 param_type=self.param_type_name, 

2623 name=self.human_readable_name, 

2624 extra_message=_format_deprecated_suffix(self.deprecated), 

2625 ) 

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

2627 

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

2629 try: 

2630 value = self.process_value(ctx, value) 

2631 except Exception: 

2632 if not ctx.resilient_parsing: 

2633 raise 

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

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

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

2637 value = UNSET 

2638 

2639 # Arbitrate the slot when several parameters target the same variable 

2640 # name (feature-switch groups). See: https://github.com/pallets/click/issues/3403 

2641 slot_empty = existing_value is UNSET 

2642 more_explicit = existing_source is not None and source < existing_source 

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

2644 auto_would_downgrade_explicit = ( 

2645 same_source 

2646 and source == ParameterSource.DEFAULT 

2647 and existing_default_explicit 

2648 and not self._default_explicit 

2649 ) 

2650 is_winner = ( 

2651 slot_empty 

2652 or more_explicit 

2653 or (same_source and not auto_would_downgrade_explicit) 

2654 ) 

2655 

2656 if is_winner: 

2657 ctx.set_parameter_source(self.name, source) 

2658 if self.expose_value: 

2659 ctx.params[self.name] = value 

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

2661 elif existing_source is None: 

2662 # Nothing has claimed the slot yet. Record at least our source so downstream 

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

2664 ctx.set_parameter_source(self.name, source) 

2665 

2666 return value, args 

2667 

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

2669 return None 

2670 

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

2672 return [] 

2673 

2674 def get_error_hint(self, ctx: Context | None) -> str: 

2675 """Get a stringified version of the param for use in error messages to 

2676 indicate which param caused the error. 

2677 

2678 .. versionchanged:: 8.4.0 

2679 ``ctx`` can be ``None``. 

2680 """ 

2681 hint_list = self.opts or [self.human_readable_name] 

2682 return " / ".join(f"'{x}'" for x in hint_list) 

2683 

2684 def shell_complete(self, ctx: Context, incomplete: str) -> list[CompletionItem]: 

2685 """Return a list of completions for the incomplete value. If a 

2686 ``shell_complete`` function was given during init, it is used. 

2687 Otherwise, the :attr:`type` 

2688 :meth:`~click.types.ParamType[t.Any].shell_complete` function is used. 

2689 

2690 :param ctx: Invocation context for this command. 

2691 :param incomplete: Value being completed. May be empty. 

2692 

2693 .. versionadded:: 8.0 

2694 """ 

2695 if self._custom_shell_complete is not None: 

2696 results = self._custom_shell_complete(ctx, self, incomplete) 

2697 

2698 if results and isinstance(results[0], str): 

2699 from click.shell_completion import CompletionItem 

2700 

2701 results = [CompletionItem(c) for c in results] 

2702 

2703 return t.cast("list[CompletionItem]", results) 

2704 

2705 return self.type.shell_complete(ctx, self, incomplete) 

2706 

2707 

2708class Option(Parameter): 

2709 """Options are usually optional values on the command line and 

2710 have some extra features that arguments don't have. 

2711 

2712 All other parameters are passed onwards to the parameter constructor. 

2713 

2714 :param show_default: Show the default value for this option in its 

2715 help text. Values are not shown by default, unless 

2716 :attr:`Context.show_default` is ``True``. If this value is a 

2717 string, it shows that string in parentheses instead of the 

2718 actual value. This is particularly useful for dynamic options. 

2719 For single option boolean flags, the default remains hidden if 

2720 its value is ``False``. 

2721 :param show_envvar: Controls if an environment variable should be 

2722 shown on the help page and error messages. 

2723 Normally, environment variables are not shown. 

2724 :param prompt: If set to ``True`` or a non empty string then the 

2725 user will be prompted for input. If set to ``True`` the prompt 

2726 will be the option name capitalized. A deprecated option cannot be 

2727 prompted. 

2728 :param confirmation_prompt: Prompt a second time to confirm the 

2729 value if it was prompted for. Can be set to a string instead of 

2730 ``True`` to customize the message. 

2731 :param prompt_required: If set to ``False``, the user will be 

2732 prompted for input only when the option was specified as a flag 

2733 without a value. 

2734 :param hide_input: If this is ``True`` then the input on the prompt 

2735 will be hidden from the user. This is useful for password input. 

2736 :param is_flag: forces this option to act as a flag. The default is 

2737 auto detection. 

2738 :param flag_value: which value should be used for this flag if it's 

2739 enabled. This is set to a boolean automatically if 

2740 the option string contains a slash to mark two options. 

2741 :param multiple: if this is set to `True` then the argument is accepted 

2742 multiple times and recorded. This is similar to ``nargs`` 

2743 in how it works but supports arbitrary number of 

2744 arguments. 

2745 :param count: this flag makes an option increment an integer. 

2746 :param allow_from_autoenv: if this is enabled then the value of this 

2747 parameter will be pulled from an environment 

2748 variable in case a prefix is defined on the 

2749 context. 

2750 :param help: the help string. 

2751 :param hidden: hide this option from help outputs. 

2752 :param attrs: Other command arguments described in :class:`Parameter`. 

2753 

2754 .. versionchanged:: 8.4 

2755 Non-basic ``flag_value`` types (not ``str``, ``int``, ``float``, or 

2756 ``bool``) are passed through unchanged instead of being stringified. 

2757 Previously, ``type=click.UNPROCESSED`` was required to preserve them. 

2758 

2759 .. versionchanged:: 8.2 

2760 ``envvar`` used with ``flag_value`` will always use the ``flag_value``, 

2761 previously it would use the value of the environment variable. 

2762 

2763 .. versionchanged:: 8.1 

2764 Help text indentation is cleaned here instead of only in the 

2765 ``@option`` decorator. 

2766 

2767 .. versionchanged:: 8.1 

2768 The ``show_default`` parameter overrides 

2769 ``Context.show_default``. 

2770 

2771 .. versionchanged:: 8.1 

2772 The default of a single option boolean flag is not shown if the 

2773 default value is ``False``. 

2774 

2775 .. versionchanged:: 8.0.1 

2776 ``type`` is detected from ``flag_value`` if given, for basic Python 

2777 types (``str``, ``int``, ``float``, ``bool``). 

2778 """ 

2779 

2780 param_type_name = "option" 

2781 

2782 def __init__( 

2783 self, 

2784 param_decls: cabc.Sequence[str] | None = None, 

2785 show_default: bool | str | None = None, 

2786 prompt: bool | str = False, 

2787 confirmation_prompt: bool | str = False, 

2788 prompt_required: bool = True, 

2789 hide_input: bool = False, 

2790 is_flag: bool | None = None, 

2791 flag_value: t.Any = UNSET, 

2792 multiple: bool = False, 

2793 count: bool = False, 

2794 allow_from_autoenv: bool = True, 

2795 type: types.ParamType[t.Any] | t.Any | None = None, 

2796 help: str | None = None, 

2797 hidden: bool = False, 

2798 show_choices: bool = True, 

2799 show_envvar: bool = False, 

2800 deprecated: bool | str = False, 

2801 **attrs: t.Any, 

2802 ) -> None: 

2803 if help: 

2804 help = inspect.cleandoc(help) 

2805 

2806 super().__init__( 

2807 param_decls, type=type, multiple=multiple, deprecated=deprecated, **attrs 

2808 ) 

2809 

2810 if prompt is True: 

2811 if not self.name: 

2812 raise TypeError("'name' is required with 'prompt=True'.") 

2813 

2814 prompt_text: str | None = self.name.replace("_", " ").capitalize() 

2815 elif prompt is False: 

2816 prompt_text = None 

2817 else: 

2818 prompt_text = prompt 

2819 

2820 if deprecated: 

2821 label = _format_deprecated_label(deprecated) 

2822 help = f"{help} {label}" if help is not None else label 

2823 

2824 self.prompt = prompt_text 

2825 self.confirmation_prompt = confirmation_prompt 

2826 self.prompt_required = prompt_required 

2827 self.hide_input = hide_input 

2828 self.hidden = hidden 

2829 

2830 # The _flag_needs_value property tells the parser that this option is a flag 

2831 # that cannot be used standalone and needs a value. With this information, the 

2832 # parser can determine whether to consider the next user-provided argument in 

2833 # the CLI as a value for this flag or as a new option. 

2834 # If prompt is enabled but not required, then it opens the possibility for the 

2835 # option to gets its value from the user. 

2836 self._flag_needs_value = self.prompt is not None and not self.prompt_required 

2837 

2838 # Auto-detect if this is a flag or not. 

2839 if is_flag is None: 

2840 # Implicitly a flag because flag_value was set. 

2841 if flag_value is not UNSET: 

2842 is_flag = True 

2843 # Not a flag, but when used as a flag it shows a prompt. 

2844 elif self._flag_needs_value: 

2845 is_flag = False 

2846 # Implicitly a flag because secondary options names were given. 

2847 elif self.secondary_opts: 

2848 is_flag = True 

2849 

2850 # The option is explicitly not a flag, but to determine whether or not it needs 

2851 # value, we need to check if `flag_value` or `default` was set. Either one is 

2852 # sufficient. 

2853 # Ref: https://github.com/pallets/click/issues/3084 

2854 elif is_flag is False and not self._flag_needs_value: 

2855 self._flag_needs_value = flag_value is not UNSET or self.default is UNSET 

2856 

2857 if is_flag: 

2858 # Set missing default for flags if not explicitly required or prompted. 

2859 if self.default is UNSET and not self.required and not self.prompt: 

2860 if multiple: 

2861 self.default = () 

2862 

2863 # Auto-detect the type of the flag based on the flag_value. 

2864 if type is None: 

2865 # A flag without a flag_value is a boolean flag. 

2866 if flag_value is UNSET: 

2867 self.type: types.ParamType[t.Any] = types.BoolParamType() 

2868 # If the flag value is a boolean, use BoolParamType. 

2869 elif isinstance(flag_value, bool): 

2870 self.type = types.BoolParamType() 

2871 # Otherwise, guess the type from the flag value. 

2872 else: 

2873 guessed = types.convert_type(None, flag_value) 

2874 if ( 

2875 isinstance(guessed, types.StringParamType) 

2876 and not isinstance(flag_value, str) 

2877 and flag_value is not None 

2878 ): 

2879 # The flag_value type couldn't be auto-detected 

2880 # (not str, int, float, or bool). Since flag_value 

2881 # is a programmer-provided Python object, not CLI 

2882 # input, pass it through unchanged instead of 

2883 # stringifying it. 

2884 self.type = types.UNPROCESSED 

2885 else: 

2886 self.type = guessed 

2887 

2888 self.is_flag: bool = bool(is_flag) 

2889 self.is_bool_flag: bool = bool( 

2890 is_flag and isinstance(self.type, types.BoolParamType) 

2891 ) 

2892 self.flag_value: t.Any = flag_value 

2893 

2894 # Set boolean flag default to False if unset and not required. 

2895 if self.is_bool_flag: 

2896 if self.default is UNSET and not self.required: 

2897 self.default = False 

2898 

2899 # The alignment of default to the flag_value is resolved lazily in 

2900 # get_default() to prevent callable flag_values (like classes) from 

2901 # being instantiated. Refs: 

2902 # https://github.com/pallets/click/issues/3121 

2903 # https://github.com/pallets/click/issues/3024#issuecomment-3146199461 

2904 # https://github.com/pallets/click/pull/3030/commits/06847da 

2905 

2906 # Set the default flag_value if it is not set. 

2907 if self.flag_value is UNSET: 

2908 if self.is_flag: 

2909 self.flag_value = True 

2910 else: 

2911 self.flag_value = None 

2912 

2913 # Counting. 

2914 self.count = count 

2915 if count: 

2916 if type is None: 

2917 self.type = types.IntRange(min=0) 

2918 if self.default is UNSET: 

2919 self.default = 0 

2920 

2921 self.allow_from_autoenv = allow_from_autoenv 

2922 self.help = help 

2923 self.show_default = show_default 

2924 self.show_choices = show_choices 

2925 self.show_envvar = show_envvar 

2926 

2927 if __debug__: 

2928 if deprecated and prompt: 

2929 raise ValueError("`deprecated` options cannot use `prompt`.") 

2930 

2931 if self.nargs == -1: 

2932 raise TypeError("nargs=-1 is not supported for options.") 

2933 

2934 if not self.is_bool_flag and self.secondary_opts: 

2935 raise TypeError("Secondary flag is not valid for non-boolean flag.") 

2936 

2937 if self.is_bool_flag and self.hide_input and self.prompt is not None: 

2938 raise TypeError( 

2939 "'prompt' with 'hide_input' is not valid for boolean flag." 

2940 ) 

2941 

2942 if self.count: 

2943 if self.multiple: 

2944 raise TypeError("'count' is not valid with 'multiple'.") 

2945 

2946 if self.is_flag: 

2947 raise TypeError("'count' is not valid with 'is_flag'.") 

2948 

2949 def to_info_dict(self) -> dict[str, t.Any]: 

2950 """ 

2951 .. versionchanged:: 8.3.0 

2952 Returns ``None`` for the :attr:`flag_value` if it was not set. 

2953 """ 

2954 info_dict = super().to_info_dict() 

2955 info_dict.update( 

2956 help=self.help, 

2957 prompt=self.prompt, 

2958 is_flag=self.is_flag, 

2959 # We explicitly hide the :attr:`UNSET` value to the user, as we choose to 

2960 # make it an implementation detail. And because ``to_info_dict`` has been 

2961 # designed for documentation purposes, we return ``None`` instead. 

2962 flag_value=self.flag_value if self.flag_value is not UNSET else None, 

2963 count=self.count, 

2964 hidden=self.hidden, 

2965 ) 

2966 return info_dict 

2967 

2968 def get_default( 

2969 self, ctx: Context, call: bool = True 

2970 ) -> t.Any | t.Callable[[], t.Any] | None: 

2971 """Return the default value for this option. 

2972 

2973 For non-boolean flag options, ``default=True`` is treated as a sentinel 

2974 meaning "activate this flag by default" and is resolved to 

2975 :attr:`flag_value`. For example, with ``--upper/--lower`` feature 

2976 switches where ``flag_value="upper"`` and ``default=True``, the default 

2977 resolves to ``"upper"``. 

2978 

2979 .. caution:: 

2980 This substitution only applies to non-boolean flags 

2981 (:attr:`is_bool_flag` is ``False``). For boolean flags, ``True`` is 

2982 a legitimate Python value and ``default=True`` is returned as-is. 

2983 

2984 .. versionchanged:: 8.3.3 

2985 ``default=True`` is no longer substituted with ``flag_value`` for 

2986 boolean flags, fixing negative boolean flags like 

2987 ``flag_value=False, default=True``. 

2988 """ 

2989 value = super().get_default(ctx, call=False) 

2990 

2991 # Resolve default=True to flag_value lazily (here instead of 

2992 # __init__) to prevent callable flag_values (like classes) from 

2993 # being instantiated by the callable check below. 

2994 if value is True and self.is_flag and not self.is_bool_flag: 

2995 value = self.flag_value 

2996 elif call and callable(value): 

2997 value = value() 

2998 

2999 return value 

3000 

3001 def get_error_hint(self, ctx: Context | None) -> str: 

3002 result = super().get_error_hint(ctx) 

3003 if self.show_envvar and self.envvar is not None: 

3004 result += f" (env var: '{self.envvar}')" 

3005 return result 

3006 

3007 def _parse_decls( 

3008 self, decls: cabc.Sequence[str], expose_value: bool 

3009 ) -> tuple[str, list[str], list[str]]: 

3010 opts = [] 

3011 secondary_opts = [] 

3012 name = None 

3013 possible_names = [] 

3014 

3015 for decl in decls: 

3016 if decl.isidentifier(): 

3017 if name is not None: 

3018 raise TypeError(_("Name '{name}' defined twice").format(name=name)) 

3019 name = decl 

3020 else: 

3021 split_char = ";" if decl[:1] == "/" else "/" 

3022 if split_char in decl: 

3023 first, second = decl.split(split_char, 1) 

3024 first = first.rstrip() 

3025 if first: 

3026 possible_names.append(_split_opt(first)) 

3027 opts.append(first) 

3028 second = second.lstrip() 

3029 if second: 

3030 secondary_opts.append(second.lstrip()) 

3031 if first == second: 

3032 raise ValueError( 

3033 _( 

3034 "Boolean option {decl!r} cannot use the" 

3035 " same flag for true/false." 

3036 ).format(decl=decl) 

3037 ) 

3038 else: 

3039 possible_names.append(_split_opt(decl)) 

3040 opts.append(decl) 

3041 

3042 if name is None and possible_names: 

3043 possible_names.sort(key=lambda x: -len(x[0])) # group long options first 

3044 name = possible_names[0][1].replace("-", "_").lower() 

3045 if not name.isidentifier(): 

3046 name = None 

3047 

3048 if name is None: 

3049 if not expose_value: 

3050 return "", opts, secondary_opts 

3051 raise TypeError( 

3052 _( 

3053 "Could not determine name for option with declarations {decls!r}" 

3054 ).format(decls=decls) 

3055 ) 

3056 

3057 if not opts and not secondary_opts: 

3058 raise TypeError( 

3059 _( 

3060 "No options defined but a name was passed ({name})." 

3061 " Did you mean to declare an argument instead? Did" 

3062 " you mean to pass '--{name}'?" 

3063 ).format(name=name) 

3064 ) 

3065 

3066 return name, opts, secondary_opts 

3067 

3068 def add_to_parser(self, parser: _OptionParser, ctx: Context) -> None: 

3069 if self.multiple: 

3070 action = "append" 

3071 elif self.count: 

3072 action = "count" 

3073 else: 

3074 action = "store" 

3075 

3076 if self.is_flag: 

3077 action = f"{action}_const" 

3078 

3079 if self.is_bool_flag and self.secondary_opts: 

3080 parser.add_option( 

3081 obj=self, opts=self.opts, dest=self.name, action=action, const=True 

3082 ) 

3083 parser.add_option( 

3084 obj=self, 

3085 opts=self.secondary_opts, 

3086 dest=self.name, 

3087 action=action, 

3088 const=False, 

3089 ) 

3090 else: 

3091 parser.add_option( 

3092 obj=self, 

3093 opts=self.opts, 

3094 dest=self.name, 

3095 action=action, 

3096 const=self.flag_value, 

3097 ) 

3098 else: 

3099 parser.add_option( 

3100 obj=self, 

3101 opts=self.opts, 

3102 dest=self.name, 

3103 action=action, 

3104 nargs=self.nargs, 

3105 ) 

3106 

3107 def get_help_record(self, ctx: Context) -> tuple[str, str] | None: 

3108 if self.hidden: 

3109 return None 

3110 

3111 any_prefix_is_slash = False 

3112 

3113 def _write_opts(opts: cabc.Sequence[str]) -> str: 

3114 nonlocal any_prefix_is_slash 

3115 

3116 rv, any_slashes = join_options(opts) 

3117 

3118 if any_slashes: 

3119 any_prefix_is_slash = True 

3120 

3121 if not self.is_flag and not self.count: 

3122 rv += f" {self.make_metavar(ctx=ctx)}" 

3123 

3124 return rv 

3125 

3126 rv = [_write_opts(self.opts)] 

3127 

3128 if self.secondary_opts: 

3129 rv.append(_write_opts(self.secondary_opts)) 

3130 

3131 help = self.help or "" 

3132 

3133 extra = self.get_help_extra(ctx) 

3134 extra_items = [] 

3135 if "envvars" in extra: 

3136 extra_items.append( 

3137 _("env var: {var}").format(var=", ".join(extra["envvars"])) 

3138 ) 

3139 if "default" in extra: 

3140 extra_items.append(_("default: {default}").format(default=extra["default"])) 

3141 if "range" in extra: 

3142 extra_items.append(extra["range"]) 

3143 if "required" in extra: 

3144 extra_items.append(_(extra["required"])) 

3145 

3146 if extra_items: 

3147 extra_str = "; ".join(extra_items) 

3148 help = f"{help} [{extra_str}]" if help else f"[{extra_str}]" 

3149 

3150 return ("; " if any_prefix_is_slash else " / ").join(rv), help 

3151 

3152 def get_help_extra(self, ctx: Context) -> types.OptionHelpExtra: 

3153 extra: types.OptionHelpExtra = {} 

3154 

3155 if self.show_envvar: 

3156 envvar = self.envvar 

3157 

3158 if envvar is None: 

3159 if ( 

3160 self.allow_from_autoenv 

3161 and ctx.auto_envvar_prefix is not None 

3162 and self.name 

3163 ): 

3164 envvar = f"{ctx.auto_envvar_prefix}_{self.name.upper()}" 

3165 

3166 if envvar is not None: 

3167 if isinstance(envvar, str): 

3168 extra["envvars"] = (envvar,) 

3169 else: 

3170 extra["envvars"] = tuple(str(d) for d in envvar) 

3171 

3172 # Temporarily enable resilient parsing to avoid type casting 

3173 # failing for the default. Might be possible to extend this to 

3174 # help formatting in general. 

3175 resilient = ctx.resilient_parsing 

3176 ctx.resilient_parsing = True 

3177 

3178 try: 

3179 default_value = self.get_default(ctx, call=False) 

3180 finally: 

3181 ctx.resilient_parsing = resilient 

3182 

3183 show_default = False 

3184 show_default_is_str = False 

3185 

3186 if self.show_default is not None: 

3187 if isinstance(self.show_default, str): 

3188 show_default_is_str = show_default = True 

3189 else: 

3190 show_default = self.show_default 

3191 elif ctx.show_default is not None: 

3192 show_default = ctx.show_default 

3193 

3194 if show_default_is_str or ( 

3195 show_default and (default_value not in (None, UNSET)) 

3196 ): 

3197 if show_default_is_str: 

3198 default_string = f"({self.show_default})" 

3199 elif isinstance(default_value, (list, tuple)): 

3200 default_string = ", ".join(str(d) for d in default_value) 

3201 elif isinstance(default_value, enum.Enum): 

3202 default_string = default_value.name 

3203 elif inspect.isfunction(default_value): 

3204 default_string = _("(dynamic)") 

3205 elif self.is_bool_flag and self.secondary_opts: 

3206 # For boolean flags that have distinct True/False opts, 

3207 # use the opt without prefix instead of the value. 

3208 default_string = _split_opt( 

3209 (self.opts if default_value else self.secondary_opts)[0] 

3210 )[1] 

3211 elif self.is_bool_flag and not self.secondary_opts and not default_value: 

3212 default_string = "" 

3213 elif isinstance(default_value, str) and default_value == "": 

3214 default_string = '""' 

3215 else: 

3216 default_string = str(default_value) 

3217 

3218 if default_string: 

3219 extra["default"] = default_string 

3220 

3221 if ( 

3222 isinstance(self.type, types._NumberRangeBase) 

3223 # skip count with default range type 

3224 and not (self.count and self.type.min == 0 and self.type.max is None) 

3225 ): 

3226 range_str = self.type._describe_range() 

3227 

3228 if range_str: 

3229 extra["range"] = range_str 

3230 

3231 if self.required: 

3232 extra["required"] = "required" 

3233 

3234 return extra 

3235 

3236 def prompt_for_value(self, ctx: Context) -> t.Any: 

3237 """This is an alternative flow that can be activated in the full 

3238 value processing if a value does not exist. It will prompt the 

3239 user until a valid value exists and then returns the processed 

3240 value as result. 

3241 """ 

3242 assert self.prompt is not None 

3243 

3244 # Calculate the default before prompting anything to lock in the value before 

3245 # attempting any user interaction. 

3246 default = self.get_default(ctx) 

3247 

3248 # A boolean flag can use a simplified [y/n] confirmation prompt. 

3249 if self.is_bool_flag: 

3250 # If we have no boolean default, we force the user to explicitly provide 

3251 # one. 

3252 if default in (UNSET, None): 

3253 default = None 

3254 # Nothing prevent you to declare an option that is simultaneously: 

3255 # 1) auto-detected as a boolean flag, 

3256 # 2) allowed to prompt, and 

3257 # 3) still declare a non-boolean default. 

3258 # This forced casting into a boolean is necessary to align any non-boolean 

3259 # default to the prompt, which is going to be a [y/n]-style confirmation 

3260 # because the option is still a boolean flag. That way, instead of [y/n], 

3261 # we get [Y/n] or [y/N] depending on the truthy value of the default. 

3262 # Refs: https://github.com/pallets/click/pull/3030#discussion_r2289180249 

3263 else: 

3264 default = bool(default) 

3265 return confirm(self.prompt, default) 

3266 

3267 # If show_default is given, provide this to `prompt` as well, 

3268 # otherwise we use `prompt`'s default behavior 

3269 prompt_kwargs: t.Any = {} 

3270 if self.show_default is not None: 

3271 prompt_kwargs["show_default"] = self.show_default 

3272 

3273 return prompt( 

3274 self.prompt, 

3275 # Use ``None`` to inform the prompt() function to reiterate until a valid 

3276 # value is provided by the user if we have no default. 

3277 default=None if default is UNSET else default, 

3278 type=self.type, 

3279 hide_input=self.hide_input, 

3280 show_choices=self.show_choices, 

3281 confirmation_prompt=self.confirmation_prompt, 

3282 value_proc=lambda x: self.process_value(ctx, x), 

3283 **prompt_kwargs, 

3284 ) 

3285 

3286 def resolve_envvar_value(self, ctx: Context) -> str | None: 

3287 """:class:`Option` resolves its environment variable the same way as 

3288 :func:`Parameter.resolve_envvar_value`, but it also supports 

3289 :attr:`Context.auto_envvar_prefix`. If we could not find an environment from 

3290 the :attr:`envvar` property, we fallback on :attr:`Context.auto_envvar_prefix` 

3291 to build dynamiccaly the environment variable name using the 

3292 :python:`{ctx.auto_envvar_prefix}_{self.name.upper()}` template. 

3293 

3294 :meta private: 

3295 """ 

3296 rv = super().resolve_envvar_value(ctx) 

3297 

3298 if rv is not None: 

3299 return rv 

3300 

3301 if self.allow_from_autoenv and ctx.auto_envvar_prefix is not None and self.name: 

3302 envvar = f"{ctx.auto_envvar_prefix}_{self.name.upper()}" 

3303 rv = os.environ.get(envvar) 

3304 

3305 if rv: 

3306 return rv 

3307 

3308 return None 

3309 

3310 def value_from_envvar(self, ctx: Context) -> t.Any: 

3311 """For :class:`Option`, this method processes the raw environment variable 

3312 string the same way as :func:`Parameter.value_from_envvar` does. 

3313 

3314 But in the case of non-boolean flags, the value is analyzed to determine if the 

3315 flag is activated or not, and returns a boolean of its activation, or the 

3316 :attr:`flag_value` if the latter is set. 

3317 

3318 This method also takes care of repeated options (i.e. options with 

3319 :attr:`multiple` set to ``True``). 

3320 

3321 :meta private: 

3322 """ 

3323 rv = self.resolve_envvar_value(ctx) 

3324 

3325 # Absent environment variable or an empty string is interpreted as unset. 

3326 if rv is None: 

3327 return None 

3328 

3329 # Non-boolean flags are more liberal in what they accept. But a flag being a 

3330 # flag, its envvar value still needs to be analyzed to determine if the flag is 

3331 # activated or not. 

3332 if self.is_flag and not self.is_bool_flag: 

3333 # If the flag_value is set and match the envvar value, return it 

3334 # directly. 

3335 if self.flag_value is not UNSET and rv == self.flag_value: 

3336 return self.flag_value 

3337 # Analyze the envvar value as a boolean to know if the flag is 

3338 # activated or not. 

3339 return types.BoolParamType.str_to_bool(rv) 

3340 

3341 # Split the envvar value if it is allowed to be repeated. 

3342 value_depth = (self.nargs != 1) + bool(self.multiple) 

3343 if value_depth > 0: 

3344 multi_rv = self.type.split_envvar_value(rv) 

3345 if self.multiple and self.nargs != 1: 

3346 multi_rv = batch(multi_rv, self.nargs) # type: ignore[assignment] 

3347 

3348 return multi_rv 

3349 

3350 return rv 

3351 

3352 def consume_value( 

3353 self, ctx: Context, opts: cabc.Mapping[str, Parameter] 

3354 ) -> tuple[t.Any, ParameterSource]: 

3355 """For :class:`Option`, the value can be collected from an interactive prompt 

3356 if the option is a flag that needs a value (and the :attr:`prompt` property is 

3357 set). 

3358 

3359 Additionally, this method handles flag option that are activated without a 

3360 value, in which case the :attr:`flag_value` is returned. 

3361 

3362 :meta private: 

3363 """ 

3364 value, source = super().consume_value(ctx, opts) 

3365 

3366 # The parser will emit a sentinel value if the option is allowed to as a flag 

3367 # without a value. 

3368 if value is FLAG_NEEDS_VALUE: 

3369 # If the option allows for a prompt, we start an interaction with the user. 

3370 if self.prompt is not None and not ctx.resilient_parsing: 

3371 value = self.prompt_for_value(ctx) 

3372 source = ParameterSource.PROMPT 

3373 # Else the flag takes its flag_value as value. 

3374 else: 

3375 value = self.flag_value 

3376 source = ParameterSource.COMMANDLINE 

3377 

3378 # A flag which is activated always returns the flag value, unless the value 

3379 # comes from the explicitly sets default. 

3380 elif ( 

3381 self.is_flag 

3382 and value is True 

3383 and not self.is_bool_flag 

3384 and source < ParameterSource.DEFAULT_MAP 

3385 ): 

3386 value = self.flag_value 

3387 

3388 # Re-interpret a multiple option which has been sent as-is by the parser. 

3389 # Here we replace each occurrence of value-less flags (marked by the 

3390 # FLAG_NEEDS_VALUE sentinel) with the flag_value. 

3391 elif ( 

3392 self.multiple 

3393 and value is not UNSET 

3394 and isinstance(value, cabc.Iterable) 

3395 and source < ParameterSource.DEFAULT_MAP 

3396 and any(v is FLAG_NEEDS_VALUE for v in value) 

3397 ): 

3398 value = [self.flag_value if v is FLAG_NEEDS_VALUE else v for v in value] 

3399 source = ParameterSource.COMMANDLINE 

3400 

3401 # The value wasn't set, or used the param's default, prompt for one to the user 

3402 # if prompting is enabled. 

3403 elif ( 

3404 (value is UNSET or source >= ParameterSource.DEFAULT_MAP) 

3405 and self.prompt is not None 

3406 and (self.required or self.prompt_required) 

3407 and not ctx.resilient_parsing 

3408 ): 

3409 value = self.prompt_for_value(ctx) 

3410 source = ParameterSource.PROMPT 

3411 

3412 return value, source 

3413 

3414 def process_value(self, ctx: Context, value: t.Any) -> t.Any: 

3415 # process_value has to be overridden on Options in order to capture 

3416 # `value == UNSET` cases before `type_cast_value()` gets called. 

3417 # 

3418 # Refs: 

3419 # https://github.com/pallets/click/issues/3069 

3420 if self.is_flag and not self.required and self.is_bool_flag and value is UNSET: 

3421 value = False 

3422 

3423 if self.callback is not None: 

3424 value = self.callback(ctx, self, value) 

3425 

3426 return value 

3427 

3428 # in the normal case, rely on Parameter.process_value 

3429 return super().process_value(ctx, value) 

3430 

3431 

3432class Argument(Parameter): 

3433 """Arguments are positional parameters to a command. They generally 

3434 provide fewer features than options but can have infinite ``nargs`` 

3435 and are required by default. 

3436 

3437 All parameters are passed onwards to the constructor of :class:`Parameter`. 

3438 """ 

3439 

3440 param_type_name = "argument" 

3441 

3442 def __init__( 

3443 self, 

3444 param_decls: cabc.Sequence[str], 

3445 required: bool | None = None, 

3446 **attrs: t.Any, 

3447 ) -> None: 

3448 # Auto-detect the requirement status of the argument if not explicitly set. 

3449 if required is None: 

3450 # The argument gets automatically required if it has no explicit default 

3451 # value set and is setup to match at least one value. 

3452 if attrs.get("default", UNSET) is UNSET: 

3453 required = attrs.get("nargs", 1) > 0 

3454 # If the argument has a default value, it is not required. 

3455 else: 

3456 required = False 

3457 

3458 if "multiple" in attrs: 

3459 raise TypeError("__init__() got an unexpected keyword argument 'multiple'.") 

3460 

3461 super().__init__(param_decls, required=required, **attrs) 

3462 

3463 @property 

3464 def human_readable_name(self) -> str: 

3465 if self.metavar is not None: 

3466 return self.metavar 

3467 return self.name.upper() 

3468 

3469 def make_metavar(self, ctx: Context) -> str: 

3470 if self.metavar is not None: 

3471 return self.metavar 

3472 var = self.type.get_metavar(param=self, ctx=ctx) 

3473 if not var: 

3474 var = self.name.upper() 

3475 if self.deprecated: 

3476 var += "!" 

3477 if not self.required: 

3478 var = f"[{var}]" 

3479 if self.nargs != 1: 

3480 var += "..." 

3481 return var 

3482 

3483 def _parse_decls( 

3484 self, decls: cabc.Sequence[str], expose_value: bool 

3485 ) -> tuple[str, list[str], list[str]]: 

3486 if not decls: 

3487 if not expose_value: 

3488 return "", [], [] 

3489 raise TypeError("Argument is marked as exposed, but does not have a name.") 

3490 if len(decls) == 1: 

3491 name = arg = decls[0] 

3492 name = name.replace("-", "_").lower() 

3493 else: 

3494 raise TypeError( 

3495 _( 

3496 "Arguments take exactly one parameter declaration, got" 

3497 " {length}: {decls}." 

3498 ).format(length=len(decls), decls=decls) 

3499 ) 

3500 return name, [arg], [] 

3501 

3502 def get_usage_pieces(self, ctx: Context) -> list[str]: 

3503 return [self.make_metavar(ctx)] 

3504 

3505 def get_error_hint(self, ctx: Context | None) -> str: 

3506 if ctx is not None: 

3507 return f"'{self.make_metavar(ctx)}'" 

3508 return f"'{self.human_readable_name}'" 

3509 

3510 def add_to_parser(self, parser: _OptionParser, ctx: Context) -> None: 

3511 parser.add_argument(dest=self.name, nargs=self.nargs, obj=self) 

3512 

3513 

3514def __getattr__(name: str) -> object: 

3515 import warnings 

3516 

3517 if name == "BaseCommand": 

3518 warnings.warn( 

3519 "'BaseCommand' is deprecated and will be removed in Click 9.0. Use" 

3520 " 'Command' instead.", 

3521 DeprecationWarning, 

3522 stacklevel=2, 

3523 ) 

3524 return _BaseCommand 

3525 

3526 if name == "MultiCommand": 

3527 warnings.warn( 

3528 "'MultiCommand' is deprecated and will be removed in Click 9.0. Use" 

3529 " 'Group' instead.", 

3530 DeprecationWarning, 

3531 stacklevel=2, 

3532 ) 

3533 return _MultiCommand 

3534 

3535 raise AttributeError(name)