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

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

1210 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 collections import abc 

11from collections import Counter 

12from contextlib import AbstractContextManager 

13from contextlib import contextmanager 

14from contextlib import ExitStack 

15from functools import update_wrapper 

16from gettext import gettext as _ 

17from gettext import ngettext 

18from itertools import repeat 

19from types import TracebackType 

20 

21from . import types 

22from ._utils import FLAG_NEEDS_VALUE 

23from ._utils import UNSET 

24from .exceptions import Abort 

25from .exceptions import BadParameter 

26from .exceptions import ClickException 

27from .exceptions import Exit 

28from .exceptions import MissingParameter 

29from .exceptions import NoArgsIsHelpError 

30from .exceptions import UsageError 

31from .formatting import HelpFormatter 

32from .formatting import join_options 

33from .globals import pop_context 

34from .globals import push_context 

35from .parser import _OptionParser 

36from .parser import _split_opt 

37from .termui import confirm 

38from .termui import prompt 

39from .termui import style 

40from .utils import _detect_program_name 

41from .utils import _expand_args 

42from .utils import echo 

43from .utils import make_default_short_help 

44from .utils import make_str 

45from .utils import PacifyFlushWrapper 

46 

47if t.TYPE_CHECKING: 

48 from .shell_completion import CompletionItem 

49 

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

51V = t.TypeVar("V") 

52 

53 

