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

1202 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 .exceptions import Abort 

23from .exceptions import BadParameter 

24from .exceptions import ClickException 

25from .exceptions import Exit 

26from .exceptions import MissingParameter 

27from .exceptions import NoArgsIsHelpError 

28from .exceptions import UsageError 

29from .formatting import HelpFormatter 

30from .formatting import join_options 

31from .globals import pop_context 

32from .globals import push_context 

33from .parser import _flag_needs_value 

34from .parser import _OptionParser 

35from .parser import _split_opt 

36from .termui import confirm 

37from .termui import prompt 

38from .termui import style 

39from .utils import _detect_program_name 

40from .utils import _expand_args 

41from .utils import echo 

42from .utils import make_default_short_help 

43from .utils import make_str 

44from .utils import PacifyFlushWrapper 

45 

46if t.TYPE_CHECKING: 

47 from .shell_completion import CompletionItem 

48 

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

50V = t.TypeVar("V") 

51 

52 

53def _complete_visible_commands( 

54 ctx: Context, incomplete: str 

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

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

57 incomplete value and aren't hidden. 

58 

59 :param ctx: Invocation context for the group. 

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

61 """ 

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

63 

64 for name in multi.list_commands(ctx): 

65 if name.startswith(incomplete): 

66 command = multi.get_command(ctx, name) 

67 

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

69 yield name, command 

70 

71 

72def _check_nested_chain( 

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

74) -> None: 

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

76 return 

77 

78 if register: 

79 message = ( 

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

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

82 ) 

83 else: 

84 message = ( 

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

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

87 ) 

88 

89 raise RuntimeError(message) 

90 

91 

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

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

94 

95 

96@contextmanager 

97def augment_usage_errors( 

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

99) -> cabc.Iterator[None]: 

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

101 try: 

102 yield 

103 except BadParameter as e: 

104 if e.ctx is None: 

105 e.ctx = ctx 

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

107 e.param = param 

108 raise 

109 except UsageError as e: 

110 if e.ctx is None: 

111 e.ctx = ctx 

112 raise 

113 

114 

115def iter_params_for_processing( 

116 invocation_order: cabc.Sequence[Parameter], 

117 declaration_order: cabc.Sequence[Parameter], 

118) -> list[Parameter]: 

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

120 

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

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

123 

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

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

126 

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

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

129 """ 

130 

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

132 try: 

133 idx: float = invocation_order.index(item) 

134 except ValueError: 

135 idx = float("inf") 

136 

137 return not item.is_eager, idx 

138 

139 return sorted(declaration_order, key=sort_key) 

140 

141 

142class ParameterSource(enum.Enum): 

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

144 parameter's value. 

145 

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

147 source for a parameter by name. 

148 

149 .. versionchanged:: 8.0 

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

151 

152 .. versionchanged:: 8.0 

153 Added the ``PROMPT`` value. 

154 """ 

155 

156 COMMANDLINE = enum.auto() 

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

158 ENVIRONMENT = enum.auto() 

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

160 DEFAULT = enum.auto() 

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

162 DEFAULT_MAP = enum.auto() 

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

164 PROMPT = enum.auto() 

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

166 

167 

168class Context: 

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

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

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

172 

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

174 control special execution features such as reading data from 

175 environment variables. 

176 

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

178 :meth:`close` on teardown. 

179 

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

181 :param parent: the parent context. 

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

183 is the most descriptive name for the script or 

184 command. For the toplevel script it is usually 

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

186 the name of the script. 

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

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

189 variables. If this is `None` then reading 

190 from environment variables is disabled. This 

191 does not affect manually set environment 

192 variables which are always read. 

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

194 for parameters. 

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

196 inherit from parent context. If no context 

197 defines the terminal width then auto 

198 detection will be applied. 

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

200 Click (this currently only affects help 

201 pages). This defaults to 80 characters if 

202 not overridden. In other words: even if the 

203 terminal is larger than that, Click will not 

204 format things wider than 80 characters by 

205 default. In addition to that, formatters might 

206 add some safety mapping on the right. 

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

208 parse without any interactivity or callback 

209 invocation. Default values will also be 

210 ignored. This is useful for implementing 

211 things such as completion support. 

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

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

214 kept on the context. The default is to inherit 

215 from the command. 

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

217 and arguments cannot be mixed. The 

218 default is to inherit from the command. 

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

220 not know and keeps them for later 

221 processing. 

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

223 the default help parameter is named. The 

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

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

226 normalize tokens (options, choices, 

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

228 implement case insensitive behavior. 

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

230 default is autodetection. This is only needed if ANSI 

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

232 default not the case. This for instance would affect 

233 help output. 

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

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

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

237 specific command. 

238 

239 .. versionchanged:: 8.2 

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

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

242 

243 .. versionchanged:: 8.1 

244 The ``show_default`` parameter is overridden by 

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

246 

247 .. versionchanged:: 8.0 

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

249 parent context. 

250 

251 .. versionchanged:: 7.1 

252 Added the ``show_default`` parameter. 

253 

254 .. versionchanged:: 4.0 

255 Added the ``color``, ``ignore_unknown_options``, and 

256 ``max_content_width`` parameters. 

257 

258 .. versionchanged:: 3.0 

259 Added the ``allow_extra_args`` and ``allow_interspersed_args`` 

260 parameters. 

261 

262 .. versionchanged:: 2.0 

263 Added the ``resilient_parsing``, ``help_option_names``, and 

264 ``token_normalize_func`` parameters. 

265 """ 

266 

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

268 #: 

269 #: .. versionadded:: 8.0 

270 formatter_class: type[HelpFormatter] = HelpFormatter 

271 

272 def __init__( 

273 self, 

274 command: Command, 

275 parent: Context | None = None, 

276 info_name: str | None = None, 

277 obj: t.Any | None = None, 

278 auto_envvar_prefix: str | None = None, 

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

280 terminal_width: int | None = None, 

281 max_content_width: int | None = None, 

282 resilient_parsing: bool = False, 

283 allow_extra_args: bool | None = None, 

284 allow_interspersed_args: bool | None = None, 

285 ignore_unknown_options: bool | None = None, 

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

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

288 color: bool | None = None, 

289 show_default: bool | None = None, 

290 ) -> None: 

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

292 self.parent = parent 

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

294 self.command = command 

295 #: the descriptive information name 

296 self.info_name = info_name 

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

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

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

300 #: the leftover arguments. 

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

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

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

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

305 #: to implement nested parsing. 

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

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

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

309 

310 if obj is None and parent is not None: 

311 obj = parent.obj 

312 

313 #: the user object stored. 

314 self.obj: t.Any = obj 

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

316 

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

318 if ( 

319 default_map is None 

320 and info_name is not None 

321 and parent is not None 

322 and parent.default_map is not None 

323 ): 

324 default_map = parent.default_map.get(info_name) 

325 

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

327 

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

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

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

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

332 #: the name of the subcommand to execute. 

333 #: 

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

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

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

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

338 self.invoked_subcommand: str | None = None 

339 

340 if terminal_width is None and parent is not None: 

341 terminal_width = parent.terminal_width 

342 

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

344 self.terminal_width: int | None = terminal_width 

345 

346 if max_content_width is None and parent is not None: 

347 max_content_width = parent.max_content_width 

348 

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

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

351 self.max_content_width: int | None = max_content_width 

352 

353 if allow_extra_args is None: 

354 allow_extra_args = command.allow_extra_args 

355 

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

357 #: fail on parsing. 

358 #: 

359 #: .. versionadded:: 3.0 

360 self.allow_extra_args = allow_extra_args 

361 

362 if allow_interspersed_args is None: 

363 allow_interspersed_args = command.allow_interspersed_args 

364 

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

366 #: options or not. 

367 #: 

368 #: .. versionadded:: 3.0 

369 self.allow_interspersed_args: bool = allow_interspersed_args 

370 

371 if ignore_unknown_options is None: 

372 ignore_unknown_options = command.ignore_unknown_options 

373 

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

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

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

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

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

379 #: forward all arguments. 

380 #: 

381 #: .. versionadded:: 4.0 

382 self.ignore_unknown_options: bool = ignore_unknown_options 

383 

384 if help_option_names is None: 

385 if parent is not None: 

386 help_option_names = parent.help_option_names 

387 else: 

388 help_option_names = ["--help"] 

389 

390 #: The names for the help options. 

391 self.help_option_names: list[str] = help_option_names 

392 

393 if token_normalize_func is None and parent is not None: 

394 token_normalize_func = parent.token_normalize_func 

395 

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

397 #: options, choices, commands etc. 

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

399 

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

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

402 #: will be ignored. Useful for completion. 

403 self.resilient_parsing: bool = resilient_parsing 

404 

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

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

407 # prefix automatically. 

408 if auto_envvar_prefix is None: 

409 if ( 

410 parent is not None 

411 and parent.auto_envvar_prefix is not None 

412 and self.info_name is not None 

413 ): 

414 auto_envvar_prefix = ( 

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

416 ) 

417 else: 

418 auto_envvar_prefix = auto_envvar_prefix.upper() 

419 

420 if auto_envvar_prefix is not None: 

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

422 

423 self.auto_envvar_prefix: str | None = auto_envvar_prefix 

424 

425 if color is None and parent is not None: 

426 color = parent.color 

427 

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

429 self.color: bool | None = color 

430 

431 if show_default is None and parent is not None: 

432 show_default = parent.show_default 

433 

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

435 self.show_default: bool | None = show_default 

436 

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

438 self._depth = 0 

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

440 self._exit_stack = ExitStack() 

441 

442 @property 

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

444 import warnings 

445 

446 warnings.warn( 

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

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

449 DeprecationWarning, 

450 stacklevel=2, 

451 ) 

452 return self._protected_args 

453 

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

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

456 user-facing documentation. This traverses the entire CLI 

457 structure. 

458 

459 .. code-block:: python 

460 

461 with Context(cli) as ctx: 

462 info = ctx.to_info_dict() 

463 

464 .. versionadded:: 8.0 

465 """ 

466 return { 

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

468 "info_name": self.info_name, 

469 "allow_extra_args": self.allow_extra_args, 

470 "allow_interspersed_args": self.allow_interspersed_args, 

471 "ignore_unknown_options": self.ignore_unknown_options, 

472 "auto_envvar_prefix": self.auto_envvar_prefix, 

473 } 

474 

475 def __enter__(self) -> Context: 

476 self._depth += 1 

477 push_context(self) 

478 return self 

479 

480 def __exit__( 

481 self, 

482 exc_type: type[BaseException] | None, 

483 exc_value: BaseException | None, 

484 tb: TracebackType | None, 

485 ) -> None: 

486 self._depth -= 1 

487 if self._depth == 0: 

488 self.close() 

489 pop_context() 

490 

491 @contextmanager 

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

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

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

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

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

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

498 

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

500 used as a context manager. 

501 

502 Example usage:: 

503 

504 with ctx.scope(): 

505 assert get_current_context() is ctx 

506 

507 This is equivalent:: 

508 

509 with ctx: 

510 assert get_current_context() is ctx 

511 

512 .. versionadded:: 5.0 

513 

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

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

516 some situations the context only wants to be 

517 temporarily pushed in which case this can be disabled. 

518 Nested pushes automatically defer the cleanup. 

519 """ 

520 if not cleanup: 

521 self._depth += 1 

522 try: 

523 with self as rv: 

524 yield rv 

525 finally: 

526 if not cleanup: 

527 self._depth -= 1 

528 

529 @property 

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

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

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

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

534 that code to manage this dictionary well. 

535 

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

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

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

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

540 the system. 

541 

542 Example usage:: 

543 

544 LANG_KEY = f'{__name__}.lang' 

545 

546 def set_language(value): 

547 ctx = get_current_context() 

548 ctx.meta[LANG_KEY] = value 

549 

550 def get_language(): 

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

552 

553 .. versionadded:: 5.0 

554 """ 

555 return self._meta 

556 

557 def make_formatter(self) -> HelpFormatter: 

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

559 usage output. 

560 

561 To quickly customize the formatter class used without overriding 

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

563 

564 .. versionchanged:: 8.0 

565 Added the :attr:`formatter_class` attribute. 

566 """ 

567 return self.formatter_class( 

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

569 ) 

570 

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

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

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

574 popped. 

575 

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

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

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

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

580 

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

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

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

584 

585 .. code-block:: python 

586 

587 @click.group() 

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

589 @click.pass_context 

590 def cli(ctx): 

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

592 

593 :param context_manager: The context manager to enter. 

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

595 

596 .. versionadded:: 8.0 

597 """ 

598 return self._exit_stack.enter_context(context_manager) 

599 

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

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

602 

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

604 execution. Resources that support Python's context manager 

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

606 registered with :meth:`with_resource` instead. 

607 

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

609 """ 

610 return self._exit_stack.callback(f) 

611 

612 def close(self) -> None: 

613 """Invoke all close callbacks registered with 

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

615 with :meth:`with_resource`. 

616 """ 

617 self._exit_stack.close() 

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

619 self._exit_stack = ExitStack() 

620 

621 @property 

622 def command_path(self) -> str: 

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

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

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

626 """ 

627 rv = "" 

628 if self.info_name is not None: 

629 rv = self.info_name 

630 if self.parent is not None: 

631 parent_command_path = [self.parent.command_path] 

632 

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

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

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

636 

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

638 return rv.lstrip() 

639 

640 def find_root(self) -> Context: 

641 """Finds the outermost context.""" 

642 node = self 

643 while node.parent is not None: 

644 node = node.parent 

645 return node 

646 

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

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

649 node: Context | None = self 

650 

651 while node is not None: 

652 if isinstance(node.obj, object_type): 

653 return node.obj 

654 

655 node = node.parent 

656 

657 return None 

658 

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

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

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

662 """ 

663 rv = self.find_object(object_type) 

664 if rv is None: 

665 self.obj = rv = object_type() 

666 return rv 

667 

668 @t.overload 

669 def lookup_default( 

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

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

672 

673 @t.overload 

674 def lookup_default( 

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

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

677 

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

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

680 

681 :param name: Name of the parameter. 

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

683 return the callable instead. 

684 

685 .. versionchanged:: 8.0 

686 Added the ``call`` parameter. 

687 """ 

688 if self.default_map is not None: 

689 value = self.default_map.get(name) 

690 

691 if call and callable(value): 

692 return value() 

693 

694 return value 

695 

696 return None 

697 

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

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

700 message. 

701 

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

703 """ 

704 raise UsageError(message, self) 

705 

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

707 """Aborts the script.""" 

708 raise Abort() 

709 

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

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

712 

713 .. versionchanged:: 8.2 

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

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

716 """ 

717 self.close() 

718 raise Exit(code) 

719 

720 def get_usage(self) -> str: 

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

722 context and command. 

723 """ 

724 return self.command.get_usage(self) 

725 

726 def get_help(self) -> str: 

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

728 context and command. 

729 """ 

730 return self.command.get_help(self) 

731 

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

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

734 for a new command. 

735 

736 :meta private: 

737 """ 

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

739 

740 @t.overload 

741 def invoke( 

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

743 ) -> V: ... 

744 

745 @t.overload 

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

747 

748 def invoke( 

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

750 ) -> t.Any | V: 

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

752 are two ways to invoke this method: 

753 

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

755 keyword arguments are forwarded directly to the function. 

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

757 arguments are forwarded as well but proper click parameters 

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

759 will fill in defaults. 

760 

761 .. versionchanged:: 8.0 

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

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

764 

765 .. versionchanged:: 3.2 

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

767 """ 

768 if isinstance(callback, Command): 

769 other_cmd = callback 

770 

771 if other_cmd.callback is None: 

772 raise TypeError( 

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

774 ) 

775 else: 

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

777 

778 ctx = self._make_sub_context(other_cmd) 

779 

780 for param in other_cmd.params: 

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

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

783 ctx, param.get_default(ctx) 

784 ) 

785 

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

787 # them on in subsequent calls. 

788 ctx.params.update(kwargs) 

789 else: 

790 ctx = self 

791 

792 with augment_usage_errors(self): 

793 with ctx: 

794 return callback(*args, **kwargs) 

795 

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

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

798 arguments from the current context if the other command expects 

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

800 

801 .. versionchanged:: 8.0 

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

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

804 """ 

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

806 if not isinstance(cmd, Command): 

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

808 

809 for param in self.params: 

810 if param not in kwargs: 

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

812 

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

814 

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

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

817 from which the value of the parameter was obtained. 

818 

819 :param name: The name of the parameter. 

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

821 """ 

822 self._parameter_source[name] = source 

823 

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

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

826 from which the value of the parameter was obtained. 

827 

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

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

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

831 value was actually taken from the default. 

832 

833 :param name: The name of the parameter. 

834 :rtype: ParameterSource 

835 

836 .. versionchanged:: 8.0 

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

838 source. 

839 """ 

840 return self._parameter_source.get(name) 

841 

842 

843class Command: 

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

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

846 more parsing to commands nested below it. 

847 

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

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

850 passed to the context object. 

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

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

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

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

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

856 help page after everything else. 

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

858 shown on the command listing of the parent command. 

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

860 option. This can be disabled by this parameter. 

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

862 provided. This option is disabled by default. 

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

864 if no arguments are passed 

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

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

867 indicating that the command is deprecated and highlights 

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

869 by using a string as the value. 

870 

871 .. versionchanged:: 8.2 

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

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

874 deprecation message. 

875 

876 .. versionchanged:: 8.1 

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

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

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

880 

881 .. versionchanged:: 8.0 

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

883 

884 .. versionchanged:: 7.1 

885 Added the ``no_args_is_help`` parameter. 

886 

887 .. versionchanged:: 2.0 

888 Added the ``context_settings`` parameter. 

889 """ 

890 

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

892 #: 

893 #: .. versionadded:: 8.0 

894 context_class: type[Context] = Context 

895 

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

897 allow_extra_args = False 

898 

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

900 allow_interspersed_args = True 

901 

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

903 ignore_unknown_options = False 

904 

905 def __init__( 

906 self, 

907 name: str | None, 

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

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

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

911 help: str | None = None, 

912 epilog: str | None = None, 

913 short_help: str | None = None, 

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

915 add_help_option: bool = True, 

916 no_args_is_help: bool = False, 

917 hidden: bool = False, 

918 deprecated: bool | str = False, 

919 ) -> None: 

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

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

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

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

924 self.name = name 

925 

926 if context_settings is None: 

927 context_settings = {} 

928 

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

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

931 

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

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

934 self.callback = callback 

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

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

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

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

939 self.help = help 

940 self.epilog = epilog 

941 self.options_metavar = options_metavar 

942 self.short_help = short_help 

943 self.add_help_option = add_help_option 

944 self._help_option = None 

945 self.no_args_is_help = no_args_is_help 

946 self.hidden = hidden 

947 self.deprecated = deprecated 

948 

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

950 return { 

951 "name": self.name, 

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

953 "help": self.help, 

954 "epilog": self.epilog, 

955 "short_help": self.short_help, 

956 "hidden": self.hidden, 

957 "deprecated": self.deprecated, 

958 } 

959 

960 def __repr__(self) -> str: 

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

962 

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

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

965 

966 Calls :meth:`format_usage` internally. 

967 """ 

968 formatter = ctx.make_formatter() 

969 self.format_usage(ctx, formatter) 

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

971 

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

973 params = self.params 

974 help_option = self.get_help_option(ctx) 

975 

976 if help_option is not None: 

977 params = [*params, help_option] 

978 

979 if __debug__: 

980 import warnings 

981 

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

983 opts_counter = Counter(opts) 

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

985 

986 for duplicate_opt in duplicate_opts: 

987 warnings.warn( 

988 ( 

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

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

991 ), 

992 stacklevel=3, 

993 ) 

994 

995 return params 

996 

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

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

999 

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

1001 """ 

1002 pieces = self.collect_usage_pieces(ctx) 

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

1004 

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

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

1007 it as a list of strings. 

1008 """ 

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

1010 

1011 for param in self.get_params(ctx): 

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

1013 

1014 return rv 

1015 

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

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

1018 all_names = set(ctx.help_option_names) 

1019 for param in self.params: 

1020 all_names.difference_update(param.opts) 

1021 all_names.difference_update(param.secondary_opts) 

1022 return list(all_names) 

1023 

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

1025 """Returns the help option object. 

1026 

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

1028 

1029 .. versionchanged:: 8.1.8 

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

1031 """ 

1032 help_option_names = self.get_help_option_names(ctx) 

1033 

1034 if not help_option_names or not self.add_help_option: 

1035 return None 

1036 

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

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

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

1040 # object comparison. 

1041 if self._help_option is None: 

1042 # Avoid circular import. 

1043 from .decorators import help_option 

1044 

1045 # Apply help_option decorator and pop resulting option 

1046 help_option(*help_option_names)(self) 

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

1048 

1049 return self._help_option 

1050 

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

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

1053 parser = _OptionParser(ctx) 

1054 for param in self.get_params(ctx): 

1055 param.add_to_parser(parser, ctx) 

1056 return parser 

1057 

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

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

1060 

1061 Calls :meth:`format_help` internally. 

1062 """ 

1063 formatter = ctx.make_formatter() 

1064 self.format_help(ctx, formatter) 

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

1066 

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

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

1069 long help string. 

1070 """ 

1071 if self.short_help: 

1072 text = inspect.cleandoc(self.short_help) 

1073 elif self.help: 

1074 text = make_default_short_help(self.help, limit) 

1075 else: 

1076 text = "" 

1077 

1078 if self.deprecated: 

1079 deprecated_message = ( 

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

1081 if isinstance(self.deprecated, str) 

1082 else "(DEPRECATED)" 

1083 ) 

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

1085 text=text, deprecated_message=deprecated_message 

1086 ) 

1087 

1088 return text.strip() 

1089 

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

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

1092 

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

1094 

1095 This calls the following methods: 

1096 

1097 - :meth:`format_usage` 

1098 - :meth:`format_help_text` 

1099 - :meth:`format_options` 

1100 - :meth:`format_epilog` 

1101 """ 

1102 self.format_usage(ctx, formatter) 

1103 self.format_help_text(ctx, formatter) 

1104 self.format_options(ctx, formatter) 

1105 self.format_epilog(ctx, formatter) 

1106 

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

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

1109 if self.help is not None: 

1110 # truncate the help text to the first form feed 

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

1112 else: 

1113 text = "" 

1114 

1115 if self.deprecated: 

1116 deprecated_message = ( 

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

1118 if isinstance(self.deprecated, str) 

1119 else "(DEPRECATED)" 

1120 ) 

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

1122 text=text, deprecated_message=deprecated_message 

1123 ) 

1124 

1125 if text: 

1126 formatter.write_paragraph() 

1127 

1128 with formatter.indentation(): 

1129 formatter.write_text(text) 

1130 

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

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

1133 opts = [] 

1134 for param in self.get_params(ctx): 

1135 rv = param.get_help_record(ctx) 

1136 if rv is not None: 

1137 opts.append(rv) 

1138 

1139 if opts: 

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

1141 formatter.write_dl(opts) 

1142 

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

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

1145 if self.epilog: 

1146 epilog = inspect.cleandoc(self.epilog) 

1147 formatter.write_paragraph() 

1148 

1149 with formatter.indentation(): 

1150 formatter.write_text(epilog) 

1151 

1152 def make_context( 

1153 self, 

1154 info_name: str | None, 

1155 args: list[str], 

1156 parent: Context | None = None, 

1157 **extra: t.Any, 

1158 ) -> Context: 

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

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

1161 invoke the actual command callback though. 

1162 

1163 To quickly customize the context class used without overriding 

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

1165 

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

1167 is the most descriptive name for the script or 

1168 command. For the toplevel script it's usually 

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

1170 the name of the command. 

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

1172 :param parent: the parent context if available. 

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

1174 constructor. 

1175 

1176 .. versionchanged:: 8.0 

1177 Added the :attr:`context_class` attribute. 

1178 """ 

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

1180 if key not in extra: 

1181 extra[key] = value 

1182 

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

1184 

1185 with ctx.scope(cleanup=False): 

1186 self.parse_args(ctx, args) 

1187 return ctx 

1188 

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

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

1191 raise NoArgsIsHelpError(ctx) 

1192 

1193 parser = self.make_parser(ctx) 

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

1195 

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

1197 value, args = param.handle_parse_result(ctx, opts, args) 

1198 

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

1200 ctx.fail( 

1201 ngettext( 

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

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

1204 len(args), 

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

1206 ) 

1207 

1208 ctx.args = args 

1209 ctx._opt_prefixes.update(parser._opt_prefixes) 

1210 return args 

1211 

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

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

1214 in the right way. 

1215 """ 

1216 if self.deprecated: 

1217 extra_message = ( 

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

1219 ) 

1220 message = _( 

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

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

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

1224 

1225 if self.callback is not None: 

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

1227 

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

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

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

1231 

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

1233 commands are valid at any point during command completion. 

1234 

1235 :param ctx: Invocation context for this command. 

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

1237 

1238 .. versionadded:: 8.0 

1239 """ 

1240 from click.shell_completion import CompletionItem 

1241 

1242 results: list[CompletionItem] = [] 

1243 

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

1245 for param in self.get_params(ctx): 

1246 if ( 

1247 not isinstance(param, Option) 

1248 or param.hidden 

1249 or ( 

1250 not param.multiple 

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

1252 is ParameterSource.COMMANDLINE 

1253 ) 

1254 ): 

1255 continue 

1256 

1257 results.extend( 

1258 CompletionItem(name, help=param.help) 

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

1260 if name.startswith(incomplete) 

1261 ) 

1262 

1263 while ctx.parent is not None: 

1264 ctx = ctx.parent 

1265 

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

1267 results.extend( 

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

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

1270 if name not in ctx._protected_args 

1271 ) 

1272 

1273 return results 

1274 

1275 @t.overload 

1276 def main( 

1277 self, 

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

1279 prog_name: str | None = None, 

1280 complete_var: str | None = None, 

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

1282 **extra: t.Any, 

1283 ) -> t.NoReturn: ... 

1284 

1285 @t.overload 

1286 def main( 

1287 self, 

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

1289 prog_name: str | None = None, 

1290 complete_var: str | None = None, 

1291 standalone_mode: bool = ..., 

1292 **extra: t.Any, 

1293 ) -> t.Any: ... 

1294 

1295 def main( 

1296 self, 

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

1298 prog_name: str | None = None, 

1299 complete_var: str | None = None, 

1300 standalone_mode: bool = True, 

1301 windows_expand_args: bool = True, 

1302 **extra: t.Any, 

1303 ) -> t.Any: 

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

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

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

1307 needs to be caught. 

1308 

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

1310 a :class:`Command`. 

1311 

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

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

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

1315 the program name is constructed by taking the file 

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

1317 :param complete_var: the environment variable that controls the 

1318 bash completion support. The default is 

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

1320 uppercase. 

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

1322 in standalone mode. Click will then 

1323 handle exceptions and convert them into 

1324 error messages and the function will never 

1325 return but shut down the interpreter. If 

1326 this is set to `False` they will be 

1327 propagated to the caller and the return 

1328 value of this function is the return value 

1329 of :meth:`invoke`. 

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

1331 env vars in command line args on Windows. 

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

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

1334 

1335 .. versionchanged:: 8.0.1 

1336 Added the ``windows_expand_args`` parameter to allow 

1337 disabling command line arg expansion on Windows. 

1338 

1339 .. versionchanged:: 8.0 

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

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

1342 

1343 .. versionchanged:: 3.0 

1344 Added the ``standalone_mode`` parameter. 

1345 """ 

1346 if args is None: 

1347 args = sys.argv[1:] 

1348 

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

1350 args = _expand_args(args) 

1351 else: 

1352 args = list(args) 

1353 

1354 if prog_name is None: 

1355 prog_name = _detect_program_name() 

1356 

1357 # Process shell completion requests and exit early. 

1358 self._main_shell_completion(extra, prog_name, complete_var) 

1359 

1360 try: 

1361 try: 

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

1363 rv = self.invoke(ctx) 

1364 if not standalone_mode: 

1365 return rv 

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

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

1368 # has obvious effects 

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

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

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

1372 # by its truthiness/falsiness 

1373 ctx.exit() 

1374 except (EOFError, KeyboardInterrupt) as e: 

1375 echo(file=sys.stderr) 

1376 raise Abort() from e 

1377 except ClickException as e: 

1378 if not standalone_mode: 

1379 raise 

1380 e.show() 

1381 sys.exit(e.exit_code) 

1382 except OSError as e: 

1383 if e.errno == errno.EPIPE: 

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

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

1386 sys.exit(1) 

1387 else: 

1388 raise 

1389 except Exit as e: 

1390 if standalone_mode: 

1391 sys.exit(e.exit_code) 

1392 else: 

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

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

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

1396 # would return its result 

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

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

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

1400 # tell the difference between the two 

1401 return e.exit_code 

1402 except Abort: 

1403 if not standalone_mode: 

1404 raise 

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

1406 sys.exit(1) 

1407 

1408 def _main_shell_completion( 

1409 self, 

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

1411 prog_name: str, 

1412 complete_var: str | None = None, 

1413 ) -> None: 

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

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

1416 program is invoked. 

1417 

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

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

1420 the completion instruction. Defaults to 

1421 ``_{PROG_NAME}_COMPLETE``. 

1422 

1423 .. versionchanged:: 8.2.0 

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

1425 """ 

1426 if complete_var is None: 

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

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

1429 

1430 instruction = os.environ.get(complete_var) 

1431 

1432 if not instruction: 

1433 return 

1434 

1435 from .shell_completion import shell_complete 

1436 

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

1438 sys.exit(rv) 

1439 

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

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

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

1443 

1444 

1445class _FakeSubclassCheck(type): 

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

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

1448 

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

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

1451 

1452 

1453class _BaseCommand(Command, metaclass=_FakeSubclassCheck): 

1454 """ 

1455 .. deprecated:: 8.2 

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

1457 """ 

1458 

1459 

1460class Group(Command): 

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

1462 

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

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

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

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

1467 subcommand is not given. 

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

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

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

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

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

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

1474 matched, and so on. 

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

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

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

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

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

1480 ``chain`` is enabled. 

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

1482 

1483 .. versionchanged:: 8.0 

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

1485 

1486 .. versionchanged:: 8.2 

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

1488 """ 

1489 

1490 allow_extra_args = True 

1491 allow_interspersed_args = False 

1492 

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

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

1495 #: subcommands use a custom command class. 

1496 #: 

1497 #: .. versionadded:: 8.0 

1498 command_class: type[Command] | None = None 

1499 

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

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

1502 #: subgroups use a custom group class. 

1503 #: 

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

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

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

1507 #: custom groups. 

1508 #: 

1509 #: .. versionadded:: 8.0 

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

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

1512 

1513 def __init__( 

1514 self, 

1515 name: str | None = None, 

1516 commands: cabc.MutableMapping[str, Command] 

1517 | cabc.Sequence[Command] 

1518 | None = None, 

1519 invoke_without_command: bool = False, 

1520 no_args_is_help: bool | None = None, 

1521 subcommand_metavar: str | None = None, 

1522 chain: bool = False, 

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

1524 **kwargs: t.Any, 

1525 ) -> None: 

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

1527 

1528 if commands is None: 

1529 commands = {} 

1530 elif isinstance(commands, abc.Sequence): 

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

1532 

1533 #: The registered subcommands by their exported names. 

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

1535 

1536 if no_args_is_help is None: 

1537 no_args_is_help = not invoke_without_command 

1538 

1539 self.no_args_is_help = no_args_is_help 

1540 self.invoke_without_command = invoke_without_command 

1541 

1542 if subcommand_metavar is None: 

1543 if chain: 

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

1545 else: 

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

1547 

1548 self.subcommand_metavar = subcommand_metavar 

1549 self.chain = chain 

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

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

1552 self._result_callback = result_callback 

1553 

1554 if self.chain: 

1555 for param in self.params: 

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

1557 raise RuntimeError( 

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

1559 ) 

1560 

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

1562 info_dict = super().to_info_dict(ctx) 

1563 commands = {} 

1564 

1565 for name in self.list_commands(ctx): 

1566 command = self.get_command(ctx, name) 

1567 

1568 if command is None: 

1569 continue 

1570 

1571 sub_ctx = ctx._make_sub_context(command) 

1572 

1573 with sub_ctx.scope(cleanup=False): 

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

1575 

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

1577 return info_dict 

1578 

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

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

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

1582 """ 

1583 name = name or cmd.name 

1584 if name is None: 

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

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

1587 self.commands[name] = cmd 

1588 

1589 @t.overload 

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

1591 

1592 @t.overload 

1593 def command( 

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

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

1596 

1597 def command( 

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

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

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

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

1602 immediately registers the created command with this group by 

1603 calling :meth:`add_command`. 

1604 

1605 To customize the command class used, set the 

1606 :attr:`command_class` attribute. 

1607 

1608 .. versionchanged:: 8.1 

1609 This decorator can be applied without parentheses. 

1610 

1611 .. versionchanged:: 8.0 

1612 Added the :attr:`command_class` attribute. 

1613 """ 

1614 from .decorators import command 

1615 

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

1617 

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

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

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

1621 ) 

1622 (func,) = args 

1623 args = () 

1624 

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

1626 kwargs["cls"] = self.command_class 

1627 

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

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

1630 self.add_command(cmd) 

1631 return cmd 

1632 

1633 if func is not None: 

1634 return decorator(func) 

1635 

1636 return decorator 

1637 

1638 @t.overload 

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

1640 

1641 @t.overload 

1642 def group( 

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

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

1645 

1646 def group( 

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

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

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

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

1651 immediately registers the created group with this group by 

1652 calling :meth:`add_command`. 

1653 

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

1655 attribute. 

1656 

1657 .. versionchanged:: 8.1 

1658 This decorator can be applied without parentheses. 

1659 

1660 .. versionchanged:: 8.0 

1661 Added the :attr:`group_class` attribute. 

1662 """ 

1663 from .decorators import group 

1664 

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

1666 

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

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

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

1670 ) 

1671 (func,) = args 

1672 args = () 

1673 

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

1675 if self.group_class is type: 

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

1677 else: 

1678 kwargs["cls"] = self.group_class 

1679 

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

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

1682 self.add_command(cmd) 

1683 return cmd 

1684 

1685 if func is not None: 

1686 return decorator(func) 

1687 

1688 return decorator 

1689 

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

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

1692 result callback is already registered this will chain them but 

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

1694 callback is invoked with the return value of the subcommand 

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

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

1697 to the main callback. 

1698 

1699 Example:: 

1700 

1701 @click.group() 

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

1703 def cli(input): 

1704 return 42 

1705 

1706 @cli.result_callback() 

1707 def process_result(result, input): 

1708 return result + input 

1709 

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

1711 callback will be removed. 

1712 

1713 .. versionchanged:: 8.0 

1714 Renamed from ``resultcallback``. 

1715 

1716 .. versionadded:: 3.0 

1717 """ 

1718 

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

1720 old_callback = self._result_callback 

1721 

1722 if old_callback is None or replace: 

1723 self._result_callback = f 

1724 return f 

1725 

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

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

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

1729 

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

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

1732 

1733 return decorator 

1734 

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

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

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

1738 """ 

1739 return self.commands.get(cmd_name) 

1740 

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

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

1743 return sorted(self.commands) 

1744 

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

1746 rv = super().collect_usage_pieces(ctx) 

1747 rv.append(self.subcommand_metavar) 

1748 return rv 

1749 

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

1751 super().format_options(ctx, formatter) 

1752 self.format_commands(ctx, formatter) 

1753 

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

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

1756 after the options. 

1757 """ 

1758 commands = [] 

1759 for subcommand in self.list_commands(ctx): 

1760 cmd = self.get_command(ctx, subcommand) 

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

1762 if cmd is None: 

1763 continue 

1764 if cmd.hidden: 

1765 continue 

1766 

1767 commands.append((subcommand, cmd)) 

1768 

1769 # allow for 3 times the default spacing 

1770 if len(commands): 

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

1772 

1773 rows = [] 

1774 for subcommand, cmd in commands: 

1775 help = cmd.get_short_help_str(limit) 

1776 rows.append((subcommand, help)) 

1777 

1778 if rows: 

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

1780 formatter.write_dl(rows) 

1781 

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

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

1784 raise NoArgsIsHelpError(ctx) 

1785 

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

1787 

1788 if self.chain: 

1789 ctx._protected_args = rest 

1790 ctx.args = [] 

1791 elif rest: 

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

1793 

1794 return ctx.args 

1795 

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

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

1798 if self._result_callback is not None: 

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

1800 return value 

1801 

1802 if not ctx._protected_args: 

1803 if self.invoke_without_command: 

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

1805 # invoked with the group return value for regular 

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

1807 with ctx: 

1808 rv = super().invoke(ctx) 

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

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

1811 

1812 # Fetch args back out 

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

1814 ctx.args = [] 

1815 ctx._protected_args = [] 

1816 

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

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

1819 # name of the command to invoke. 

1820 if not self.chain: 

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

1822 # resources until the result processor has worked. 

1823 with ctx: 

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

1825 assert cmd is not None 

1826 ctx.invoked_subcommand = cmd_name 

1827 super().invoke(ctx) 

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

1829 with sub_ctx: 

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

1831 

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

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

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

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

1836 # but nothing else. 

1837 with ctx: 

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

1839 super().invoke(ctx) 

1840 

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

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

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

1844 contexts = [] 

1845 while args: 

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

1847 assert cmd is not None 

1848 sub_ctx = cmd.make_context( 

1849 cmd_name, 

1850 args, 

1851 parent=ctx, 

1852 allow_extra_args=True, 

1853 allow_interspersed_args=False, 

1854 ) 

1855 contexts.append(sub_ctx) 

1856 args, sub_ctx.args = sub_ctx.args, [] 

1857 

1858 rv = [] 

1859 for sub_ctx in contexts: 

1860 with sub_ctx: 

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

1862 return _process_result(rv) 

1863 

1864 def resolve_command( 

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

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

1867 cmd_name = make_str(args[0]) 

1868 original_cmd_name = cmd_name 

1869 

1870 # Get the command 

1871 cmd = self.get_command(ctx, cmd_name) 

1872 

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

1874 # function available, we try with that one. 

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

1876 cmd_name = ctx.token_normalize_func(cmd_name) 

1877 cmd = self.get_command(ctx, cmd_name) 

1878 

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

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

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

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

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

1884 # place. 

1885 if cmd is None and not ctx.resilient_parsing: 

1886 if _split_opt(cmd_name)[0]: 

1887 self.parse_args(ctx, args) 

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

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

1890 

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

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

1893 at the names of options, subcommands, and chained 

1894 multi-commands. 

1895 

1896 :param ctx: Invocation context for this command. 

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

1898 

1899 .. versionadded:: 8.0 

1900 """ 

1901 from click.shell_completion import CompletionItem 

1902 

1903 results = [ 

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

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

1906 ] 

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

1908 return results 

1909 

1910 

1911class _MultiCommand(Group, metaclass=_FakeSubclassCheck): 

1912 """ 

1913 .. deprecated:: 8.2 

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

1915 """ 

1916 

1917 

1918class CommandCollection(Group): 

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

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

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

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

1923 commands in many groups into this one group. 

1924 

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

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

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

1928 

1929 .. versionchanged:: 8.2 

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

1931 group, then each of its sources. 

1932 """ 

1933 

1934 def __init__( 

1935 self, 

1936 name: str | None = None, 

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

1938 **kwargs: t.Any, 

1939 ) -> None: 

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

1941 #: The list of registered groups. 

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

1943 

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

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

1946 self.sources.append(group) 

1947 

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

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

1950 

1951 if rv is not None: 

1952 return rv 

1953 

1954 for source in self.sources: 

1955 rv = source.get_command(ctx, cmd_name) 

1956 

1957 if rv is not None: 

1958 if self.chain: 

1959 _check_nested_chain(self, cmd_name, rv) 

1960 

1961 return rv 

1962 

1963 return None 

1964 

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

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

1967 

1968 for source in self.sources: 

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

1970 

1971 return sorted(rv) 

1972 

1973 

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

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

1976 error, or return an iterator over the value. 

1977 """ 

1978 if isinstance(value, str): 

1979 raise TypeError 

1980 

1981 return iter(value) 

1982 

1983 

1984class Parameter: 

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

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

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

1988 intentionally not finalized. 

1989 

1990 Some settings are supported by both options and arguments. 

1991 

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

1993 argument. This is a list of flags or argument 

1994 names. 

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

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

1997 automatically if supported. 

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

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

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

2001 without any arguments. 

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

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

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

2005 including prompts. 

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

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

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

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

2010 parameters are collected. 

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

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

2013 to the command callback and stored on the context, 

2014 otherwise it's skipped. 

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

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

2017 order of processing. 

2018 :param envvar: a string or list of strings that are environment variables 

2019 that should be checked. 

2020 :param shell_complete: A function that returns custom shell 

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

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

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

2024 strings. 

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

2026 indicating that the argument is deprecated and highlights 

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

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

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

2030 

2031 .. versionchanged:: 8.2.0 

2032 Introduction of ``deprecated``. 

2033 

2034 .. versionchanged:: 8.2 

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

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

2037 

2038 .. versionchanged:: 8.2 

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

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

2041 

2042 .. versionchanged:: 8.0 

2043 ``process_value`` validates required parameters and bounded 

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

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

2046 ``full_process_value`` is removed. 

2047 

2048 .. versionchanged:: 8.0 

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

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

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

2052 new requirements. 

2053 

2054 .. versionchanged:: 8.0 

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

2056 tuples. 

2057 

2058 .. versionchanged:: 8.0 

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

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

2061 default to ``()``. 

2062 

2063 .. versionchanged:: 7.1 

2064 Empty environment variables are ignored rather than taking the 

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

2066 variables if they can't unset them. 

2067 

2068 .. versionchanged:: 2.0 

2069 Changed signature for parameter callback to also be passed the 

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

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

2072 """ 

2073 

2074 param_type_name = "parameter" 

2075 

2076 def __init__( 

2077 self, 

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

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

2080 required: bool = False, 

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

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

2083 nargs: int | None = None, 

2084 multiple: bool = False, 

2085 metavar: str | None = None, 

2086 expose_value: bool = True, 

2087 is_eager: bool = False, 

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

2089 shell_complete: t.Callable[ 

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

2091 ] 

2092 | None = None, 

2093 deprecated: bool | str = False, 

2094 ) -> None: 

2095 self.name: str | None 

2096 self.opts: list[str] 

2097 self.secondary_opts: list[str] 

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

2099 param_decls or (), expose_value 

2100 ) 

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

2102 

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

2104 # information available. 

2105 if nargs is None: 

2106 if self.type.is_composite: 

2107 nargs = self.type.arity 

2108 else: 

2109 nargs = 1 

2110 

2111 self.required = required 

2112 self.callback = callback 

2113 self.nargs = nargs 

2114 self.multiple = multiple 

2115 self.expose_value = expose_value 

2116 self.default = default 

2117 self.is_eager = is_eager 

2118 self.metavar = metavar 

2119 self.envvar = envvar 

2120 self._custom_shell_complete = shell_complete 

2121 self.deprecated = deprecated 

2122 

2123 if __debug__: 

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

2125 raise ValueError( 

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

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

2128 ) 

2129 

2130 # Skip no default or callable default. 

2131 check_default = default if not callable(default) else None 

2132 

2133 if check_default is not None: 

2134 if multiple: 

2135 try: 

2136 # Only check the first value against nargs. 

2137 check_default = next(_check_iter(check_default), None) 

2138 except TypeError: 

2139 raise ValueError( 

2140 "'default' must be a list when 'multiple' is true." 

2141 ) from None 

2142 

2143 # Can be None for multiple with empty default. 

2144 if nargs != 1 and check_default is not None: 

2145 try: 

2146 _check_iter(check_default) 

2147 except TypeError: 

2148 if multiple: 

2149 message = ( 

2150 "'default' must be a list of lists when 'multiple' is" 

2151 " true and 'nargs' != 1." 

2152 ) 

2153 else: 

2154 message = "'default' must be a list when 'nargs' != 1." 

2155 

2156 raise ValueError(message) from None 

2157 

2158 if nargs > 1 and len(check_default) != nargs: 

2159 subject = "item length" if multiple else "length" 

2160 raise ValueError( 

2161 f"'default' {subject} must match nargs={nargs}." 

2162 ) 

2163 

2164 if required and deprecated: 

2165 raise ValueError( 

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

2167 "is deprecated and still required. A deprecated " 

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

2169 ) 

2170 

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

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

2173 user-facing documentation. 

2174 

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

2176 CLI structure. 

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 "default": self.default, 

2190 "envvar": self.envvar, 

2191 } 

2192 

2193 def __repr__(self) -> str: 

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

2195 

2196 def _parse_decls( 

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

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

2199 raise NotImplementedError() 

2200 

2201 @property 

2202 def human_readable_name(self) -> str: 

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

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

2205 """ 

2206 return self.name # type: ignore 

2207 

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

2209 if self.metavar is not None: 

2210 return self.metavar 

2211 

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

2213 

2214 if metavar is None: 

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

2216 

2217 if self.nargs != 1: 

2218 metavar += "..." 

2219 

2220 return metavar 

2221 

2222 @t.overload 

2223 def get_default( 

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

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

2226 

2227 @t.overload 

2228 def get_default( 

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

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

2231 

2232 def get_default( 

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

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

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

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

2237 

2238 :param ctx: Current context. 

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

2240 return the callable instead. 

2241 

2242 .. versionchanged:: 8.0.2 

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

2244 

2245 .. versionchanged:: 8.0.1 

2246 Type casting can fail in resilient parsing mode. Invalid 

2247 defaults will not prevent showing help text. 

2248 

2249 .. versionchanged:: 8.0 

2250 Looks at ``ctx.default_map`` first. 

2251 

2252 .. versionchanged:: 8.0 

2253 Added the ``call`` parameter. 

2254 """ 

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

2256 

2257 if value is None: 

2258 value = self.default 

2259 

2260 if call and callable(value): 

2261 value = value() 

2262 

2263 return value 

2264 

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

2266 raise NotImplementedError() 

2267 

2268 def consume_value( 

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

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

2271 value = opts.get(self.name) # type: ignore 

2272 source = ParameterSource.COMMANDLINE 

2273 

2274 if value is None: 

2275 value = self.value_from_envvar(ctx) 

2276 source = ParameterSource.ENVIRONMENT 

2277 

2278 if value is None: 

2279 value = ctx.lookup_default(self.name) # type: ignore 

2280 source = ParameterSource.DEFAULT_MAP 

2281 

2282 if value is None: 

2283 value = self.get_default(ctx) 

2284 source = ParameterSource.DEFAULT 

2285 

2286 return value, source 

2287 

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

2289 """Convert and validate a value against the option's 

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

2291 """ 

2292 if value is None: 

2293 return () if self.multiple or self.nargs == -1 else None 

2294 

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

2296 try: 

2297 return _check_iter(value) 

2298 except TypeError: 

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

2300 # the parser should construct an iterable when parsing 

2301 # the command line. 

2302 raise BadParameter( 

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

2304 ) from None 

2305 

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

2307 

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

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

2310 

2311 elif self.nargs == -1: 

2312 

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

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

2315 

2316 else: # nargs > 1 

2317 

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

2319 value = tuple(check_iter(value)) 

2320 

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

2322 raise BadParameter( 

2323 ngettext( 

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

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

2326 len(value), 

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

2328 ctx=ctx, 

2329 param=self, 

2330 ) 

2331 

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

2333 

2334 if self.multiple: 

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

2336 

2337 return convert(value) 

2338 

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

2340 if value is None: 

2341 return True 

2342 

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

2344 return True 

2345 

2346 return False 

2347 

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

2349 value = self.type_cast_value(ctx, value) 

2350 

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

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

2353 

2354 if self.callback is not None: 

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

2356 

2357 return value 

2358 

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

2360 if self.envvar is None: 

2361 return None 

2362 

2363 if isinstance(self.envvar, str): 

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

2365 

2366 if rv: 

2367 return rv 

2368 else: 

2369 for envvar in self.envvar: 

2370 rv = os.environ.get(envvar) 

2371 

2372 if rv: 

2373 return rv 

2374 

2375 return None 

2376 

2377 def value_from_envvar(self, ctx: Context) -> t.Any | None: 

2378 rv: t.Any | None = self.resolve_envvar_value(ctx) 

2379 

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

2381 rv = self.type.split_envvar_value(rv) 

2382 

2383 return rv 

2384 

2385 def handle_parse_result( 

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

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

2388 with augment_usage_errors(ctx, param=self): 

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

2390 

2391 if ( 

2392 self.deprecated 

2393 and value is not None 

2394 and source 

2395 not in ( 

2396 ParameterSource.DEFAULT, 

2397 ParameterSource.DEFAULT_MAP, 

2398 ) 

2399 ): 

2400 extra_message = ( 

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

2402 ) 

2403 message = _( 

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

2405 "{extra_message}" 

2406 ).format( 

2407 param_type=self.param_type_name, 

2408 name=self.human_readable_name, 

2409 extra_message=extra_message, 

2410 ) 

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

2412 

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

2414 

2415 try: 

2416 value = self.process_value(ctx, value) 

2417 except Exception: 

2418 if not ctx.resilient_parsing: 

2419 raise 

2420 

2421 value = None 

2422 

2423 if self.expose_value: 

2424 ctx.params[self.name] = value # type: ignore 

2425 

2426 return value, args 

2427 

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

2429 pass 

2430 

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

2432 return [] 

2433 

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

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

2436 indicate which param caused the error. 

2437 """ 

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

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

2440 

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

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

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

2444 Otherwise, the :attr:`type` 

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

2446 

2447 :param ctx: Invocation context for this command. 

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

2449 

2450 .. versionadded:: 8.0 

2451 """ 

2452 if self._custom_shell_complete is not None: 

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

2454 

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

2456 from click.shell_completion import CompletionItem 

2457 

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

2459 

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

2461 

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

2463 

2464 

2465class Option(Parameter): 

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

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

2468 

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

2470 

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

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

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

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

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

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

2477 its value is ``False``. 

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

2479 shown on the help page and error messages. 

2480 Normally, environment variables are not shown. 

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

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

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

2484 prompted. 

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

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

2487 ``True`` to customize the message. 

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

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

2490 without a value. 

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

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

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

2494 auto detection. 

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

2496 enabled. This is set to a boolean automatically if 

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

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

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

2500 in how it works but supports arbitrary number of 

2501 arguments. 

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

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

2504 parameter will be pulled from an environment 

2505 variable in case a prefix is defined on the 

2506 context. 

2507 :param help: the help string. 

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

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

2510 

2511 .. versionchanged:: 8.2 

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

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

2514 

2515 .. versionchanged:: 8.1 

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

2517 ``@option`` decorator. 

2518 

2519 .. versionchanged:: 8.1 

2520 The ``show_default`` parameter overrides 

2521 ``Context.show_default``. 

2522 

2523 .. versionchanged:: 8.1 

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

2525 default value is ``False``. 

2526 

2527 .. versionchanged:: 8.0.1 

2528 ``type`` is detected from ``flag_value`` if given. 

2529 """ 

2530 

2531 param_type_name = "option" 

2532 

2533 def __init__( 

2534 self, 

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

2536 show_default: bool | str | None = None, 

2537 prompt: bool | str = False, 

2538 confirmation_prompt: bool | str = False, 

2539 prompt_required: bool = True, 

2540 hide_input: bool = False, 

2541 is_flag: bool | None = None, 

2542 flag_value: t.Any | None = None, 

2543 multiple: bool = False, 

2544 count: bool = False, 

2545 allow_from_autoenv: bool = True, 

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

2547 help: str | None = None, 

2548 hidden: bool = False, 

2549 show_choices: bool = True, 

2550 show_envvar: bool = False, 

2551 deprecated: bool | str = False, 

2552 **attrs: t.Any, 

2553 ) -> None: 

2554 if help: 

2555 help = inspect.cleandoc(help) 

2556 

2557 default_is_missing = "default" not in attrs 

2558 super().__init__( 

2559 param_decls, type=type, multiple=multiple, deprecated=deprecated, **attrs 

2560 ) 

2561 

2562 if prompt is True: 

2563 if self.name is None: 

2564 raise TypeError("'name' is required with 'prompt=True'.") 

2565 

2566 prompt_text: str | None = self.name.replace("_", " ").capitalize() 

2567 elif prompt is False: 

2568 prompt_text = None 

2569 else: 

2570 prompt_text = prompt 

2571 

2572 if deprecated: 

2573 deprecated_message = ( 

2574 f"(DEPRECATED: {deprecated})" 

2575 if isinstance(deprecated, str) 

2576 else "(DEPRECATED)" 

2577 ) 

2578 help = help + deprecated_message if help is not None else deprecated_message 

2579 

2580 self.prompt = prompt_text 

2581 self.confirmation_prompt = confirmation_prompt 

2582 self.prompt_required = prompt_required 

2583 self.hide_input = hide_input 

2584 self.hidden = hidden 

2585 

2586 # If prompt is enabled but not required, then the option can be 

2587 # used as a flag to indicate using prompt or flag_value. 

2588 self._flag_needs_value = self.prompt is not None and not self.prompt_required 

2589 

2590 if is_flag is None: 

2591 if flag_value is not None: 

2592 # Implicitly a flag because flag_value was set. 

2593 is_flag = True 

2594 elif self._flag_needs_value: 

2595 # Not a flag, but when used as a flag it shows a prompt. 

2596 is_flag = False 

2597 else: 

2598 # Implicitly a flag because flag options were given. 

2599 is_flag = bool(self.secondary_opts) 

2600 elif is_flag is False and not self._flag_needs_value: 

2601 # Not a flag, and prompt is not enabled, can be used as a 

2602 # flag if flag_value is set. 

2603 self._flag_needs_value = flag_value is not None 

2604 

2605 self.default: t.Any | t.Callable[[], t.Any] 

2606 

2607 if is_flag and default_is_missing and not self.required: 

2608 if multiple: 

2609 self.default = () 

2610 else: 

2611 self.default = False 

2612 

2613 if is_flag and flag_value is None: 

2614 flag_value = not self.default 

2615 

2616 self.type: types.ParamType 

2617 if is_flag and type is None: 

2618 # Re-guess the type from the flag value instead of the 

2619 # default. 

2620 self.type = types.convert_type(None, flag_value) 

2621 

2622 self.is_flag: bool = is_flag 

2623 self.is_bool_flag: bool = is_flag and isinstance(self.type, types.BoolParamType) 

2624 self.flag_value: t.Any = flag_value 

2625 

2626 # Counting 

2627 self.count = count 

2628 if count: 

2629 if type is None: 

2630 self.type = types.IntRange(min=0) 

2631 if default_is_missing: 

2632 self.default = 0 

2633 

2634 self.allow_from_autoenv = allow_from_autoenv 

2635 self.help = help 

2636 self.show_default = show_default 

2637 self.show_choices = show_choices 

2638 self.show_envvar = show_envvar 

2639 

2640 if __debug__: 

2641 if deprecated and prompt: 

2642 raise ValueError("`deprecated` options cannot use `prompt`.") 

2643 

2644 if self.nargs == -1: 

2645 raise TypeError("nargs=-1 is not supported for options.") 

2646 

2647 if self.prompt and self.is_flag and not self.is_bool_flag: 

2648 raise TypeError("'prompt' is not valid for non-boolean flag.") 

2649 

2650 if not self.is_bool_flag and self.secondary_opts: 

2651 raise TypeError("Secondary flag is not valid for non-boolean flag.") 

2652 

2653 if self.is_bool_flag and self.hide_input and self.prompt is not None: 

2654 raise TypeError( 

2655 "'prompt' with 'hide_input' is not valid for boolean flag." 

2656 ) 

2657 

2658 if self.count: 

2659 if self.multiple: 

2660 raise TypeError("'count' is not valid with 'multiple'.") 

2661 

2662 if self.is_flag: 

2663 raise TypeError("'count' is not valid with 'is_flag'.") 

2664 

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

2666 info_dict = super().to_info_dict() 

2667 info_dict.update( 

2668 help=self.help, 

2669 prompt=self.prompt, 

2670 is_flag=self.is_flag, 

2671 flag_value=self.flag_value, 

2672 count=self.count, 

2673 hidden=self.hidden, 

2674 ) 

2675 return info_dict 

2676 

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

2678 result = super().get_error_hint(ctx) 

2679 if self.show_envvar: 

2680 result += f" (env var: '{self.envvar}')" 

2681 return result 

2682 

2683 def _parse_decls( 

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

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

2686 opts = [] 

2687 secondary_opts = [] 

2688 name = None 

2689 possible_names = [] 

2690 

2691 for decl in decls: 

2692 if decl.isidentifier(): 

2693 if name is not None: 

2694 raise TypeError(f"Name '{name}' defined twice") 

2695 name = decl 

2696 else: 

2697 split_char = ";" if decl[:1] == "/" else "/" 

2698 if split_char in decl: 

2699 first, second = decl.split(split_char, 1) 

2700 first = first.rstrip() 

2701 if first: 

2702 possible_names.append(_split_opt(first)) 

2703 opts.append(first) 

2704 second = second.lstrip() 

2705 if second: 

2706 secondary_opts.append(second.lstrip()) 

2707 if first == second: 

2708 raise ValueError( 

2709 f"Boolean option {decl!r} cannot use the" 

2710 " same flag for true/false." 

2711 ) 

2712 else: 

2713 possible_names.append(_split_opt(decl)) 

2714 opts.append(decl) 

2715 

2716 if name is None and possible_names: 

2717 possible_names.sort(key=lambda x: -len(x[0])) # group long options first 

2718 name = possible_names[0][1].replace("-", "_").lower() 

2719 if not name.isidentifier(): 

2720 name = None 

2721 

2722 if name is None: 

2723 if not expose_value: 

2724 return None, opts, secondary_opts 

2725 raise TypeError( 

2726 f"Could not determine name for option with declarations {decls!r}" 

2727 ) 

2728 

2729 if not opts and not secondary_opts: 

2730 raise TypeError( 

2731 f"No options defined but a name was passed ({name})." 

2732 " Did you mean to declare an argument instead? Did" 

2733 f" you mean to pass '--{name}'?" 

2734 ) 

2735 

2736 return name, opts, secondary_opts 

2737 

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

2739 if self.multiple: 

2740 action = "append" 

2741 elif self.count: 

2742 action = "count" 

2743 else: 

2744 action = "store" 

2745 

2746 if self.is_flag: 

2747 action = f"{action}_const" 

2748 

2749 if self.is_bool_flag and self.secondary_opts: 

2750 parser.add_option( 

2751 obj=self, opts=self.opts, dest=self.name, action=action, const=True 

2752 ) 

2753 parser.add_option( 

2754 obj=self, 

2755 opts=self.secondary_opts, 

2756 dest=self.name, 

2757 action=action, 

2758 const=False, 

2759 ) 

2760 else: 

2761 parser.add_option( 

2762 obj=self, 

2763 opts=self.opts, 

2764 dest=self.name, 

2765 action=action, 

2766 const=self.flag_value, 

2767 ) 

2768 else: 

2769 parser.add_option( 

2770 obj=self, 

2771 opts=self.opts, 

2772 dest=self.name, 

2773 action=action, 

2774 nargs=self.nargs, 

2775 ) 

2776 

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

2778 if self.hidden: 

2779 return None 

2780 

2781 any_prefix_is_slash = False 

2782 

2783 def _write_opts(opts: cabc.Sequence[str]) -> str: 

2784 nonlocal any_prefix_is_slash 

2785 

2786 rv, any_slashes = join_options(opts) 

2787 

2788 if any_slashes: 

2789 any_prefix_is_slash = True 

2790 

2791 if not self.is_flag and not self.count: 

2792 rv += f" {self.make_metavar(ctx=ctx)}" 

2793 

2794 return rv 

2795 

2796 rv = [_write_opts(self.opts)] 

2797 

2798 if self.secondary_opts: 

2799 rv.append(_write_opts(self.secondary_opts)) 

2800 

2801 help = self.help or "" 

2802 

2803 extra = self.get_help_extra(ctx) 

2804 extra_items = [] 

2805 if "envvars" in extra: 

2806 extra_items.append( 

2807 _("env var: {var}").format(var=", ".join(extra["envvars"])) 

2808 ) 

2809 if "default" in extra: 

2810 extra_items.append(_("default: {default}").format(default=extra["default"])) 

2811 if "range" in extra: 

2812 extra_items.append(extra["range"]) 

2813 if "required" in extra: 

2814 extra_items.append(_(extra["required"])) 

2815 

2816 if extra_items: 

2817 extra_str = "; ".join(extra_items) 

2818 help = f"{help} [{extra_str}]" if help else f"[{extra_str}]" 

2819 

2820 return ("; " if any_prefix_is_slash else " / ").join(rv), help 

2821 

2822 def get_help_extra(self, ctx: Context) -> types.OptionHelpExtra: 

2823 extra: types.OptionHelpExtra = {} 

2824 

2825 if self.show_envvar: 

2826 envvar = self.envvar 

2827 

2828 if envvar is None: 

2829 if ( 

2830 self.allow_from_autoenv 

2831 and ctx.auto_envvar_prefix is not None 

2832 and self.name is not None 

2833 ): 

2834 envvar = f"{ctx.auto_envvar_prefix}_{self.name.upper()}" 

2835 

2836 if envvar is not None: 

2837 if isinstance(envvar, str): 

2838 extra["envvars"] = (envvar,) 

2839 else: 

2840 extra["envvars"] = tuple(str(d) for d in envvar) 

2841 

2842 # Temporarily enable resilient parsing to avoid type casting 

2843 # failing for the default. Might be possible to extend this to 

2844 # help formatting in general. 

2845 resilient = ctx.resilient_parsing 

2846 ctx.resilient_parsing = True 

2847 

2848 try: 

2849 default_value = self.get_default(ctx, call=False) 

2850 finally: 

2851 ctx.resilient_parsing = resilient 

2852 

2853 show_default = False 

2854 show_default_is_str = False 

2855 

2856 if self.show_default is not None: 

2857 if isinstance(self.show_default, str): 

2858 show_default_is_str = show_default = True 

2859 else: 

2860 show_default = self.show_default 

2861 elif ctx.show_default is not None: 

2862 show_default = ctx.show_default 

2863 

2864 if show_default_is_str or (show_default and (default_value is not None)): 

2865 if show_default_is_str: 

2866 default_string = f"({self.show_default})" 

2867 elif isinstance(default_value, (list, tuple)): 

2868 default_string = ", ".join(str(d) for d in default_value) 

2869 elif inspect.isfunction(default_value): 

2870 default_string = _("(dynamic)") 

2871 elif self.is_bool_flag and self.secondary_opts: 

2872 # For boolean flags that have distinct True/False opts, 

2873 # use the opt without prefix instead of the value. 

2874 default_string = _split_opt( 

2875 (self.opts if default_value else self.secondary_opts)[0] 

2876 )[1] 

2877 elif self.is_bool_flag and not self.secondary_opts and not default_value: 

2878 default_string = "" 

2879 elif default_value == "": 

2880 default_string = '""' 

2881 else: 

2882 default_string = str(default_value) 

2883 

2884 if default_string: 

2885 extra["default"] = default_string 

2886 

2887 if ( 

2888 isinstance(self.type, types._NumberRangeBase) 

2889 # skip count with default range type 

2890 and not (self.count and self.type.min == 0 and self.type.max is None) 

2891 ): 

2892 range_str = self.type._describe_range() 

2893 

2894 if range_str: 

2895 extra["range"] = range_str 

2896 

2897 if self.required: 

2898 extra["required"] = "required" 

2899 

2900 return extra 

2901 

2902 @t.overload 

2903 def get_default( 

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

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

2906 

2907 @t.overload 

2908 def get_default( 

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

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

2911 

2912 def get_default( 

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

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

2915 # If we're a non boolean flag our default is more complex because 

2916 # we need to look at all flags in the same group to figure out 

2917 # if we're the default one in which case we return the flag 

2918 # value as default. 

2919 if self.is_flag and not self.is_bool_flag: 

2920 for param in ctx.command.params: 

2921 if param.name == self.name and param.default: 

2922 return t.cast(Option, param).flag_value 

2923 

2924 return None 

2925 

2926 return super().get_default(ctx, call=call) 

2927 

2928 def prompt_for_value(self, ctx: Context) -> t.Any: 

2929 """This is an alternative flow that can be activated in the full 

2930 value processing if a value does not exist. It will prompt the 

2931 user until a valid value exists and then returns the processed 

2932 value as result. 

2933 """ 

2934 assert self.prompt is not None 

2935 

2936 # Calculate the default before prompting anything to be stable. 

2937 default = self.get_default(ctx) 

2938 

2939 # If this is a prompt for a flag we need to handle this 

2940 # differently. 

2941 if self.is_bool_flag: 

2942 return confirm(self.prompt, default) 

2943 

2944 # If show_default is set to True/False, provide this to `prompt` as well. For 

2945 # non-bool values of `show_default`, we use `prompt`'s default behavior 

2946 prompt_kwargs: t.Any = {} 

2947 if isinstance(self.show_default, bool): 

2948 prompt_kwargs["show_default"] = self.show_default 

2949 

2950 return prompt( 

2951 self.prompt, 

2952 default=default, 

2953 type=self.type, 

2954 hide_input=self.hide_input, 

2955 show_choices=self.show_choices, 

2956 confirmation_prompt=self.confirmation_prompt, 

2957 value_proc=lambda x: self.process_value(ctx, x), 

2958 **prompt_kwargs, 

2959 ) 

2960 

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

2962 rv = super().resolve_envvar_value(ctx) 

2963 

2964 if rv is not None: 

2965 if self.is_flag and self.flag_value: 

2966 return str(self.flag_value) 

2967 return rv 

2968 

2969 if ( 

2970 self.allow_from_autoenv 

2971 and ctx.auto_envvar_prefix is not None 

2972 and self.name is not None 

2973 ): 

2974 envvar = f"{ctx.auto_envvar_prefix}_{self.name.upper()}" 

2975 rv = os.environ.get(envvar) 

2976 

2977 if rv: 

2978 return rv 

2979 

2980 return None 

2981 

2982 def value_from_envvar(self, ctx: Context) -> t.Any | None: 

2983 rv: t.Any | None = self.resolve_envvar_value(ctx) 

2984 

2985 if rv is None: 

2986 return None 

2987 

2988 value_depth = (self.nargs != 1) + bool(self.multiple) 

2989 

2990 if value_depth > 0: 

2991 rv = self.type.split_envvar_value(rv) 

2992 

2993 if self.multiple and self.nargs != 1: 

2994 rv = batch(rv, self.nargs) 

2995 

2996 return rv 

2997 

2998 def consume_value( 

2999 self, ctx: Context, opts: cabc.Mapping[str, Parameter] 

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

3001 value, source = super().consume_value(ctx, opts) 

3002 

3003 # The parser will emit a sentinel value if the option can be 

3004 # given as a flag without a value. This is different from None 

3005 # to distinguish from the flag not being given at all. 

3006 if value is _flag_needs_value: 

3007 if self.prompt is not None and not ctx.resilient_parsing: 

3008 value = self.prompt_for_value(ctx) 

3009 source = ParameterSource.PROMPT 

3010 else: 

3011 value = self.flag_value 

3012 source = ParameterSource.COMMANDLINE 

3013 

3014 elif ( 

3015 self.multiple 

3016 and value is not None 

3017 and any(v is _flag_needs_value for v in value) 

3018 ): 

3019 value = [self.flag_value if v is _flag_needs_value else v for v in value] 

3020 source = ParameterSource.COMMANDLINE 

3021 

3022 # The value wasn't set, or used the param's default, prompt if 

3023 # prompting is enabled. 

3024 elif ( 

3025 source in {None, ParameterSource.DEFAULT} 

3026 and self.prompt is not None 

3027 and (self.required or self.prompt_required) 

3028 and not ctx.resilient_parsing 

3029 ): 

3030 value = self.prompt_for_value(ctx) 

3031 source = ParameterSource.PROMPT 

3032 

3033 return value, source 

3034 

3035 

3036class Argument(Parameter): 

3037 """Arguments are positional parameters to a command. They generally 

3038 provide fewer features than options but can have infinite ``nargs`` 

3039 and are required by default. 

3040 

3041 All parameters are passed onwards to the constructor of :class:`Parameter`. 

3042 """ 

3043 

3044 param_type_name = "argument" 

3045 

3046 def __init__( 

3047 self, 

3048 param_decls: cabc.Sequence[str], 

3049 required: bool | None = None, 

3050 **attrs: t.Any, 

3051 ) -> None: 

3052 if required is None: 

3053 if attrs.get("default") is not None: 

3054 required = False 

3055 else: 

3056 required = attrs.get("nargs", 1) > 0 

3057 

3058 if "multiple" in attrs: 

3059 raise TypeError("__init__() got an unexpected keyword argument 'multiple'.") 

3060 

3061 super().__init__(param_decls, required=required, **attrs) 

3062 

3063 if __debug__: 

3064 if self.default is not None and self.nargs == -1: 

3065 raise TypeError("'default' is not supported for nargs=-1.") 

3066 

3067 @property 

3068 def human_readable_name(self) -> str: 

3069 if self.metavar is not None: 

3070 return self.metavar 

3071 return self.name.upper() # type: ignore 

3072 

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

3074 if self.metavar is not None: 

3075 return self.metavar 

3076 var = self.type.get_metavar(param=self, ctx=ctx) 

3077 if not var: 

3078 var = self.name.upper() # type: ignore 

3079 if self.deprecated: 

3080 var += "!" 

3081 if not self.required: 

3082 var = f"[{var}]" 

3083 if self.nargs != 1: 

3084 var += "..." 

3085 return var 

3086 

3087 def _parse_decls( 

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

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

3090 if not decls: 

3091 if not expose_value: 

3092 return None, [], [] 

3093 raise TypeError("Argument is marked as exposed, but does not have a name.") 

3094 if len(decls) == 1: 

3095 name = arg = decls[0] 

3096 name = name.replace("-", "_").lower() 

3097 else: 

3098 raise TypeError( 

3099 "Arguments take exactly one parameter declaration, got" 

3100 f" {len(decls)}: {decls}." 

3101 ) 

3102 return name, [arg], [] 

3103 

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

3105 return [self.make_metavar(ctx)] 

3106 

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

3108 return f"'{self.make_metavar(ctx)}'" 

3109 

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

3111 parser.add_argument(dest=self.name, nargs=self.nargs, obj=self) 

3112 

3113 

3114def __getattr__(name: str) -> object: 

3115 import warnings 

3116 

3117 if name == "BaseCommand": 

3118 warnings.warn( 

3119 "'BaseCommand' is deprecated and will be removed in Click 9.0. Use" 

3120 " 'Command' instead.", 

3121 DeprecationWarning, 

3122 stacklevel=2, 

3123 ) 

3124 return _BaseCommand 

3125 

3126 if name == "MultiCommand": 

3127 warnings.warn( 

3128 "'MultiCommand' is deprecated and will be removed in Click 9.0. Use" 

3129 " 'Group' instead.", 

3130 DeprecationWarning, 

3131 stacklevel=2, 

3132 ) 

3133 return _MultiCommand 

3134 

3135 raise AttributeError(name)