54def _complete_visible_commands( 

55 ctx: Context, incomplete: str 

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

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

58 incomplete value and aren't hidden. 

59 

60 :param ctx: Invocation context for the group. 

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

62 """ 

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

64 

65 for name in multi.list_commands(ctx): 

66 if name.startswith(incomplete): 

67 command = multi.get_command(ctx, name) 

68 

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

70 yield name, command 

71 

72 

73def _check_nested_chain( 

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

75) -> None: 

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

77 return 

78 

79 if register: 

80 message = ( 

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

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

83 ) 

84 else: 

85 message = ( 

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

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

88 ) 

89 

90 raise RuntimeError(message) 

91 

92 

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

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

95 

96 

97@contextmanager 

98def augment_usage_errors( 

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

100) -> cabc.Iterator[None]: 

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

102 try: 

103 yield 

104 except BadParameter as e: 

105 if e.ctx is None: 

106 e.ctx = ctx 

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

108 e.param = param 

109 raise 

110 except UsageError as e: 

111 if e.ctx is None: 

112 e.ctx = ctx 

113 raise 

114 

115 

116def iter_params_for_processing( 

117 invocation_order: cabc.Sequence[Parameter], 

118 declaration_order: cabc.Sequence[Parameter], 

119) -> list[Parameter]: 

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

121 

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

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

124 

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

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

127 

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

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

130 """ 

131 

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

133 try: 

134 idx: float = invocation_order.index(item) 

135 except ValueError: 

136 idx = float("inf") 

137 

138 return not item.is_eager, idx 

139 

140 return sorted(declaration_order, key=sort_key) 

141 

142 

143class ParameterSource(enum.Enum): 

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

145 parameter's value. 

146 

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

148 source for a parameter by name. 

149 

150 .. versionchanged:: 8.0 

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

152 

153 .. versionchanged:: 8.0 

154 Added the ``PROMPT`` value. 

155 """ 

156 

157 COMMANDLINE = enum.auto() 

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

159 ENVIRONMENT = enum.auto() 

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

161 DEFAULT = enum.auto() 

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

163 DEFAULT_MAP = enum.auto() 

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

165 PROMPT = enum.auto() 

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

167 

168 

169class Context: 

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

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

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

173 

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

175 control special execution features such as reading data from 

176 environment variables. 

177 

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

179 :meth:`close` on teardown. 

180 

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

182 :param parent: the parent context. 

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

184 is the most descriptive name for the script or 

185 command. For the toplevel script it is usually 

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

187 the name of the script. 

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

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

190 variables. If this is `None` then reading 

191 from environment variables is disabled. This 

192 does not affect manually set environment 

193 variables which are always read. 

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

195 for parameters. 

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

197 inherit from parent context. If no context 

198 defines the terminal width then auto 

199 detection will be applied. 

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

201 Click (this currently only affects help 

202 pages). This defaults to 80 characters if 

203 not overridden. In other words: even if the 

204 terminal is larger than that, Click will not 

205 format things wider than 80 characters by 

206 default. In addition to that, formatters might 

207 add some safety mapping on the right. 

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

209 parse without any interactivity or callback 

210 invocation. Default values will also be 

211 ignored. This is useful for implementing 

212 things such as completion support. 

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

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

215 kept on the context. The default is to inherit 

216 from the command. 

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

218 and arguments cannot be mixed. The 

219 default is to inherit from the command. 

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

221 not know and keeps them for later 

222 processing. 

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

224 the default help parameter is named. The 

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

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

227 normalize tokens (options, choices, 

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

229 implement case insensitive behavior. 

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

231 default is autodetection. This is only needed if ANSI 

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

233 default not the case. This for instance would affect 

234 help output. 

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

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

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

238 specific command. 

239 

240 .. versionchanged:: 8.2 

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

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

243 

244 .. versionchanged:: 8.1 

245 The ``show_default`` parameter is overridden by 

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

247 

248 .. versionchanged:: 8.0 

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

250 parent context. 

251 

252 .. versionchanged:: 7.1 

253 Added the ``show_default`` parameter. 

254 

255 .. versionchanged:: 4.0 

256 Added the ``color``, ``ignore_unknown_options``, and 

257 ``max_content_width`` parameters. 

258 

259 .. versionchanged:: 3.0 

260 Added the ``allow_extra_args`` and ``allow_interspersed_args`` 

261 parameters. 

262 

263 .. versionchanged:: 2.0 

264 Added the ``resilient_parsing``, ``help_option_names``, and 

265 ``token_normalize_func`` parameters. 

266 """ 

267 

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

269 #: 

270 #: .. versionadded:: 8.0 

271 formatter_class: type[HelpFormatter] = HelpFormatter 

272 

273 def __init__( 

274 self, 

275 command: Command, 

276 parent: Context | None = None, 

277 info_name: str | None = None, 

278 obj: t.Any | None = None, 

279 auto_envvar_prefix: str | None = None, 

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

281 terminal_width: int | None = None, 

282 max_content_width: int | None = None, 

283 resilient_parsing: bool = False, 

284 allow_extra_args: bool | None = None, 

285 allow_interspersed_args: bool | None = None, 

286 ignore_unknown_options: bool | None = None, 

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

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

289 color: bool | None = None, 

290 show_default: bool | None = None, 

291 ) -> None: 

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

293 self.parent = parent 

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

295 self.command = command 

296 #: the descriptive information name 

297 self.info_name = info_name 

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

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

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

301 #: the leftover arguments. 

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

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

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

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

306 #: to implement nested parsing. 

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

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

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

310 

311 if obj is None and parent is not None: 

312 obj = parent.obj 

313 

314 #: the user object stored. 

315 self.obj: t.Any = obj 

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

317 

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

319 if ( 

320 default_map is None 

321 and info_name is not None 

322 and parent is not None 

323 and parent.default_map is not None 

324 ): 

325 default_map = parent.default_map.get(info_name) 

326 

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

328 

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

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

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

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

333 #: the name of the subcommand to execute. 

334 #: 

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

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

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

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

339 self.invoked_subcommand: str | None = None 

340 

341 if terminal_width is None and parent is not None: 

342 terminal_width = parent.terminal_width 

343 

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

345 self.terminal_width: int | None = terminal_width 

346 

347 if max_content_width is None and parent is not None: 

348 max_content_width = parent.max_content_width 

349 

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

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

352 self.max_content_width: int | None = max_content_width 

353 

354 if allow_extra_args is None: 

355 allow_extra_args = command.allow_extra_args 

356 

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

358 #: fail on parsing. 

359 #: 

360 #: .. versionadded:: 3.0 

361 self.allow_extra_args = allow_extra_args 

362 

363 if allow_interspersed_args is None: 

364 allow_interspersed_args = command.allow_interspersed_args 

365 

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

367 #: options or not. 

368 #: 

369 #: .. versionadded:: 3.0 

370 self.allow_interspersed_args: bool = allow_interspersed_args 

371 

372 if ignore_unknown_options is None: 

373 ignore_unknown_options = command.ignore_unknown_options 

374 

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

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

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

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

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

380 #: forward all arguments. 

381 #: 

382 #: .. versionadded:: 4.0 

383 self.ignore_unknown_options: bool = ignore_unknown_options 

384 

385 if help_option_names is None: 

386 if parent is not None: 

387 help_option_names = parent.help_option_names 

388 else: 

389 help_option_names = ["--help"] 

390 

391 #: The names for the help options. 

392 self.help_option_names: list[str] = help_option_names 

393 

394 if token_normalize_func is None and parent is not None: 

395 token_normalize_func = parent.token_normalize_func 

396 

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

398 #: options, choices, commands etc. 

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

400 

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

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

403 #: will be ignored. Useful for completion. 

404 self.resilient_parsing: bool = resilient_parsing 

405 

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

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

408 # prefix automatically. 

409 if auto_envvar_prefix is None: 

410 if ( 

411 parent is not None 

412 and parent.auto_envvar_prefix is not None 

413 and self.info_name is not None 

414 ): 

415 auto_envvar_prefix = ( 

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

417 ) 

418 else: 

419 auto_envvar_prefix = auto_envvar_prefix.upper() 

420 

421 if auto_envvar_prefix is not None: 

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

423 

424 self.auto_envvar_prefix: str | None = auto_envvar_prefix 

425 

426 if color is None and parent is not None: 

427 color = parent.color 

428 

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

430 self.color: bool | None = color 

431 

432 if show_default is None and parent is not None: 

433 show_default = parent.show_default 

434 

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

436 self.show_default: bool | None = show_default 

437 

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

439 self._depth = 0 

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

441 self._exit_stack = ExitStack() 

442 

443 @property 

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

445 import warnings 

446 

447 warnings.warn( 

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

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

450 DeprecationWarning, 

451 stacklevel=2, 

452 ) 

453 return self._protected_args 

454 

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

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

457 user-facing documentation. This traverses the entire CLI 

458 structure. 

459 

460 .. code-block:: python 

461 

462 with Context(cli) as ctx: 

463 info = ctx.to_info_dict() 

464 

465 .. versionadded:: 8.0 

466 """ 

467 return { 

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

469 "info_name": self.info_name, 

470 "allow_extra_args": self.allow_extra_args, 

471 "allow_interspersed_args": self.allow_interspersed_args, 

472 "ignore_unknown_options": self.ignore_unknown_options, 

473 "auto_envvar_prefix": self.auto_envvar_prefix, 

474 } 

475 

476 def __enter__(self) -> Context: 

477 self._depth += 1 

478 push_context(self) 

479 return self 

480 

481 def __exit__( 

482 self, 

483 exc_type: type[BaseException] | None, 

484 exc_value: BaseException | None, 

485 tb: TracebackType | None, 

486 ) -> bool | None: 

487 self._depth -= 1 

488 exit_result: bool | None = None 

489 if self._depth == 0: 

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

491 pop_context() 

492 

493 return exit_result 

494 

495 @contextmanager 

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

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

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

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

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

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

502 

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

504 used as a context manager. 

505 

506 Example usage:: 

507 

508 with ctx.scope(): 

509 assert get_current_context() is ctx 

510 

511 This is equivalent:: 

512 

513 with ctx: 

514 assert get_current_context() is ctx 

515 

516 .. versionadded:: 5.0 

517 

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

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

520 some situations the context only wants to be 

521 temporarily pushed in which case this can be disabled. 

522 Nested pushes automatically defer the cleanup. 

523 """ 

524 if not cleanup: 

525 self._depth += 1 

526 try: 

527 with self as rv: 

528 yield rv 

529 finally: 

530 if not cleanup: 

531 self._depth -= 1 

532 

533 @property 

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

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

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

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

538 that code to manage this dictionary well. 

539 

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

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

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

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

544 the system. 

545 

546 Example usage:: 

547 

548 LANG_KEY = f'{__name__}.lang' 

549 

550 def set_language(value): 

551 ctx = get_current_context() 

552 ctx.meta[LANG_KEY] = value 

553 

554 def get_language(): 

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

556 

557 .. versionadded:: 5.0 

558 """ 

559 return self._meta 

560 

561 def make_formatter(self) -> HelpFormatter: 

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

563 usage output. 

564 

565 To quickly customize the formatter class used without overriding 

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

567 

568 .. versionchanged:: 8.0 

569 Added the :attr:`formatter_class` attribute. 

570 """ 

571 return self.formatter_class( 

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

573 ) 

574 

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

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

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

578 popped. 

579 

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

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

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

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

584 

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

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

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

588 

589 .. code-block:: python 

590 

591 @click.group() 

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

593 @click.pass_context 

594 def cli(ctx): 

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

596 

597 :param context_manager: The context manager to enter. 

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

599 

600 .. versionadded:: 8.0 

601 """ 

602 return self._exit_stack.enter_context(context_manager) 

603 

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

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

606 

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

608 execution. Resources that support Python's context manager 

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

610 registered with :meth:`with_resource` instead. 

611 

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

613 """ 

614 return self._exit_stack.callback(f) 

615 

616 def close(self) -> None: 

617 """Invoke all close callbacks registered with 

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

619 with :meth:`with_resource`. 

620 """ 

621 self._close_with_exception_info(None, None, None) 

622 

623 def _close_with_exception_info( 

624 self, 

625 exc_type: type[BaseException] | None, 

626 exc_value: BaseException | None, 

627 tb: TracebackType | None, 

628 ) -> bool | None: 

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

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

631 using :meth;`with_resource` 

632 

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

634 """ 

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

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

637 self._exit_stack = ExitStack() 

638 

639 return exit_result 

640 

641 @property 

642 def command_path(self) -> str: 

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

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

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

646 """ 

647 rv = "" 

648 if self.info_name is not None: 

649 rv = self.info_name 

650 if self.parent is not None: 

651 parent_command_path = [self.parent.command_path] 

652 

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

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

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

656 

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

658 return rv.lstrip() 

659 

660 def find_root(self) -> Context: 

661 """Finds the outermost context.""" 

662 node = self 

663 while node.parent is not None: 

664 node = node.parent 

665 return node 

666 

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

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

669 node: Context | None = self 

670 

671 while node is not None: 

672 if isinstance(node.obj, object_type): 

673 return node.obj 

674 

675 node = node.parent 

676 

677 return None 

678 

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

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

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

682 """ 

683 rv = self.find_object(object_type) 

684 if rv is None: 

685 self.obj = rv = object_type() 

686 return rv 

687 

688 @t.overload 

689 def lookup_default( 

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

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

692 

693 @t.overload 

694 def lookup_default( 

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

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

697 

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

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

700 

701 :param name: Name of the parameter. 

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

703 return the callable instead. 

704 

705 .. versionchanged:: 8.0 

706 Added the ``call`` parameter. 

707 """ 

708 if self.default_map is not None: 

709 value = self.default_map.get(name, UNSET) 

710 

711 if call and callable(value): 

712 return value() 

713 

714 return value 

715 

716 return UNSET 

717 

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

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

720 message. 

721 

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

723 """ 

724 raise UsageError(message, self) 

725 

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

727 """Aborts the script.""" 

728 raise Abort() 

729 

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

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

732 

733 .. versionchanged:: 8.2 

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

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

736 """ 

737 self.close() 

738 raise Exit(code) 

739 

740 def get_usage(self) -> str: 

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

742 context and command. 

743 """ 

744 return self.command.get_usage(self) 

745 

746 def get_help(self) -> str: 

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

748 context and command. 

749 """ 

750 return self.command.get_help(self) 

751 

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

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

754 for a new command. 

755 

756 :meta private: 

757 """ 

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

759 

760 @t.overload 

761 def invoke( 

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

763 ) -> V: ... 

764 

765 @t.overload 

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

767 

768 def invoke( 

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

770 ) -> t.Any | V: 

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

772 are two ways to invoke this method: 

773 

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

775 keyword arguments are forwarded directly to the function. 

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

777 arguments are forwarded as well but proper click parameters 

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

779 will fill in defaults. 

780 

781 .. versionchanged:: 8.0 

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

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

784 

785 .. versionchanged:: 3.2 

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

787 """ 

788 if isinstance(callback, Command): 

789 other_cmd = callback 

790 

791 if other_cmd.callback is None: 

792 raise TypeError( 

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

794 ) 

795 else: 

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

797 

798 ctx = self._make_sub_context(other_cmd) 

799 

800 for param in other_cmd.params: 

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

802 kwargs[param.name] = param.type_cast_value( # type: ignore 

803 ctx, param.get_default(ctx) 

804 ) 

805 

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

807 # them on in subsequent calls. 

808 ctx.params.update(kwargs) 

809 else: 

810 ctx = self 

811 

812 with augment_usage_errors(self): 

813 with ctx: 

814 return callback(*args, **kwargs) 

815 

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

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

818 arguments from the current context if the other command expects 

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

820 

821 .. versionchanged:: 8.0 

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

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

824 """ 

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

826 if not isinstance(cmd, Command): 

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

828 

829 for param in self.params: 

830 if param not in kwargs: 

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

832 

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

834 

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

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

837 from which the value of the parameter was obtained. 

838 

839 :param name: The name of the parameter. 

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

841 """ 

842 self._parameter_source[name] = source 

843 

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

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

846 from which the value of the parameter was obtained. 

847 

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

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

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

851 value was actually taken from the default. 

852 

853 :param name: The name of the parameter. 

854 :rtype: ParameterSource 

855 

856 .. versionchanged:: 8.0 

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

858 source. 

859 """ 

860 return self._parameter_source.get(name) 

861 

862 

863class Command: 

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

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

866 more parsing to commands nested below it. 

867 

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

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

870 passed to the context object. 

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

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

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

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

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

876 help page after everything else. 

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

878 shown on the command listing of the parent command. 

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

880 option. This can be disabled by this parameter. 

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

882 provided. This option is disabled by default. 

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

884 if no arguments are passed 

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

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

887 indicating that the command is deprecated and highlights 

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

889 by using a string as the value. 

890 

891 .. versionchanged:: 8.2 

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

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

894 deprecation message. 

895 

896 .. versionchanged:: 8.1 

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

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

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

900 

901 .. versionchanged:: 8.0 

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

903 

904 .. versionchanged:: 7.1 

905 Added the ``no_args_is_help`` parameter. 

906 

907 .. versionchanged:: 2.0 

908 Added the ``context_settings`` parameter. 

909 """ 

910 

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

912 #: 

913 #: .. versionadded:: 8.0 

914 context_class: type[Context] = Context 

915 

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

917 allow_extra_args = False 

918 

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

920 allow_interspersed_args = True 

921 

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

923 ignore_unknown_options = False 

924 

925 def __init__( 

926 self, 

927 name: str | None, 

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

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

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

931 help: str | None = None, 

932 epilog: str | None = None, 

933 short_help: str | None = None, 

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

935 add_help_option: bool = True, 

936 no_args_is_help: bool = False, 

937 hidden: bool = False, 

938 deprecated: bool | str = False, 

939 ) -> None: 

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

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

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

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

944 self.name = name 

945 

946 if context_settings is None: 

947 context_settings = {} 

948 

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

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

951 

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

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

954 self.callback = callback 

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

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

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

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

959 self.help = help 

960 self.epilog = epilog 

961 self.options_metavar = options_metavar 

962 self.short_help = short_help 

963 self.add_help_option = add_help_option 

964 self._help_option = None 

965 self.no_args_is_help = no_args_is_help 

966 self.hidden = hidden 

967 self.deprecated = deprecated 

968 

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

970 return { 

971 "name": self.name, 

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

973 "help": self.help, 

974 "epilog": self.epilog, 

975 "short_help": self.short_help, 

976 "hidden": self.hidden, 

977 "deprecated": self.deprecated, 

978 } 

979 

980 def __repr__(self) -> str: 

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

982 

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

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

985 

986 Calls :meth:`format_usage` internally. 

987 """ 

988 formatter = ctx.make_formatter() 

989 self.format_usage(ctx, formatter) 

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

991 

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

993 params = self.params 

994 help_option = self.get_help_option(ctx) 

995 

996 if help_option is not None: 

997 params = [*params, help_option] 

998 

999 if __debug__: 

1000 import warnings 

1001 

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

1003 opts_counter = Counter(opts) 

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

1005 

1006 for duplicate_opt in duplicate_opts: 

1007 warnings.warn( 

1008 ( 

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

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

1011 ), 

1012 stacklevel=3, 

1013 ) 

1014 

1015 return params 

1016 

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

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

1019 

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

1021 """ 

1022 pieces = self.collect_usage_pieces(ctx) 

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

1024 

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

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

1027 it as a list of strings. 

1028 """ 

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

1030 

1031 for param in self.get_params(ctx): 

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

1033 

1034 return rv 

1035 

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

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

1038 all_names = set(ctx.help_option_names) 

1039 for param in self.params: 

1040 all_names.difference_update(param.opts) 

1041 all_names.difference_update(param.secondary_opts) 

1042 return list(all_names) 

1043 

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

1045 """Returns the help option object. 

1046 

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

1048 

1049 .. versionchanged:: 8.1.8 

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

1051 """ 

1052 help_option_names = self.get_help_option_names(ctx) 

1053 

1054 if not help_option_names or not self.add_help_option: 

1055 return None 

1056 

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

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

1059 # callback odering by iter_params_for_processing(), which relies on 

1060 # object comparison. 

1061 if self._help_option is None: 

1062 # Avoid circular import. 

1063 from .decorators import help_option 

1064 

1065 # Apply help_option decorator and pop resulting option 

1066 help_option(*help_option_names)(self) 

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

1068 

1069 return self._help_option 

1070 

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

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

1073 parser = _OptionParser(ctx) 

1074 for param in self.get_params(ctx): 

1075 param.add_to_parser(parser, ctx) 

1076 return parser 

1077 

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

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

1080 

1081 Calls :meth:`format_help` internally. 

1082 """ 

1083 formatter = ctx.make_formatter() 

1084 self.format_help(ctx, formatter) 

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

1086 

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

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

1089 long help string. 

1090 """ 

1091 if self.short_help: 

1092 text = inspect.cleandoc(self.short_help) 

1093 elif self.help: 

1094 text = make_default_short_help(self.help, limit) 

1095 else: 

1096 text = "" 

1097 

1098 if self.deprecated: 

1099 deprecated_message = ( 

1100 f"(DEPRECATED: {self.deprecated})" 

1101 if isinstance(self.deprecated, str) 

1102 else "(DEPRECATED)" 

1103 ) 

1104 text = _("{text} {deprecated_message}").format( 

1105 text=text, deprecated_message=deprecated_message 

1106 ) 

1107 

1108 return text.strip() 

1109 

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

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

1112 

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

1114 

1115 This calls the following methods: 

1116 

1117 - :meth:`format_usage` 

1118 - :meth:`format_help_text` 

1119 - :meth:`format_options` 

1120 - :meth:`format_epilog` 

1121 """ 

1122 self.format_usage(ctx, formatter) 

1123 self.format_help_text(ctx, formatter) 

1124 self.format_options(ctx, formatter) 

1125 self.format_epilog(ctx, formatter) 

1126 

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

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

1129 if self.help is not None: 

1130 # truncate the help text to the first form feed 

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

1132 else: 

1133 text = "" 

1134 

1135 if self.deprecated: 

1136 deprecated_message = ( 

1137 f"(DEPRECATED: {self.deprecated})" 

1138 if isinstance(self.deprecated, str) 

1139 else "(DEPRECATED)" 

1140 ) 

1141 text = _("{text} {deprecated_message}").format( 

1142 text=text, deprecated_message=deprecated_message 

1143 ) 

1144 

1145 if text: 

1146 formatter.write_paragraph() 

1147 

1148 with formatter.indentation(): 

1149 formatter.write_text(text) 

1150 

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

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

1153 opts = [] 

1154 for param in self.get_params(ctx): 

1155 rv = param.get_help_record(ctx) 

1156 if rv is not None: 

1157 opts.append(rv) 

1158 

1159 if opts: 

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

1161 formatter.write_dl(opts) 

1162 

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

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

1165 if self.epilog: 

1166 epilog = inspect.cleandoc(self.epilog) 

1167 formatter.write_paragraph() 

1168 

1169 with formatter.indentation(): 

1170 formatter.write_text(epilog) 

1171 

1172 def make_context( 

1173 self, 

1174 info_name: str | None, 

1175 args: list[str], 

1176 parent: Context | None = None, 

1177 **extra: t.Any, 

1178 ) -> Context: 

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

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

1181 invoke the actual command callback though. 

1182 

1183 To quickly customize the context class used without overriding 

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

1185 

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

1187 is the most descriptive name for the script or 

1188 command. For the toplevel script it's usually 

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

1190 the name of the command. 

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

1192 :param parent: the parent context if available. 

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

1194 constructor. 

1195 

1196 .. versionchanged:: 8.0 

1197 Added the :attr:`context_class` attribute. 

1198 """ 

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

1200 if key not in extra: 

1201 extra[key] = value 

1202 

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

1204 

1205 with ctx.scope(cleanup=False): 

1206 self.parse_args(ctx, args) 

1207 return ctx 

1208 

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

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

1211 raise NoArgsIsHelpError(ctx) 

1212 

1213 parser = self.make_parser(ctx) 

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

1215 

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

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

1218 

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

1220 ctx.fail( 

1221 ngettext( 

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

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

1224 len(args), 

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

1226 ) 

1227 

1228 ctx.args = args 

1229 ctx._opt_prefixes.update(parser._opt_prefixes) 

1230 return args 

1231 

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

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

1234 in the right way. 

1235 """ 

1236 if self.deprecated: 

1237 extra_message = ( 

1238 f" {self.deprecated}" if isinstance(self.deprecated, str) else "" 

1239 ) 

1240 message = _( 

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

1242 ).format(name=self.name, extra_message=extra_message) 

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

1244 

1245 if self.callback is not None: 

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

1247 

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

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

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

1251 

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

1253 commands are valid at any point during command completion. 

1254 

1255 :param ctx: Invocation context for this command. 

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

1257 

1258 .. versionadded:: 8.0 

1259 """ 

1260 from click.shell_completion import CompletionItem 

1261 

1262 results: list[CompletionItem] = [] 

1263 

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

1265 for param in self.get_params(ctx): 

1266 if ( 

1267 not isinstance(param, Option) 

1268 or param.hidden 

1269 or ( 

1270 not param.multiple 

1271 and ctx.get_parameter_source(param.name) # type: ignore 

1272 is ParameterSource.COMMANDLINE 

1273 ) 

1274 ): 

1275 continue 

1276 

1277 results.extend( 

1278 CompletionItem(name, help=param.help) 

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

1280 if name.startswith(incomplete) 

1281 ) 

1282 

1283 while ctx.parent is not None: 

1284 ctx = ctx.parent 

1285 

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

1287 results.extend( 

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

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

1290 if name not in ctx._protected_args 

1291 ) 

1292 

1293 return results 

1294 

1295 @t.overload 

1296 def main( 

1297 self, 

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

1299 prog_name: str | None = None, 

1300 complete_var: str | None = None, 

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

1302 **extra: t.Any, 

1303 ) -> t.NoReturn: ... 

1304 

1305 @t.overload 

1306 def main( 

1307 self, 

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

1309 prog_name: str | None = None, 

1310 complete_var: str | None = None, 

1311 standalone_mode: bool = ..., 

1312 **extra: t.Any, 

1313 ) -> t.Any: ... 

1314 

1315 def main( 

1316 self, 

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

1318 prog_name: str | None = None, 

1319 complete_var: str | None = None, 

1320 standalone_mode: bool = True, 

1321 windows_expand_args: bool = True, 

1322 **extra: t.Any, 

1323 ) -> t.Any: 

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

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

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

1327 needs to be caught. 

1328 

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

1330 a :class:`Command`. 

1331 

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

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

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

1335 the program name is constructed by taking the file 

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

1337 :param complete_var: the environment variable that controls the 

1338 bash completion support. The default is 

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

1340 uppercase. 

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

1342 in standalone mode. Click will then 

1343 handle exceptions and convert them into 

1344 error messages and the function will never 

1345 return but shut down the interpreter. If 

1346 this is set to `False` they will be 

1347 propagated to the caller and the return 

1348 value of this function is the return value 

1349 of :meth:`invoke`. 

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

1351 env vars in command line args on Windows. 

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

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

1354 

1355 .. versionchanged:: 8.0.1 

1356 Added the ``windows_expand_args`` parameter to allow 

1357 disabling command line arg expansion on Windows. 

1358 

1359 .. versionchanged:: 8.0 

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

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

1362 

1363 .. versionchanged:: 3.0 

1364 Added the ``standalone_mode`` parameter. 

1365 """ 

1366 if args is None: 

1367 args = sys.argv[1:] 

1368 

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

1370 args = _expand_args(args) 

1371 else: 

1372 args = list(args) 

1373 

1374 if prog_name is None: 

1375 prog_name = _detect_program_name() 

1376 

1377 # Process shell completion requests and exit early. 

1378 self._main_shell_completion(extra, prog_name, complete_var) 

1379 

1380 try: 

1381 try: 

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

1383 rv = self.invoke(ctx) 

1384 if not standalone_mode: 

1385 return rv 

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

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

1388 # has obvious effects 

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

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

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

1392 # by its truthiness/falsiness 

1393 ctx.exit() 

1394 except (EOFError, KeyboardInterrupt) as e: 

1395 echo(file=sys.stderr) 

1396 raise Abort() from e 

1397 except ClickException as e: 

1398 if not standalone_mode: 

1399 raise 

1400 e.show() 

1401 sys.exit(e.exit_code) 

1402 except OSError as e: 

1403 if e.errno == errno.EPIPE: 

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

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

1406 sys.exit(1) 

1407 else: 

1408 raise 

1409 except Exit as e: 

1410 if standalone_mode: 

1411 sys.exit(e.exit_code) 

1412 else: 

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

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

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

1416 # would return its result 

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

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

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

1420 # tell the difference between the two 

1421 return e.exit_code 

1422 except Abort: 

1423 if not standalone_mode: 

1424 raise 

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

1426 sys.exit(1) 

1427 

1428 def _main_shell_completion( 

1429 self, 

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

1431 prog_name: str, 

1432 complete_var: str | None = None, 

1433 ) -> None: 

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

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

1436 program is invoked. 

1437 

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

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

1440 the completion instruction. Defaults to 

1441 ``_{PROG_NAME}_COMPLETE``. 

1442 

1443 .. versionchanged:: 8.2.0 

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

1445 """ 

1446 if complete_var is None: 

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

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

1449 

1450 instruction = os.environ.get(complete_var) 

1451 

1452 if not instruction: 

1453 return 

1454 

1455 from .shell_completion import shell_complete 

1456 

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

1458 sys.exit(rv) 

1459 

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

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

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

1463 

1464 

1465class _FakeSubclassCheck(type): 

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

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

1468 

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

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

1471 

1472 

1473class _BaseCommand(Command, metaclass=_FakeSubclassCheck): 

1474 """ 

1475 .. deprecated:: 8.2 

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

1477 """ 

1478 

1479 

1480class Group(Command): 

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

1482 

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

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

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

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

1487 subcommand is not given. 

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

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

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

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

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

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

1494 matched, and so on. 

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

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

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

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

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

1500 ``chain`` is enabled. 

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

1502 

1503 .. versionchanged:: 8.0 

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

1505 

1506 .. versionchanged:: 8.2 

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

1508 """ 

1509 

1510 allow_extra_args = True 

1511 allow_interspersed_args = False 

1512 

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

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

1515 #: subcommands use a custom command class. 

1516 #: 

1517 #: .. versionadded:: 8.0 

1518 command_class: type[Command] | None = None 

1519 

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

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

1522 #: subgroups use a custom group class. 

1523 #: 

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

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

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

1527 #: custom groups. 

1528 #: 

1529 #: .. versionadded:: 8.0 

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

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

1532 

1533 def __init__( 

1534 self, 

1535 name: str | None = None, 

1536 commands: cabc.MutableMapping[str, Command] 

1537 | cabc.Sequence[Command] 

1538 | None = None, 

1539 invoke_without_command: bool = False, 

1540 no_args_is_help: bool | None = None, 

1541 subcommand_metavar: str | None = None, 

1542 chain: bool = False, 

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

1544 **kwargs: t.Any, 

1545 ) -> None: 

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

1547 

1548 if commands is None: 

1549 commands = {} 

1550 elif isinstance(commands, abc.Sequence): 

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

1552 

1553 #: The registered subcommands by their exported names. 

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

1555 

1556 if no_args_is_help is None: 

1557 no_args_is_help = not invoke_without_command 

1558 

1559 self.no_args_is_help = no_args_is_help 

1560 self.invoke_without_command = invoke_without_command 

1561 

1562 if subcommand_metavar is None: 

1563 if chain: 

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

1565 else: 

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

1567 

1568 self.subcommand_metavar = subcommand_metavar 

1569 self.chain = chain 

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

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

1572 self._result_callback = result_callback 

1573 

1574 if self.chain: 

1575 for param in self.params: 

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

1577 raise RuntimeError( 

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

1579 ) 

1580 

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

1582 info_dict = super().to_info_dict(ctx) 

1583 commands = {} 

1584 

1585 for name in self.list_commands(ctx): 

1586 command = self.get_command(ctx, name) 

1587 

1588 if command is None: 

1589 continue 

1590 

1591 sub_ctx = ctx._make_sub_context(command) 

1592 

1593 with sub_ctx.scope(cleanup=False): 

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

1595 

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

1597 return info_dict 

1598 

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

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

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

1602 """ 

1603 name = name or cmd.name 

1604 if name is None: 

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

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

1607 self.commands[name] = cmd 

1608 

1609 @t.overload 

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

1611 

1612 @t.overload 

1613 def command( 

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

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

1616 

1617 def command( 

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

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

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

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

1622 immediately registers the created command with this group by 

1623 calling :meth:`add_command`. 

1624 

1625 To customize the command class used, set the 

1626 :attr:`command_class` attribute. 

1627 

1628 .. versionchanged:: 8.1 

1629 This decorator can be applied without parentheses. 

1630 

1631 .. versionchanged:: 8.0 

1632 Added the :attr:`command_class` attribute. 

1633 """ 

1634 from .decorators import command 

1635 

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

1637 

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

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

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

1641 ) 

1642 (func,) = args 

1643 args = () 

1644 

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

1646 kwargs["cls"] = self.command_class 

1647 

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

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

1650 self.add_command(cmd) 

1651 return cmd 

1652 

1653 if func is not None: 

1654 return decorator(func) 

1655 

1656 return decorator 

1657 

1658 @t.overload 

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

1660 

1661 @t.overload 

1662 def group( 

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

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

1665 

1666 def group( 

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

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

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

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

1671 immediately registers the created group with this group by 

1672 calling :meth:`add_command`. 

1673 

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

1675 attribute. 

1676 

1677 .. versionchanged:: 8.1 

1678 This decorator can be applied without parentheses. 

1679 

1680 .. versionchanged:: 8.0 

1681 Added the :attr:`group_class` attribute. 

1682 """ 

1683 from .decorators import group 

1684 

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

1686 

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

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

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

1690 ) 

1691 (func,) = args 

1692 args = () 

1693 

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

1695 if self.group_class is type: 

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

1697 else: 

1698 kwargs["cls"] = self.group_class 

1699 

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

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

1702 self.add_command(cmd) 

1703 return cmd 

1704 

1705 if func is not None: 

1706 return decorator(func) 

1707 

1708 return decorator 

1709 

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

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

1712 result callback is already registered this will chain them but 

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

1714 callback is invoked with the return value of the subcommand 

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

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

1717 to the main callback. 

1718 

1719 Example:: 

1720 

1721 @click.group() 

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

1723 def cli(input): 

1724 return 42 

1725 

1726 @cli.result_callback() 

1727 def process_result(result, input): 

1728 return result + input 

1729 

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

1731 callback will be removed. 

1732 

1733 .. versionchanged:: 8.0 

1734 Renamed from ``resultcallback``. 

1735 

1736 .. versionadded:: 3.0 

1737 """ 

1738 

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

1740 old_callback = self._result_callback 

1741 

1742 if old_callback is None or replace: 

1743 self._result_callback = f 

1744 return f 

1745 

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

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

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

1749 

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

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

1752 

1753 return decorator 

1754 

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

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

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

1758 """ 

1759 return self.commands.get(cmd_name) 

1760 

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

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

1763 return sorted(self.commands) 

1764 

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

1766 rv = super().collect_usage_pieces(ctx) 

1767 rv.append(self.subcommand_metavar) 

1768 return rv 

1769 

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

1771 super().format_options(ctx, formatter) 

1772 self.format_commands(ctx, formatter) 

1773 

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

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

1776 after the options. 

1777 """ 

1778 commands = [] 

1779 for subcommand in self.list_commands(ctx): 

1780 cmd = self.get_command(ctx, subcommand) 

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

1782 if cmd is None: 

1783 continue 

1784 if cmd.hidden: 

1785 continue 

1786 

1787 commands.append((subcommand, cmd)) 

1788 

1789 # allow for 3 times the default spacing 

1790 if len(commands): 

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

1792 

1793 rows = [] 

1794 for subcommand, cmd in commands: 

1795 help = cmd.get_short_help_str(limit) 

1796 rows.append((subcommand, help)) 

1797 

1798 if rows: 

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

1800 formatter.write_dl(rows) 

1801 

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

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

1804 raise NoArgsIsHelpError(ctx) 

1805 

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

1807 

1808 if self.chain: 

1809 ctx._protected_args = rest 

1810 ctx.args = [] 

1811 elif rest: 

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

1813 

1814 return ctx.args 

1815 

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

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

1818 if self._result_callback is not None: 

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

1820 return value 

1821 

1822 if not ctx._protected_args: 

1823 if self.invoke_without_command: 

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

1825 # invoked with the group return value for regular 

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

1827 with ctx: 

1828 rv = super().invoke(ctx) 

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

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

1831 

1832 # Fetch args back out 

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

1834 ctx.args = [] 

1835 ctx._protected_args = [] 

1836 

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

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

1839 # name of the command to invoke. 

1840 if not self.chain: 

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

1842 # resources until the result processor has worked. 

1843 with ctx: 

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

1845 assert cmd is not None 

1846 ctx.invoked_subcommand = cmd_name 

1847 super().invoke(ctx) 

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

1849 with sub_ctx: 

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

1851 

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

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

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

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

1856 # but nothing else. 

1857 with ctx: 

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

1859 super().invoke(ctx) 

1860 

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

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

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

1864 contexts = [] 

1865 while args: 

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

1867 assert cmd is not None 

1868 sub_ctx = cmd.make_context( 

1869 cmd_name, 

1870 args, 

1871 parent=ctx, 

1872 allow_extra_args=True, 

1873 allow_interspersed_args=False, 

1874 ) 

1875 contexts.append(sub_ctx) 

1876 args, sub_ctx.args = sub_ctx.args, [] 

1877 

1878 rv = [] 

1879 for sub_ctx in contexts: 

1880 with sub_ctx: 

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

1882 return _process_result(rv) 

1883 

1884 def resolve_command( 

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

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

1887 cmd_name = make_str(args[0]) 

1888 original_cmd_name = cmd_name 

1889 

1890 # Get the command 

1891 cmd = self.get_command(ctx, cmd_name) 

1892 

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

1894 # function available, we try with that one. 

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

1896 cmd_name = ctx.token_normalize_func(cmd_name) 

1897 cmd = self.get_command(ctx, cmd_name) 

1898 

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

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

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

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

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

1904 # place. 

1905 if cmd is None and not ctx.resilient_parsing: 

1906 if _split_opt(cmd_name)[0]: 

1907 self.parse_args(ctx, args) 

1908 ctx.fail(_("No such command {name!r}.").format(name=original_cmd_name)) 

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

1910 

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

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

1913 at the names of options, subcommands, and chained 

1914 multi-commands. 

1915 

1916 :param ctx: Invocation context for this command. 

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

1918 

1919 .. versionadded:: 8.0 

1920 """ 

1921 from click.shell_completion import CompletionItem 

1922 

1923 results = [ 

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

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

1926 ] 

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

1928 return results 

1929 

1930 

1931class _MultiCommand(Group, metaclass=_FakeSubclassCheck): 

1932 """ 

1933 .. deprecated:: 8.2 

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

1935 """ 

1936 

1937 

1938class CommandCollection(Group): 

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

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

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

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

1943 commands in many groups into this one group. 

1944 

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

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

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

1948 

1949 .. versionchanged:: 8.2 

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

1951 group, then each of its sources. 

1952 """ 

1953 

1954 def __init__( 

1955 self, 

1956 name: str | None = None, 

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

1958 **kwargs: t.Any, 

1959 ) -> None: 

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

1961 #: The list of registered groups. 

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

1963 

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

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

1966 self.sources.append(group) 

1967 

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

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

1970 

1971 if rv is not None: 

1972 return rv 

1973 

1974 for source in self.sources: 

1975 rv = source.get_command(ctx, cmd_name) 

1976 

1977 if rv is not None: 

1978 if self.chain: 

1979 _check_nested_chain(self, cmd_name, rv) 

1980 

1981 return rv 

1982 

1983 return None 

1984 

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

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

1987 

1988 for source in self.sources: 

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

1990 

1991 return sorted(rv) 

1992 

1993 

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

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

1996 error, or return an iterator over the value. 

1997 """ 

1998 if isinstance(value, str): 

1999 raise TypeError 

2000 

2001 return iter(value) 

2002 

2003 

2004class Parameter: 

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

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

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

2008 intentionally not finalized. 

2009 

2010 Some settings are supported by both options and arguments. 

2011 

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

2013 argument. This is a list of flags or argument 

2014 names. 

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

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

2017 automatically if supported. 

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

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

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

2021 without any arguments. 

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

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

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

2025 including prompts. 

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

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

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

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

2030 parameters are collected. 

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

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

2033 to the command callback and stored on the context, 

2034 otherwise it's skipped. 

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

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

2037 order of processing. 

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

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

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

2041 :param shell_complete: A function that returns custom shell 

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

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

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

2045 strings. 

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

2047 indicating that the argument is deprecated and highlights 

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

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

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

2051 

2052 .. versionchanged:: 8.2.0 

2053 Introduction of ``deprecated``. 

2054 

2055 .. versionchanged:: 8.2 

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

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

2058 

2059 .. versionchanged:: 8.2 

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

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

2062 

2063 .. versionchanged:: 8.0 

2064 ``process_value`` validates required parameters and bounded 

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

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

2067 ``full_process_value`` is removed. 

2068 

2069 .. versionchanged:: 8.0 

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

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

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

2073 new requirements. 

2074 

2075 .. versionchanged:: 8.0 

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

2077 tuples. 

2078 

2079 .. versionchanged:: 8.0 

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

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

2082 default to ``()``. 

2083 

2084 .. versionchanged:: 7.1 

2085 Empty environment variables are ignored rather than taking the 

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

2087 variables if they can't unset them. 

2088 

2089 .. versionchanged:: 2.0 

2090 Changed signature for parameter callback to also be passed the 

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

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

2093 """ 

2094 

2095 param_type_name = "parameter" 

2096 

2097 def __init__( 

2098 self, 

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

2100 type: types.ParamType | t.Any | None = None, 

2101 required: bool = False, 

2102 # XXX The default historically embed two concepts: 

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

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

2105 # self.name, like flag options), 

2106 # - and the actual value of the default. 

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

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

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

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

2111 # Parameter.is_default and Parameter.default_value. 

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

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

2114 nargs: int | None = None, 

2115 multiple: bool = False, 

2116 metavar: str | None = None, 

2117 expose_value: bool = True, 

2118 is_eager: bool = False, 

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

2120 shell_complete: t.Callable[ 

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

2122 ] 

2123 | None = None, 

2124 deprecated: bool | str = False, 

2125 ) -> None: 

2126 self.name: str | None 

2127 self.opts: list[str] 

2128 self.secondary_opts: list[str] 

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

2130 param_decls or (), expose_value 

2131 ) 

2132 self.type: types.ParamType = types.convert_type(type, default) 

2133 

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

2135 # information available. 

2136 if nargs is None: 

2137 if self.type.is_composite: 

2138 nargs = self.type.arity 

2139 else: 

2140 nargs = 1 

2141 

2142 self.required = required 

2143 self.callback = callback 

2144 self.nargs = nargs 

2145 self.multiple = multiple 

2146 self.expose_value = expose_value 

2147 self.default = default 

2148 self.is_eager = is_eager 

2149 self.metavar = metavar 

2150 self.envvar = envvar 

2151 self._custom_shell_complete = shell_complete 

2152 self.deprecated = deprecated 

2153 

2154 if __debug__: 

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

2156 raise ValueError( 

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

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

2159 ) 

2160 

2161 if required and deprecated: 

2162 raise ValueError( 

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

2164 "is deprecated and still required. A deprecated " 

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

2166 ) 

2167 

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

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

2170 user-facing documentation. 

2171 

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

2173 CLI structure. 

2174 

2175 .. versionchanged:: 8.3.0 

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

2177 

2178 .. versionadded:: 8.0 

2179 """ 

2180 return { 

2181 "name": self.name, 

2182 "param_type_name": self.param_type_name, 

2183 "opts": self.opts, 

2184 "secondary_opts": self.secondary_opts, 

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

2186 "required": self.required, 

2187 "nargs": self.nargs, 

2188 "multiple": self.multiple, 

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

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

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

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

2193 "envvar": self.envvar, 

2194 } 

2195 

2196 def __repr__(self) -> str: 

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

2198 

2199 def _parse_decls( 

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

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

2202 raise NotImplementedError() 

2203 

2204 @property 

2205 def human_readable_name(self) -> str: 

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

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

2208 """ 

2209 return self.name # type: ignore 

2210 

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

2212 if self.metavar is not None: 

2213 return self.metavar 

2214 

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

2216 

2217 if metavar is None: 

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

2219 

2220 if self.nargs != 1: 

2221 metavar += "..." 

2222 

2223 return metavar 

2224 

2225 @t.overload 

2226 def get_default( 

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

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

2229 

2230 @t.overload 

2231 def get_default( 

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

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

2234 

2235 def get_default( 

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

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

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

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

2240 

2241 :param ctx: Current context. 

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

2243 return the callable instead. 

2244 

2245 .. versionchanged:: 8.0.2 

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

2247 

2248 .. versionchanged:: 8.0.1 

2249 Type casting can fail in resilient parsing mode. Invalid 

2250 defaults will not prevent showing help text. 

2251 

2252 .. versionchanged:: 8.0 

2253 Looks at ``ctx.default_map`` first. 

2254 

2255 .. versionchanged:: 8.0 

2256 Added the ``call`` parameter. 

2257 """ 

2258 value = ctx.lookup_default(self.name, call=False) # type: ignore 

2259 

2260 if value is UNSET: 

2261 value = self.default 

2262 

2263 if call and callable(value): 

2264 value = value() 

2265 

2266 return value 

2267 

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

2269 raise NotImplementedError() 

2270 

2271 def consume_value( 

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

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

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

2275 

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

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

2278 default value. In that order of precedence. 

2279 

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

2281 

2282 :meta private: 

2283 """ 

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

2285 value = opts.get(self.name, UNSET) # type: ignore 

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

2287 # parser, otherwise it left unset by default. 

2288 source = ( 

2289 ParameterSource.COMMANDLINE 

2290 if value is not UNSET 

2291 else ParameterSource.DEFAULT 

2292 ) 

2293 

2294 if value is UNSET: 

2295 envvar_value = self.value_from_envvar(ctx) 

2296 if envvar_value is not None: 

2297 value = envvar_value 

2298 source = ParameterSource.ENVIRONMENT 

2299 

2300 if value is UNSET: 

2301 default_map_value = ctx.lookup_default(self.name) # type: ignore 

2302 if default_map_value is not UNSET: 

2303 value = default_map_value 

2304 source = ParameterSource.DEFAULT_MAP 

2305 

2306 if value is UNSET: 

2307 default_value = self.get_default(ctx) 

2308 if default_value is not UNSET: 

2309 value = default_value 

2310 source = ParameterSource.DEFAULT 

2311 

2312 return value, source 

2313 

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

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

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

2317 """ 

2318 if value in (None, UNSET): 

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

2320 return () 

2321 else: 

2322 return value 

2323 

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

2325 try: 

2326 return _check_iter(value) 

2327 except TypeError: 

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

2329 # the parser should construct an iterable when parsing 

2330 # the command line. 

2331 raise BadParameter( 

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

2333 ) from None 

2334 

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

2336 

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

2338 

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

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

2341 

2342 elif self.nargs == -1: 

2343 

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

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

2346 

2347 else: # nargs > 1 

2348 

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

2350 value = tuple(check_iter(value)) 

2351 

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

2353 raise BadParameter( 

2354 ngettext( 

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

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

2357 len(value), 

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

2359 ctx=ctx, 

2360 param=self, 

2361 ) 

2362 

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

2364 

2365 if self.multiple: 

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

2367 

2368 return convert(value) 

2369 

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

2371 """A value is considered missing if: 

2372 

2373 - it is :attr:`UNSET`, 

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

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

2376 set). 

2377 

2378 :meta private: 

2379 """ 

2380 if value is UNSET: 

2381 return True 

2382 

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

2384 return True 

2385 

2386 return False 

2387 

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

2389 """Process the value of this parameter: 

2390 

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

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

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

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

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

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

2397 the :attr:`UNSET` sentinel. 

2398 

2399 :meta private: 

2400 """ 

2401 value = self.type_cast_value(ctx, value) 

2402 

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

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

2405 

2406 if self.callback is not None: 

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

2408 # to None. 

2409 if value is UNSET: 

2410 value = None 

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

2412 

2413 return value 

2414 

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

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

2417 parameter. 

2418 

2419 Environment variables values are `always returned as strings 

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

2421 

2422 This method returns ``None`` if: 

2423 

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

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

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

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

2428 

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

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

2431 

2432 .. caution:: 

2433 

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

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

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

2437 

2438 :meta private: 

2439 """ 

2440 if not self.envvar: 

2441 return None 

2442 

2443 if isinstance(self.envvar, str): 

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

2445 

2446 if rv: 

2447 return rv 

2448 else: 

2449 for envvar in self.envvar: 

2450 rv = os.environ.get(envvar) 

2451 

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

2453 if rv: 

2454 return rv 

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

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

2457 

2458 return None 

2459 

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

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

2462 

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

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

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

2466 

2467 :meta private: 

2468 """ 

2469 rv = self.resolve_envvar_value(ctx) 

2470 

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

2472 return self.type.split_envvar_value(rv) 

2473 

2474 return rv 

2475 

2476 def handle_parse_result( 

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

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

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

2480 

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

2482 comes from. 

2483 

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

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

2486 a default). 

2487 

2488 :meta private: 

2489 """ 

2490 with augment_usage_errors(ctx, param=self): 

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

2492 

2493 ctx.set_parameter_source(self.name, source) # type: ignore 

2494 

2495 # Display a deprecation warning if necessary. 

2496 if ( 

2497 self.deprecated 

2498 and value is not UNSET 

2499 and source not in (ParameterSource.DEFAULT, ParameterSource.DEFAULT_MAP) 

2500 ): 

2501 extra_message = ( 

2502 f" {self.deprecated}" if isinstance(self.deprecated, str) else "" 

2503 ) 

2504 message = _( 

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

2506 "{extra_message}" 

2507 ).format( 

2508 param_type=self.param_type_name, 

2509 name=self.human_readable_name, 

2510 extra_message=extra_message, 

2511 ) 

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

2513 

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

2515 try: 

2516 value = self.process_value(ctx, value) 

2517 except Exception: 

2518 if not ctx.resilient_parsing: 

2519 raise 

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

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

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

2523 value = UNSET 

2524 

2525 # Add parameter's value to the context. 

2526 if ( 

2527 self.expose_value 

2528 # We skip adding the value if it was previously set by another parameter 

2529 # targeting the same variable name. This prevents parameters competing for 

2530 # the same name to override each other. 

2531 and self.name not in ctx.params 

2532 ): 

2533 # Click is logically enforcing that the name is None if the parameter is 

2534 # not to be exposed. We still assert it here to please the type checker. 

2535 assert self.name is not None, ( 

2536 f"{self!r} parameter's name should not be None when exposing value." 

2537 ) 

2538 # Normalize UNSET values to None, as we're about to pass them to the 

2539 # command function and move them to the pure-Python realm of user-written 

2540 # code. 

2541 ctx.params[self.name] = value if value is not UNSET else None 

2542 

2543 return value, args 

2544 

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

2546 pass 

2547 

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

2549 return [] 

2550 

2551 def get_error_hint(self, ctx: Context) -> str: 

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

2553 indicate which param caused the error. 

2554 """ 

2555 hint_list = self.opts or [self.human_readable_name] 

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

2557 

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

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

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

2561 Otherwise, the :attr:`type` 

2562 :meth:`~click.types.ParamType.shell_complete` function is used. 

2563 

2564 :param ctx: Invocation context for this command. 

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

2566 

2567 .. versionadded:: 8.0 

2568 """ 

2569 if self._custom_shell_complete is not None: 

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

2571 

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

2573 from click.shell_completion import CompletionItem 

2574 

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

2576 

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

2578 

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

2580 

2581 

2582class Option(Parameter): 

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

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

2585 

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

2587 

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

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

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

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

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

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

2594 its value is ``False``. 

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

2596 shown on the help page and error messages. 

2597 Normally, environment variables are not shown. 

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

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

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

2601 prompted. 

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

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

2604 ``True`` to customize the message. 

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

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

2607 without a value. 

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

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

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

2611 auto detection. 

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

2613 enabled. This is set to a boolean automatically if 

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

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

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

2617 in how it works but supports arbitrary number of 

2618 arguments. 

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

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

2621 parameter will be pulled from an environment 

2622 variable in case a prefix is defined on the 

2623 context. 

2624 :param help: the help string. 

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

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

2627 

2628 .. versionchanged:: 8.2 

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

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

2631 

2632 .. versionchanged:: 8.1 

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

2634 ``@option`` decorator. 

2635 

2636 .. versionchanged:: 8.1 

2637 The ``show_default`` parameter overrides 

2638 ``Context.show_default``. 

2639 

2640 .. versionchanged:: 8.1 

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

2642 default value is ``False``. 

2643 

2644 .. versionchanged:: 8.0.1 

2645 ``type`` is detected from ``flag_value`` if given. 

2646 """ 

2647 

2648 param_type_name = "option" 

2649 

2650 def __init__( 

2651 self, 

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

2653 show_default: bool | str | None = None, 

2654 prompt: bool | str = False, 

2655 confirmation_prompt: bool | str = False, 

2656 prompt_required: bool = True, 

2657 hide_input: bool = False, 

2658 is_flag: bool | None = None, 

2659 flag_value: t.Any = UNSET, 

2660 multiple: bool = False, 

2661 count: bool = False, 

2662 allow_from_autoenv: bool = True, 

2663 type: types.ParamType | t.Any | None = None, 

2664 help: str | None = None, 

2665 hidden: bool = False, 

2666 show_choices: bool = True, 

2667 show_envvar: bool = False, 

2668 deprecated: bool | str = False, 

2669 **attrs: t.Any, 

2670 ) -> None: 

2671 if help: 

2672 help = inspect.cleandoc(help) 

2673 

2674 super().__init__( 

2675 param_decls, type=type, multiple=multiple, deprecated=deprecated, **attrs 

2676 ) 

2677 

2678 if prompt is True: 

2679 if self.name is None: 

2680 raise TypeError("'name' is required with 'prompt=True'.") 

2681 

2682 prompt_text: str | None = self.name.replace("_", " ").capitalize() 

2683 elif prompt is False: 

2684 prompt_text = None 

2685 else: 

2686 prompt_text = prompt 

2687 

2688 if deprecated: 

2689 deprecated_message = ( 

2690 f"(DEPRECATED: {deprecated})" 

2691 if isinstance(deprecated, str) 

2692 else "(DEPRECATED)" 

2693 ) 

2694 help = help + deprecated_message if help is not None else deprecated_message 

2695 

2696 self.prompt = prompt_text 

2697 self.confirmation_prompt = confirmation_prompt 

2698 self.prompt_required = prompt_required 

2699 self.hide_input = hide_input 

2700 self.hidden = hidden 

2701 

2702 # The _flag_needs_value property tells the parser that this option is a flag 

2703 # that cannot be used standalone and needs a value. With this information, the 

2704 # parser can determine whether to consider the next user-provided argument in 

2705 # the CLI as a value for this flag or as a new option. 

2706 # If prompt is enabled but not required, then it opens the possibility for the 

2707 # option to gets its value from the user. 

2708 self._flag_needs_value = self.prompt is not None and not self.prompt_required 

2709 

2710 # Auto-detect if this is a flag or not. 

2711 if is_flag is None: 

2712 # Implicitly a flag because flag_value was set. 

2713 if flag_value is not UNSET: 

2714 is_flag = True 

2715 # Not a flag, but when used as a flag it shows a prompt. 

2716 elif self._flag_needs_value: 

2717 is_flag = False 

2718 # Implicitly a flag because secondary options names were given. 

2719 elif self.secondary_opts: 

2720 is_flag = True 

2721 # The option is explicitly not a flag. But we do not know yet if it needs a 

2722 # value or not. So we look at the default value to determine it. 

2723 elif is_flag is False and not self._flag_needs_value: 

2724 self._flag_needs_value = self.default is UNSET 

2725 

2726 if is_flag: 

2727 # Set missing default for flags if not explicitly required or prompted. 

2728 if self.default is UNSET and not self.required and not self.prompt: 

2729 if multiple: 

2730 self.default = () 

2731 

2732 # Auto-detect the type of the flag based on the flag_value. 

2733 if type is None: 

2734 # A flag without a flag_value is a boolean flag. 

2735 if flag_value is UNSET: 

2736 self.type = types.BoolParamType() 

2737 # If the flag value is a boolean, use BoolParamType. 

2738 elif isinstance(flag_value, bool): 

2739 self.type = types.BoolParamType() 

2740 # Otherwise, guess the type from the flag value. 

2741 else: 

2742 self.type = types.convert_type(None, flag_value) 

2743 

2744 self.is_flag: bool = bool(is_flag) 

2745 self.is_bool_flag: bool = bool( 

2746 is_flag and isinstance(self.type, types.BoolParamType) 

2747 ) 

2748 self.flag_value: t.Any = flag_value 

2749 

2750 # Set boolean flag default to False if unset and not required. 

2751 if self.is_bool_flag: 

2752 if self.default is UNSET and not self.required: 

2753 self.default = False 

2754 

2755 # Support the special case of aligning the default value with the flag_value 

2756 # for flags whose default is explicitly set to True. Note that as long as we 

2757 # have this condition, there is no way a flag can have a default set to True, 

2758 # and a flag_value set to something else. Refs: 

2759 # https://github.com/pallets/click/issues/3024#issuecomment-3146199461 

2760 # https://github.com/pallets/click/pull/3030/commits/06847da 

2761 if self.default is True and self.flag_value is not UNSET: 

2762 self.default = self.flag_value 

2763 

2764 # Set the default flag_value if it is not set. 

2765 if self.flag_value is UNSET: 

2766 if self.is_flag: 

2767 self.flag_value = True 

2768 else: 

2769 self.flag_value = None 

2770 

2771 # Counting. 

2772 self.count = count 

2773 if count: 

2774 if type is None: 

2775 self.type = types.IntRange(min=0) 

2776 if self.default is UNSET: 

2777 self.default = 0 

2778 

2779 self.allow_from_autoenv = allow_from_autoenv 

2780 self.help = help 

2781 self.show_default = show_default 

2782 self.show_choices = show_choices 

2783 self.show_envvar = show_envvar 

2784 

2785 if __debug__: 

2786 if deprecated and prompt: 

2787 raise ValueError("`deprecated` options cannot use `prompt`.") 

2788 

2789 if self.nargs == -1: 

2790 raise TypeError("nargs=-1 is not supported for options.") 

2791 

2792 if not self.is_bool_flag and self.secondary_opts: 

2793 raise TypeError("Secondary flag is not valid for non-boolean flag.") 

2794 

2795 if self.is_bool_flag and self.hide_input and self.prompt is not None: 

2796 raise TypeError( 

2797 "'prompt' with 'hide_input' is not valid for boolean flag." 

2798 ) 

2799 

2800 if self.count: 

2801 if self.multiple: 

2802 raise TypeError("'count' is not valid with 'multiple'.") 

2803 

2804 if self.is_flag: 

2805 raise TypeError("'count' is not valid with 'is_flag'.") 

2806 

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

2808 """ 

2809 .. versionchanged:: 8.3.0 

2810 Returns ``None`` for the :attr:`flag_value` if it was not set. 

2811 """ 

2812 info_dict = super().to_info_dict() 

2813 info_dict.update( 

2814 help=self.help, 

2815 prompt=self.prompt, 

2816 is_flag=self.is_flag, 

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

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

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

2820 flag_value=self.flag_value if self.flag_value is not UNSET else None, 

2821 count=self.count, 

2822 hidden=self.hidden, 

2823 ) 

2824 return info_dict 

2825 

2826 def get_error_hint(self, ctx: Context) -> str: 

2827 result = super().get_error_hint(ctx) 

2828 if self.show_envvar and self.envvar is not None: 

2829 result += f" (env var: '{self.envvar}')" 

2830 return result 

2831 

2832 def _parse_decls( 

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

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

2835 opts = [] 

2836 secondary_opts = [] 

2837 name = None 

2838 possible_names = [] 

2839 

2840 for decl in decls: 

2841 if decl.isidentifier(): 

2842 if name is not None: 

2843 raise TypeError(f"Name '{name}' defined twice") 

2844 name = decl 

2845 else: 

2846 split_char = ";" if decl[:1] == "/" else "/" 

2847 if split_char in decl: 

2848 first, second = decl.split(split_char, 1) 

2849 first = first.rstrip() 

2850 if first: 

2851 possible_names.append(_split_opt(first)) 

2852 opts.append(first) 

2853 second = second.lstrip() 

2854 if second: 

2855 secondary_opts.append(second.lstrip()) 

2856 if first == second: 

2857 raise ValueError( 

2858 f"Boolean option {decl!r} cannot use the" 

2859 " same flag for true/false." 

2860 ) 

2861 else: 

2862 possible_names.append(_split_opt(decl)) 

2863 opts.append(decl) 

2864 

2865 if name is None and possible_names: 

2866 possible_names.sort(key=lambda x: -len(x[0])) # group long options first 

2867 name = possible_names[0][1].replace("-", "_").lower() 

2868 if not name.isidentifier(): 

2869 name = None 

2870 

2871 if name is None: 

2872 if not expose_value: 

2873 return None, opts, secondary_opts 

2874 raise TypeError( 

2875 f"Could not determine name for option with declarations {decls!r}" 

2876 ) 

2877 

2878 if not opts and not secondary_opts: 

2879 raise TypeError( 

2880 f"No options defined but a name was passed ({name})." 

2881 " Did you mean to declare an argument instead? Did" 

2882 f" you mean to pass '--{name}'?" 

2883 ) 

2884 

2885 return name, opts, secondary_opts 

2886 

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

2888 if self.multiple: 

2889 action = "append" 

2890 elif self.count: 

2891 action = "count" 

2892 else: 

2893 action = "store" 

2894 

2895 if self.is_flag: 

2896 action = f"{action}_const" 

2897 

2898 if self.is_bool_flag and self.secondary_opts: 

2899 parser.add_option( 

2900 obj=self, opts=self.opts, dest=self.name, action=action, const=True 

2901 ) 

2902 parser.add_option( 

2903 obj=self, 

2904 opts=self.secondary_opts, 

2905 dest=self.name, 

2906 action=action, 

2907 const=False, 

2908 ) 

2909 else: 

2910 parser.add_option( 

2911 obj=self, 

2912 opts=self.opts, 

2913 dest=self.name, 

2914 action=action, 

2915 const=self.flag_value, 

2916 ) 

2917 else: 

2918 parser.add_option( 

2919 obj=self, 

2920 opts=self.opts, 

2921 dest=self.name, 

2922 action=action, 

2923 nargs=self.nargs, 

2924 ) 

2925 

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

2927 if self.hidden: 

2928 return None 

2929 

2930 any_prefix_is_slash = False 

2931 

2932 def _write_opts(opts: cabc.Sequence[str]) -> str: 

2933 nonlocal any_prefix_is_slash 

2934 

2935 rv, any_slashes = join_options(opts) 

2936 

2937 if any_slashes: 

2938 any_prefix_is_slash = True 

2939 

2940 if not self.is_flag and not self.count: 

2941 rv += f" {self.make_metavar(ctx=ctx)}" 

2942 

2943 return rv 

2944 

2945 rv = [_write_opts(self.opts)] 

2946 

2947 if self.secondary_opts: 

2948 rv.append(_write_opts(self.secondary_opts)) 

2949 

2950 help = self.help or "" 

2951 

2952 extra = self.get_help_extra(ctx) 

2953 extra_items = [] 

2954 if "envvars" in extra: 

2955 extra_items.append( 

2956 _("env var: {var}").format(var=", ".join(extra["envvars"])) 

2957 ) 

2958 if "default" in extra: 

2959 extra_items.append(_("default: {default}").format(default=extra["default"])) 

2960 if "range" in extra: 

2961 extra_items.append(extra["range"]) 

2962 if "required" in extra: 

2963 extra_items.append(_(extra["required"])) 

2964 

2965 if extra_items: 

2966 extra_str = "; ".join(extra_items) 

2967 help = f"{help} [{extra_str}]" if help else f"[{extra_str}]" 

2968 

2969 return ("; " if any_prefix_is_slash else " / ").join(rv), help 

2970 

2971 def get_help_extra(self, ctx: Context) -> types.OptionHelpExtra: 

2972 extra: types.OptionHelpExtra = {} 

2973 

2974 if self.show_envvar: 

2975 envvar = self.envvar 

2976 

2977 if envvar is None: 

2978 if ( 

2979 self.allow_from_autoenv 

2980 and ctx.auto_envvar_prefix is not None 

2981 and self.name is not None 

2982 ): 

2983 envvar = f"{ctx.auto_envvar_prefix}_{self.name.upper()}" 

2984 

2985 if envvar is not None: 

2986 if isinstance(envvar, str): 

2987 extra["envvars"] = (envvar,) 

2988 else: 

2989 extra["envvars"] = tuple(str(d) for d in envvar) 

2990 

2991 # Temporarily enable resilient parsing to avoid type casting 

2992 # failing for the default. Might be possible to extend this to 

2993 # help formatting in general. 

2994 resilient = ctx.resilient_parsing 

2995 ctx.resilient_parsing = True 

2996 

2997 try: 

2998 default_value = self.get_default(ctx, call=False) 

2999 finally: 

3000 ctx.resilient_parsing = resilient 

3001 

3002 show_default = False 

3003 show_default_is_str = False 

3004 

3005 if self.show_default is not None: 

3006 if isinstance(self.show_default, str): 

3007 show_default_is_str = show_default = True 

3008 else: 

3009 show_default = self.show_default 

3010 elif ctx.show_default is not None: 

3011 show_default = ctx.show_default 

3012 

3013 if show_default_is_str or ( 

3014 show_default and (default_value not in (None, UNSET)) 

3015 ): 

3016 if show_default_is_str: 

3017 default_string = f"({self.show_default})" 

3018 elif isinstance(default_value, (list, tuple)): 

3019 default_string = ", ".join(str(d) for d in default_value) 

3020 elif isinstance(default_value, enum.Enum): 

3021 default_string = default_value.name 

3022 elif inspect.isfunction(default_value): 

3023 default_string = _("(dynamic)") 

3024 elif self.is_bool_flag and self.secondary_opts: 

3025 # For boolean flags that have distinct True/False opts, 

3026 # use the opt without prefix instead of the value. 

3027 default_string = _split_opt( 

3028 (self.opts if default_value else self.secondary_opts)[0] 

3029 )[1] 

3030 elif self.is_bool_flag and not self.secondary_opts and not default_value: 

3031 default_string = "" 

3032 elif default_value == "": 

3033 default_string = '""' 

3034 else: 

3035 default_string = str(default_value) 

3036 

3037 if default_string: 

3038 extra["default"] = default_string 

3039 

3040 if ( 

3041 isinstance(self.type, types._NumberRangeBase) 

3042 # skip count with default range type 

3043 and not (self.count and self.type.min == 0 and self.type.max is None) 

3044 ): 

3045 range_str = self.type._describe_range() 

3046 

3047 if range_str: 

3048 extra["range"] = range_str 

3049 

3050 if self.required: 

3051 extra["required"] = "required" 

3052 

3053 return extra 

3054 

3055 def prompt_for_value(self, ctx: Context) -> t.Any: 

3056 """This is an alternative flow that can be activated in the full 

3057 value processing if a value does not exist. It will prompt the 

3058 user until a valid value exists and then returns the processed 

3059 value as result. 

3060 """ 

3061 assert self.prompt is not None 

3062 

3063 # Calculate the default before prompting anything to lock in the value before 

3064 # attempting any user interaction. 

3065 default = self.get_default(ctx) 

3066 

3067 # A boolean flag can use a simplified [y/n] confirmation prompt. 

3068 if self.is_bool_flag: 

3069 # If we have no boolean default, we force the user to explicitly provide 

3070 # one. 

3071 if default in (UNSET, None): 

3072 default = None 

3073 # Nothing prevent you to declare an option that is simultaneously: 

3074 # 1) auto-detected as a boolean flag, 

3075 # 2) allowed to prompt, and 

3076 # 3) still declare a non-boolean default. 

3077 # This forced casting into a boolean is necessary to align any non-boolean 

3078 # default to the prompt, which is going to be a [y/n]-style confirmation 

3079 # because the option is still a boolean flag. That way, instead of [y/n], 

3080 # we get [Y/n] or [y/N] depending on the truthy value of the default. 

3081 # Refs: https://github.com/pallets/click/pull/3030#discussion_r2289180249 

3082 else: 

3083 default = bool(default) 

3084 return confirm(self.prompt, default) 

3085 

3086 # If show_default is set to True/False, provide this to `prompt` as well. For 

3087 # non-bool values of `show_default`, we use `prompt`'s default behavior 

3088 prompt_kwargs: t.Any = {} 

3089 if isinstance(self.show_default, bool): 

3090 prompt_kwargs["show_default"] = self.show_default 

3091 

3092 return prompt( 

3093 self.prompt, 

3094 # Use ``None`` to inform the prompt() function to reiterate until a valid 

3095 # value is provided by the user if we have no default. 

3096 default=None if default is UNSET else default, 

3097 type=self.type, 

3098 hide_input=self.hide_input, 

3099 show_choices=self.show_choices, 

3100 confirmation_prompt=self.confirmation_prompt, 

3101 value_proc=lambda x: self.process_value(ctx, x), 

3102 **prompt_kwargs, 

3103 ) 

3104 

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

3106 """:class:`Option` resolves its environment variable the same way as 

3107 :func:`Parameter.resolve_envvar_value`, but it also supports 

3108 :attr:`Context.auto_envvar_prefix`. If we could not find an environment from 

3109 the :attr:`envvar` property, we fallback on :attr:`Context.auto_envvar_prefix` 

3110 to build dynamiccaly the environment variable name using the 

3111 :python:`{ctx.auto_envvar_prefix}_{self.name.upper()}` template. 

3112 

3113 :meta private: 

3114 """ 

3115 rv = super().resolve_envvar_value(ctx) 

3116 

3117 if rv is not None: 

3118 return rv 

3119 

3120 if ( 

3121 self.allow_from_autoenv 

3122 and ctx.auto_envvar_prefix is not None 

3123 and self.name is not None 

3124 ): 

3125 envvar = f"{ctx.auto_envvar_prefix}_{self.name.upper()}" 

3126 rv = os.environ.get(envvar) 

3127 

3128 if rv: 

3129 return rv 

3130 

3131 return None 

3132 

3133 def value_from_envvar(self, ctx: Context) -> t.Any: 

3134 """For :class:`Option`, this method processes the raw environment variable 

3135 string the same way as :func:`Parameter.value_from_envvar` does. 

3136 

3137 But in the case of non-boolean flags, the value is analyzed to determine if the 

3138 flag is activated or not, and returns a boolean of its activation, or the 

3139 :attr:`flag_value` if the latter is set. 

3140 

3141 This method also takes care of repeated options (i.e. options with 

3142 :attr:`multiple` set to ``True``). 

3143 

3144 :meta private: 

3145 """ 

3146 rv = self.resolve_envvar_value(ctx) 

3147 

3148 # Absent environment variable or an empty string is interpreted as unset. 

3149 if rv is None: 

3150 return None 

3151 

3152 # Non-boolean flags are more liberal in what they accept. But a flag being a 

3153 # flag, its envvar value still needs to be analyzed to determine if the flag is 

3154 # activated or not. 

3155 if self.is_flag and not self.is_bool_flag: 

3156 # If the flag_value is set and match the envvar value, return it 

3157 # directly. 

3158 if self.flag_value is not UNSET and rv == self.flag_value: 

3159 return self.flag_value 

3160 # Analyze the envvar value as a boolean to know if the flag is 

3161 # activated or not. 

3162 return types.BoolParamType.str_to_bool(rv) 

3163 

3164 # Split the envvar value if it is allowed to be repeated. 

3165 value_depth = (self.nargs != 1) + bool(self.multiple) 

3166 if value_depth > 0: 

3167 multi_rv = self.type.split_envvar_value(rv) 

3168 if self.multiple and self.nargs != 1: 

3169 multi_rv = batch(multi_rv, self.nargs) # type: ignore[assignment] 

3170 

3171 return multi_rv 

3172 

3173 return rv 

3174 

3175 def consume_value( 

3176 self, ctx: Context, opts: cabc.Mapping[str, Parameter] 

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

3178 """For :class:`Option`, the value can be collected from an interactive prompt 

3179 if the option is a flag that needs a value (and the :attr:`prompt` property is 

3180 set). 

3181 

3182 Additionally, this method handles flag option that are activated without a 

3183 value, in which case the :attr:`flag_value` is returned. 

3184 

3185 :meta private: 

3186 """ 

3187 value, source = super().consume_value(ctx, opts) 

3188 

3189 # The parser will emit a sentinel value if the option is allowed to as a flag 

3190 # without a value. 

3191 if value is FLAG_NEEDS_VALUE: 

3192 # If the option allows for a prompt, we start an interaction with the user. 

3193 if self.prompt is not None and not ctx.resilient_parsing: 

3194 value = self.prompt_for_value(ctx) 

3195 source = ParameterSource.PROMPT 

3196 # Else the flag takes its flag_value as value. 

3197 else: 

3198 value = self.flag_value 

3199 source = ParameterSource.COMMANDLINE 

3200 

3201 # A flag which is activated always returns the flag value, unless the value 

3202 # comes from the explicitly sets default. 

3203 elif ( 

3204 self.is_flag 

3205 and value is True 

3206 and not self.is_bool_flag 

3207 and source not in (ParameterSource.DEFAULT, ParameterSource.DEFAULT_MAP) 

3208 ): 

3209 value = self.flag_value 

3210 

3211 # Re-interpret a multiple option which has been sent as-is by the parser. 

3212 # Here we replace each occurrence of value-less flags (marked by the 

3213 # FLAG_NEEDS_VALUE sentinel) with the flag_value. 

3214 elif ( 

3215 self.multiple 

3216 and value is not UNSET 

3217 and source not in (ParameterSource.DEFAULT, ParameterSource.DEFAULT_MAP) 

3218 and any(v is FLAG_NEEDS_VALUE for v in value) 

3219 ): 

3220 value = [self.flag_value if v is FLAG_NEEDS_VALUE else v for v in value] 

3221 source = ParameterSource.COMMANDLINE 

3222 

3223 # The value wasn't set, or used the param's default, prompt for one to the user 

3224 # if prompting is enabled. 

3225 elif ( 

3226 ( 

3227 value is UNSET 

3228 or source in (ParameterSource.DEFAULT, ParameterSource.DEFAULT_MAP) 

3229 ) 

3230 and self.prompt is not None 

3231 and (self.required or self.prompt_required) 

3232 and not ctx.resilient_parsing 

3233 ): 

3234 value = self.prompt_for_value(ctx) 

3235 source = ParameterSource.PROMPT 

3236 

3237 return value, source 

3238 

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

3240 if self.is_flag and not self.required: 

3241 if value is UNSET: 

3242 if self.is_bool_flag: 

3243 # If the flag is a boolean flag, we return False if it is not set. 

3244 value = False 

3245 return super().type_cast_value(ctx, value) 

3246 

3247 

3248class Argument(Parameter): 

3249 """Arguments are positional parameters to a command. They generally 

3250 provide fewer features than options but can have infinite ``nargs`` 

3251 and are required by default. 

3252 

3253 All parameters are passed onwards to the constructor of :class:`Parameter`. 

3254 """ 

3255 

3256 param_type_name = "argument" 

3257 

3258 def __init__( 

3259 self, 

3260 param_decls: cabc.Sequence[str], 

3261 required: bool | None = None, 

3262 **attrs: t.Any, 

3263 ) -> None: 

3264 # Auto-detect the requirement status of the argument if not explicitly set. 

3265 if required is None: 

3266 # The argument gets automatically required if it has no explicit default 

3267 # value set and is setup to match at least one value. 

3268 if attrs.get("default", UNSET) is UNSET: 

3269 required = attrs.get("nargs", 1) > 0 

3270 # If the argument has a default value, it is not required. 

3271 else: 

3272 required = False 

3273 

3274 if "multiple" in attrs: 

3275 raise TypeError("__init__() got an unexpected keyword argument 'multiple'.") 

3276 

3277 super().__init__(param_decls, required=required, **attrs) 

3278 

3279 @property 

3280 def human_readable_name(self) -> str: 

3281 if self.metavar is not None: 

3282 return self.metavar 

3283 return self.name.upper() # type: ignore 

3284 

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

3286 if self.metavar is not None: 

3287 return self.metavar 

3288 var = self.type.get_metavar(param=self, ctx=ctx) 

3289 if not var: 

3290 var = self.name.upper() # type: ignore 

3291 if self.deprecated: 

3292 var += "!" 

3293 if not self.required: 

3294 var = f"[{var}]" 

3295 if self.nargs != 1: 

3296 var += "..." 

3297 return var 

3298 

3299 def _parse_decls( 

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

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

3302 if not decls: 

3303 if not expose_value: 

3304 return None, [], [] 

3305 raise TypeError("Argument is marked as exposed, but does not have a name.") 

3306 if len(decls) == 1: 

3307 name = arg = decls[0] 

3308 name = name.replace("-", "_").lower() 

3309 else: 

3310 raise TypeError( 

3311 "Arguments take exactly one parameter declaration, got" 

3312 f" {len(decls)}: {decls}." 

3313 ) 

3314 return name, [arg], [] 

3315 

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

3317 return [self.make_metavar(ctx)] 

3318 

3319 def get_error_hint(self, ctx: Context) -> str: 

3320 return f"'{self.make_metavar(ctx)}'" 

3321 

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

3323 parser.add_argument(dest=self.name, nargs=self.nargs, obj=self) 

3324 

3325 

3326def __getattr__(name: str) -> object: 

3327 import warnings 

3328 

3329 if name == "BaseCommand": 

3330 warnings.warn( 

3331 "'BaseCommand' is deprecated and will be removed in Click 9.0. Use" 

3332 " 'Command' instead.", 

3333 DeprecationWarning, 

3334 stacklevel=2, 

3335 ) 

3336 return _BaseCommand 

3337 

3338 if name == "MultiCommand": 

3339 warnings.warn( 

3340 "'MultiCommand' is deprecated and will be removed in Click 9.0. Use" 

3341 " 'Group' instead.", 

3342 DeprecationWarning, 

3343 stacklevel=2, 

3344 ) 

3345 return _MultiCommand 

3346 

3347 raise AttributeError(name)