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

1158 statements  

« prev     ^ index     » next       coverage.py v7.3.2, created at 2023-12-09 06:03 +0000

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 contextlib import AbstractContextManager 

12from contextlib import contextmanager 

13from contextlib import ExitStack 

14from functools import update_wrapper 

15from gettext import gettext as _ 

16from gettext import ngettext 

17from itertools import repeat 

18from types import TracebackType 

19 

20from . import types 

21from .exceptions import Abort 

22from .exceptions import BadParameter 

23from .exceptions import ClickException 

24from .exceptions import Exit 

25from .exceptions import MissingParameter 

26from .exceptions import UsageError 

27from .formatting import HelpFormatter 

28from .formatting import join_options 

29from .globals import pop_context 

30from .globals import push_context 

31from .parser import _flag_needs_value 

32from .parser import _OptionParser 

33from .parser import _split_opt 

34from .termui import confirm 

35from .termui import prompt 

36from .termui import style 

37from .utils import _detect_program_name 

38from .utils import _expand_args 

39from .utils import echo 

40from .utils import make_default_short_help 

41from .utils import make_str 

42from .utils import PacifyFlushWrapper 

43 

44if t.TYPE_CHECKING: 

45 from .shell_completion import CompletionItem 

46 

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

48V = t.TypeVar("V") 

49 

50 

51def _complete_visible_commands( 

52 ctx: Context, incomplete: str 

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

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

55 incomplete value and aren't hidden. 

56 

57 :param ctx: Invocation context for the group. 

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

59 """ 

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

61 

62 for name in multi.list_commands(ctx): 

63 if name.startswith(incomplete): 

64 command = multi.get_command(ctx, name) 

65 

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

67 yield name, command 

68 

69 

70def _check_nested_chain( 

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

72) -> None: 

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

74 return 

75 

76 if register: 

77 message = ( 

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

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

80 ) 

81 else: 

82 message = ( 

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

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

85 ) 

86 

87 raise RuntimeError(message) 

88 

89 

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

91 return list(zip(*repeat(iter(iterable), batch_size))) 

92 

93 

94@contextmanager 

95def augment_usage_errors( 

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

97) -> cabc.Iterator[None]: 

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

99 try: 

100 yield 

101 except BadParameter as e: 

102 if e.ctx is None: 

103 e.ctx = ctx 

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

105 e.param = param 

106 raise 

107 except UsageError as e: 

108 if e.ctx is None: 

109 e.ctx = ctx 

110 raise 

111 

112 

113def iter_params_for_processing( 

114 invocation_order: cabc.Sequence[Parameter], 

115 declaration_order: cabc.Sequence[Parameter], 

116) -> list[Parameter]: 

117 """Given a sequence of parameters in the order as should be considered 

118 for processing and an iterable of parameters that exist, this returns 

119 a list in the correct order as they should be processed. 

120 """ 

121 

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

123 try: 

124 idx: float = invocation_order.index(item) 

125 except ValueError: 

126 idx = float("inf") 

127 

128 return not item.is_eager, idx 

129 

130 return sorted(declaration_order, key=sort_key) 

131 

132 

133class ParameterSource(enum.Enum): 

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

135 parameter's value. 

136 

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

138 source for a parameter by name. 

139 

140 .. versionchanged:: 8.0 

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

142 

143 .. versionchanged:: 8.0 

144 Added the ``PROMPT`` value. 

145 """ 

146 

147 COMMANDLINE = enum.auto() 

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

149 ENVIRONMENT = enum.auto() 

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

151 DEFAULT = enum.auto() 

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

153 DEFAULT_MAP = enum.auto() 

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

155 PROMPT = enum.auto() 

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

157 

158 

159class Context: 

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

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

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

163 

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

165 control special execution features such as reading data from 

166 environment variables. 

167 

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

169 :meth:`close` on teardown. 

170 

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

172 :param parent: the parent context. 

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

174 is the most descriptive name for the script or 

175 command. For the toplevel script it is usually 

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

177 the name of the script. 

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

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

180 variables. If this is `None` then reading 

181 from environment variables is disabled. This 

182 does not affect manually set environment 

183 variables which are always read. 

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

185 for parameters. 

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

187 inherit from parent context. If no context 

188 defines the terminal width then auto 

189 detection will be applied. 

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

191 Click (this currently only affects help 

192 pages). This defaults to 80 characters if 

193 not overridden. In other words: even if the 

194 terminal is larger than that, Click will not 

195 format things wider than 80 characters by 

196 default. In addition to that, formatters might 

197 add some safety mapping on the right. 

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

199 parse without any interactivity or callback 

200 invocation. Default values will also be 

201 ignored. This is useful for implementing 

202 things such as completion support. 

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

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

205 kept on the context. The default is to inherit 

206 from the command. 

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

208 and arguments cannot be mixed. The 

209 default is to inherit from the command. 

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

211 not know and keeps them for later 

212 processing. 

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

214 the default help parameter is named. The 

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

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

217 normalize tokens (options, choices, 

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

219 implement case insensitive behavior. 

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

221 default is autodetection. This is only needed if ANSI 

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

223 default not the case. This for instance would affect 

224 help output. 

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

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

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

228 specific command. 

229 

230 .. versionchanged:: 8.2 

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

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

233 

234 .. versionchanged:: 8.1 

235 The ``show_default`` parameter is overridden by 

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

237 

238 .. versionchanged:: 8.0 

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

240 parent context. 

241 

242 .. versionchanged:: 7.1 

243 Added the ``show_default`` parameter. 

244 

245 .. versionchanged:: 4.0 

246 Added the ``color``, ``ignore_unknown_options``, and 

247 ``max_content_width`` parameters. 

248 

249 .. versionchanged:: 3.0 

250 Added the ``allow_extra_args`` and ``allow_interspersed_args`` 

251 parameters. 

252 

253 .. versionchanged:: 2.0 

254 Added the ``resilient_parsing``, ``help_option_names``, and 

255 ``token_normalize_func`` parameters. 

256 """ 

257 

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

259 #: 

260 #: .. versionadded:: 8.0 

261 formatter_class: type[HelpFormatter] = HelpFormatter 

262 

263 def __init__( 

264 self, 

265 command: Command, 

266 parent: Context | None = None, 

267 info_name: str | None = None, 

268 obj: t.Any | None = None, 

269 auto_envvar_prefix: str | None = None, 

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

271 terminal_width: int | None = None, 

272 max_content_width: int | None = None, 

273 resilient_parsing: bool = False, 

274 allow_extra_args: bool | None = None, 

275 allow_interspersed_args: bool | None = None, 

276 ignore_unknown_options: bool | None = None, 

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

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

279 color: bool | None = None, 

280 show_default: bool | None = None, 

281 ) -> None: 

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

283 self.parent = parent 

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

285 self.command = command 

286 #: the descriptive information name 

287 self.info_name = info_name 

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

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

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

291 #: the leftover arguments. 

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

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

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

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

296 #: to implement nested parsing. 

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

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

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

300 

301 if obj is None and parent is not None: 

302 obj = parent.obj 

303 

304 #: the user object stored. 

305 self.obj: t.Any = obj 

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

307 

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

309 if ( 

310 default_map is None 

311 and info_name is not None 

312 and parent is not None 

313 and parent.default_map is not None 

314 ): 

315 default_map = parent.default_map.get(info_name) 

316 

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

318 

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

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

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

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

323 #: the name of the subcommand to execute. 

324 #: 

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

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

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

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

329 self.invoked_subcommand: str | None = None 

330 

331 if terminal_width is None and parent is not None: 

332 terminal_width = parent.terminal_width 

333 

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

335 self.terminal_width: int | None = terminal_width 

336 

337 if max_content_width is None and parent is not None: 

338 max_content_width = parent.max_content_width 

339 

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

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

342 self.max_content_width: int | None = max_content_width 

343 

344 if allow_extra_args is None: 

345 allow_extra_args = command.allow_extra_args 

346 

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

348 #: fail on parsing. 

349 #: 

350 #: .. versionadded:: 3.0 

351 self.allow_extra_args = allow_extra_args 

352 

353 if allow_interspersed_args is None: 

354 allow_interspersed_args = command.allow_interspersed_args 

355 

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

357 #: options or not. 

358 #: 

359 #: .. versionadded:: 3.0 

360 self.allow_interspersed_args: bool = allow_interspersed_args 

361 

362 if ignore_unknown_options is None: 

363 ignore_unknown_options = command.ignore_unknown_options 

364 

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

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

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

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

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

370 #: forward all arguments. 

371 #: 

372 #: .. versionadded:: 4.0 

373 self.ignore_unknown_options: bool = ignore_unknown_options 

374 

375 if help_option_names is None: 

376 if parent is not None: 

377 help_option_names = parent.help_option_names 

378 else: 

379 help_option_names = ["--help"] 

380 

381 #: The names for the help options. 

382 self.help_option_names: list[str] = help_option_names 

383 

384 if token_normalize_func is None and parent is not None: 

385 token_normalize_func = parent.token_normalize_func 

386 

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

388 #: options, choices, commands etc. 

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

390 

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

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

393 #: will be ignored. Useful for completion. 

394 self.resilient_parsing: bool = resilient_parsing 

395 

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

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

398 # prefix automatically. 

399 if auto_envvar_prefix is None: 

400 if ( 

401 parent is not None 

402 and parent.auto_envvar_prefix is not None 

403 and self.info_name is not None 

404 ): 

405 auto_envvar_prefix = ( 

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

407 ) 

408 else: 

409 auto_envvar_prefix = auto_envvar_prefix.upper() 

410 

411 if auto_envvar_prefix is not None: 

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

413 

414 self.auto_envvar_prefix: str | None = auto_envvar_prefix 

415 

416 if color is None and parent is not None: 

417 color = parent.color 

418 

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

420 self.color: bool | None = color 

421 

422 if show_default is None and parent is not None: 

423 show_default = parent.show_default 

424 

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

426 self.show_default: bool | None = show_default 

427 

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

429 self._depth = 0 

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

431 self._exit_stack = ExitStack() 

432 

433 @property 

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

435 import warnings 

436 

437 warnings.warn( 

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

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

440 DeprecationWarning, 

441 stacklevel=2, 

442 ) 

443 return self._protected_args 

444 

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

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

447 user-facing documentation. This traverses the entire CLI 

448 structure. 

449 

450 .. code-block:: python 

451 

452 with Context(cli) as ctx: 

453 info = ctx.to_info_dict() 

454 

455 .. versionadded:: 8.0 

456 """ 

457 return { 

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

459 "info_name": self.info_name, 

460 "allow_extra_args": self.allow_extra_args, 

461 "allow_interspersed_args": self.allow_interspersed_args, 

462 "ignore_unknown_options": self.ignore_unknown_options, 

463 "auto_envvar_prefix": self.auto_envvar_prefix, 

464 } 

465 

466 def __enter__(self) -> Context: 

467 self._depth += 1 

468 push_context(self) 

469 return self 

470 

471 def __exit__( 

472 self, 

473 exc_type: type[BaseException] | None, 

474 exc_value: BaseException | None, 

475 tb: TracebackType | None, 

476 ) -> None: 

477 self._depth -= 1 

478 if self._depth == 0: 

479 self.close() 

480 pop_context() 

481 

482 @contextmanager 

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

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

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

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

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

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

489 

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

491 used as a context manager. 

492 

493 Example usage:: 

494 

495 with ctx.scope(): 

496 assert get_current_context() is ctx 

497 

498 This is equivalent:: 

499 

500 with ctx: 

501 assert get_current_context() is ctx 

502 

503 .. versionadded:: 5.0 

504 

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

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

507 some situations the context only wants to be 

508 temporarily pushed in which case this can be disabled. 

509 Nested pushes automatically defer the cleanup. 

510 """ 

511 if not cleanup: 

512 self._depth += 1 

513 try: 

514 with self as rv: 

515 yield rv 

516 finally: 

517 if not cleanup: 

518 self._depth -= 1 

519 

520 @property 

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

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

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

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

525 that code to manage this dictionary well. 

526 

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

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

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

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

531 the system. 

532 

533 Example usage:: 

534 

535 LANG_KEY = f'{__name__}.lang' 

536 

537 def set_language(value): 

538 ctx = get_current_context() 

539 ctx.meta[LANG_KEY] = value 

540 

541 def get_language(): 

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

543 

544 .. versionadded:: 5.0 

545 """ 

546 return self._meta 

547 

548 def make_formatter(self) -> HelpFormatter: 

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

550 usage output. 

551 

552 To quickly customize the formatter class used without overriding 

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

554 

555 .. versionchanged:: 8.0 

556 Added the :attr:`formatter_class` attribute. 

557 """ 

558 return self.formatter_class( 

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

560 ) 

561 

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

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

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

565 popped. 

566 

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

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

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

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

571 

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

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

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

575 

576 .. code-block:: python 

577 

578 @click.group() 

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

580 @click.pass_context 

581 def cli(ctx): 

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

583 

584 :param context_manager: The context manager to enter. 

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

586 

587 .. versionadded:: 8.0 

588 """ 

589 return self._exit_stack.enter_context(context_manager) 

590 

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

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

593 

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

595 execution. Resources that support Python's context manager 

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

597 registered with :meth:`with_resource` instead. 

598 

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

600 """ 

601 return self._exit_stack.callback(f) 

602 

603 def close(self) -> None: 

604 """Invoke all close callbacks registered with 

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

606 with :meth:`with_resource`. 

607 """ 

608 self._exit_stack.close() 

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

610 self._exit_stack = ExitStack() 

611 

612 @property 

613 def command_path(self) -> str: 

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

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

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

617 """ 

618 rv = "" 

619 if self.info_name is not None: 

620 rv = self.info_name 

621 if self.parent is not None: 

622 parent_command_path = [self.parent.command_path] 

623 

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

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

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

627 

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

629 return rv.lstrip() 

630 

631 def find_root(self) -> Context: 

632 """Finds the outermost context.""" 

633 node = self 

634 while node.parent is not None: 

635 node = node.parent 

636 return node 

637 

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

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

640 node: Context | None = self 

641 

642 while node is not None: 

643 if isinstance(node.obj, object_type): 

644 return node.obj 

645 

646 node = node.parent 

647 

648 return None 

649 

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

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

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

653 """ 

654 rv = self.find_object(object_type) 

655 if rv is None: 

656 self.obj = rv = object_type() 

657 return rv 

658 

659 @t.overload 

660 def lookup_default(self, name: str, call: t.Literal[True] = True) -> t.Any | None: 

661 ... 

662 

663 @t.overload 

664 def lookup_default( 

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

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

667 ... 

668 

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

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

671 

672 :param name: Name of the parameter. 

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

674 return the callable instead. 

675 

676 .. versionchanged:: 8.0 

677 Added the ``call`` parameter. 

678 """ 

679 if self.default_map is not None: 

680 value = self.default_map.get(name) 

681 

682 if call and callable(value): 

683 return value() 

684 

685 return value 

686 

687 return None 

688 

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

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

691 message. 

692 

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

694 """ 

695 raise UsageError(message, self) 

696 

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

698 """Aborts the script.""" 

699 raise Abort() 

700 

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

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

703 raise Exit(code) 

704 

705 def get_usage(self) -> str: 

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

707 context and command. 

708 """ 

709 return self.command.get_usage(self) 

710 

711 def get_help(self) -> str: 

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

713 context and command. 

714 """ 

715 return self.command.get_help(self) 

716 

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

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

719 for a new command. 

720 

721 :meta private: 

722 """ 

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

724 

725 @t.overload 

726 def invoke( 

727 __self, # noqa: B902 

728 __callback: t.Callable[..., V], 

729 *args: t.Any, 

730 **kwargs: t.Any, 

731 ) -> V: 

732 ... 

733 

734 @t.overload 

735 def invoke( 

736 __self, # noqa: B902 

737 __callback: Command, 

738 *args: t.Any, 

739 **kwargs: t.Any, 

740 ) -> t.Any: 

741 ... 

742 

743 def invoke( 

744 __self, # noqa: B902 

745 __callback: Command | t.Callable[..., V], 

746 *args: t.Any, 

747 **kwargs: t.Any, 

748 ) -> t.Any | V: 

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

750 are two ways to invoke this method: 

751 

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

753 keyword arguments are forwarded directly to the function. 

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

755 arguments are forwarded as well but proper click parameters 

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

757 will fill in defaults. 

758 

759 .. versionchanged:: 8.0 

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

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

762 

763 .. versionchanged:: 3.2 

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

765 """ 

766 if isinstance(__callback, Command): 

767 other_cmd = __callback 

768 

769 if other_cmd.callback is None: 

770 raise TypeError( 

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

772 ) 

773 else: 

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

775 

776 ctx = __self._make_sub_context(other_cmd) 

777 

778 for param in other_cmd.params: 

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

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

781 ctx, param.get_default(ctx) 

782 ) 

783 

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

785 # them on in subsequent calls. 

786 ctx.params.update(kwargs) 

787 else: 

788 ctx = __self 

789 

790 with augment_usage_errors(__self): 

791 with ctx: 

792 return __callback(*args, **kwargs) 

793 

794 def forward( 

795 __self, __cmd: Command, *args: t.Any, **kwargs: t.Any # noqa: B902 

796 ) -> 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 

867 :param deprecated: issues a message indicating that 

868 the command is deprecated. 

869 

870 .. versionchanged:: 8.2 

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

872 

873 .. versionchanged:: 8.1 

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

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

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

877 

878 .. versionchanged:: 8.0 

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

880 

881 .. versionchanged:: 7.1 

882 Added the ``no_args_is_help`` parameter. 

883 

884 .. versionchanged:: 2.0 

885 Added the ``context_settings`` parameter. 

886 """ 

887 

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

889 #: 

890 #: .. versionadded:: 8.0 

891 context_class: type[Context] = Context 

892 

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

894 allow_extra_args = False 

895 

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

897 allow_interspersed_args = True 

898 

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

900 ignore_unknown_options = False 

901 

902 def __init__( 

903 self, 

904 name: str | None, 

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

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

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

908 help: str | None = None, 

909 epilog: str | None = None, 

910 short_help: str | None = None, 

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

912 add_help_option: bool = True, 

913 no_args_is_help: bool = False, 

914 hidden: bool = False, 

915 deprecated: bool = False, 

916 ) -> None: 

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

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

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

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

921 self.name = name 

922 

923 if context_settings is None: 

924 context_settings = {} 

925 

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

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

928 

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

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

931 self.callback = callback 

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

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

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

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

936 self.help = help 

937 self.epilog = epilog 

938 self.options_metavar = options_metavar 

939 self.short_help = short_help 

940 self.add_help_option = add_help_option 

941 self.no_args_is_help = no_args_is_help 

942 self.hidden = hidden 

943 self.deprecated = deprecated 

944 

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

946 return { 

947 "name": self.name, 

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

949 "help": self.help, 

950 "epilog": self.epilog, 

951 "short_help": self.short_help, 

952 "hidden": self.hidden, 

953 "deprecated": self.deprecated, 

954 } 

955 

956 def __repr__(self) -> str: 

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

958 

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

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

961 

962 Calls :meth:`format_usage` internally. 

963 """ 

964 formatter = ctx.make_formatter() 

965 self.format_usage(ctx, formatter) 

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

967 

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

969 rv = self.params 

970 help_option = self.get_help_option(ctx) 

971 

972 if help_option is not None: 

973 rv = [*rv, help_option] 

974 

975 return rv 

976 

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

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

979 

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

981 """ 

982 pieces = self.collect_usage_pieces(ctx) 

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

984 

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

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

987 it as a list of strings. 

988 """ 

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

990 

991 for param in self.get_params(ctx): 

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

993 

994 return rv 

995 

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

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

998 all_names = set(ctx.help_option_names) 

999 for param in self.params: 

1000 all_names.difference_update(param.opts) 

1001 all_names.difference_update(param.secondary_opts) 

1002 return list(all_names) 

1003 

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

1005 """Returns the help option object.""" 

1006 help_options = self.get_help_option_names(ctx) 

1007 

1008 if not help_options or not self.add_help_option: 

1009 return None 

1010 

1011 def show_help(ctx: Context, param: Parameter, value: str) -> None: 

1012 if value and not ctx.resilient_parsing: 

1013 echo(ctx.get_help(), color=ctx.color) 

1014 ctx.exit() 

1015 

1016 return Option( 

1017 help_options, 

1018 is_flag=True, 

1019 is_eager=True, 

1020 expose_value=False, 

1021 callback=show_help, 

1022 help=_("Show this message and exit."), 

1023 ) 

1024 

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

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

1027 parser = _OptionParser(ctx) 

1028 for param in self.get_params(ctx): 

1029 param.add_to_parser(parser, ctx) 

1030 return parser 

1031 

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

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

1034 

1035 Calls :meth:`format_help` internally. 

1036 """ 

1037 formatter = ctx.make_formatter() 

1038 self.format_help(ctx, formatter) 

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

1040 

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

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

1043 long help string. 

1044 """ 

1045 if self.short_help: 

1046 text = inspect.cleandoc(self.short_help) 

1047 elif self.help: 

1048 text = make_default_short_help(self.help, limit) 

1049 else: 

1050 text = "" 

1051 

1052 if self.deprecated: 

1053 text = _("(Deprecated) {text}").format(text=text) 

1054 

1055 return text.strip() 

1056 

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

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

1059 

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

1061 

1062 This calls the following methods: 

1063 

1064 - :meth:`format_usage` 

1065 - :meth:`format_help_text` 

1066 - :meth:`format_options` 

1067 - :meth:`format_epilog` 

1068 """ 

1069 self.format_usage(ctx, formatter) 

1070 self.format_help_text(ctx, formatter) 

1071 self.format_options(ctx, formatter) 

1072 self.format_epilog(ctx, formatter) 

1073 

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

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

1076 if self.help is not None: 

1077 # truncate the help text to the first form feed 

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

1079 else: 

1080 text = "" 

1081 

1082 if self.deprecated: 

1083 text = _("(Deprecated) {text}").format(text=text) 

1084 

1085 if text: 

1086 formatter.write_paragraph() 

1087 

1088 with formatter.indentation(): 

1089 formatter.write_text(text) 

1090 

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

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

1093 opts = [] 

1094 for param in self.get_params(ctx): 

1095 rv = param.get_help_record(ctx) 

1096 if rv is not None: 

1097 opts.append(rv) 

1098 

1099 if opts: 

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

1101 formatter.write_dl(opts) 

1102 

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

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

1105 if self.epilog: 

1106 epilog = inspect.cleandoc(self.epilog) 

1107 formatter.write_paragraph() 

1108 

1109 with formatter.indentation(): 

1110 formatter.write_text(epilog) 

1111 

1112 def make_context( 

1113 self, 

1114 info_name: str | None, 

1115 args: list[str], 

1116 parent: Context | None = None, 

1117 **extra: t.Any, 

1118 ) -> Context: 

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

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

1121 invoke the actual command callback though. 

1122 

1123 To quickly customize the context class used without overriding 

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

1125 

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

1127 is the most descriptive name for the script or 

1128 command. For the toplevel script it's usually 

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

1130 the name of the command. 

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

1132 :param parent: the parent context if available. 

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

1134 constructor. 

1135 

1136 .. versionchanged:: 8.0 

1137 Added the :attr:`context_class` attribute. 

1138 """ 

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

1140 if key not in extra: 

1141 extra[key] = value 

1142 

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

1144 

1145 with ctx.scope(cleanup=False): 

1146 self.parse_args(ctx, args) 

1147 return ctx 

1148 

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

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

1151 echo(ctx.get_help(), color=ctx.color) 

1152 ctx.exit() 

1153 

1154 parser = self.make_parser(ctx) 

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

1156 

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

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

1159 

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

1161 ctx.fail( 

1162 ngettext( 

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

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

1165 len(args), 

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

1167 ) 

1168 

1169 ctx.args = args 

1170 ctx._opt_prefixes.update(parser._opt_prefixes) 

1171 return args 

1172 

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

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

1175 in the right way. 

1176 """ 

1177 if self.deprecated: 

1178 message = _( 

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

1180 ).format(name=self.name) 

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

1182 

1183 if self.callback is not None: 

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

1185 

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

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

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

1189 

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

1191 commands are valid at any point during command completion. 

1192 

1193 :param ctx: Invocation context for this command. 

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

1195 

1196 .. versionadded:: 8.0 

1197 """ 

1198 from click.shell_completion import CompletionItem 

1199 

1200 results: list[CompletionItem] = [] 

1201 

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

1203 for param in self.get_params(ctx): 

1204 if ( 

1205 not isinstance(param, Option) 

1206 or param.hidden 

1207 or ( 

1208 not param.multiple 

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

1210 is ParameterSource.COMMANDLINE 

1211 ) 

1212 ): 

1213 continue 

1214 

1215 results.extend( 

1216 CompletionItem(name, help=param.help) 

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

1218 if name.startswith(incomplete) 

1219 ) 

1220 

1221 while ctx.parent is not None: 

1222 ctx = ctx.parent 

1223 

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

1225 results.extend( 

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

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

1228 if name not in ctx._protected_args 

1229 ) 

1230 

1231 return results 

1232 

1233 @t.overload 

1234 def main( 

1235 self, 

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

1237 prog_name: str | None = None, 

1238 complete_var: str | None = None, 

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

1240 **extra: t.Any, 

1241 ) -> t.NoReturn: 

1242 ... 

1243 

1244 @t.overload 

1245 def main( 

1246 self, 

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

1248 prog_name: str | None = None, 

1249 complete_var: str | None = None, 

1250 standalone_mode: bool = ..., 

1251 **extra: t.Any, 

1252 ) -> t.Any: 

1253 ... 

1254 

1255 def main( 

1256 self, 

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

1258 prog_name: str | None = None, 

1259 complete_var: str | None = None, 

1260 standalone_mode: bool = True, 

1261 windows_expand_args: bool = True, 

1262 **extra: t.Any, 

1263 ) -> t.Any: 

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

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

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

1267 needs to be caught. 

1268 

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

1270 a :class:`Command`. 

1271 

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

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

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

1275 the program name is constructed by taking the file 

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

1277 :param complete_var: the environment variable that controls the 

1278 bash completion support. The default is 

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

1280 uppercase. 

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

1282 in standalone mode. Click will then 

1283 handle exceptions and convert them into 

1284 error messages and the function will never 

1285 return but shut down the interpreter. If 

1286 this is set to `False` they will be 

1287 propagated to the caller and the return 

1288 value of this function is the return value 

1289 of :meth:`invoke`. 

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

1291 env vars in command line args on Windows. 

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

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

1294 

1295 .. versionchanged:: 8.0.1 

1296 Added the ``windows_expand_args`` parameter to allow 

1297 disabling command line arg expansion on Windows. 

1298 

1299 .. versionchanged:: 8.0 

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

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

1302 

1303 .. versionchanged:: 3.0 

1304 Added the ``standalone_mode`` parameter. 

1305 """ 

1306 if args is None: 

1307 args = sys.argv[1:] 

1308 

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

1310 args = _expand_args(args) 

1311 else: 

1312 args = list(args) 

1313 

1314 if prog_name is None: 

1315 prog_name = _detect_program_name() 

1316 

1317 # Process shell completion requests and exit early. 

1318 self._main_shell_completion(extra, prog_name, complete_var) 

1319 

1320 try: 

1321 try: 

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

1323 rv = self.invoke(ctx) 

1324 if not standalone_mode: 

1325 return rv 

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

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

1328 # has obvious effects 

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

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

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

1332 # by its truthiness/falsiness 

1333 ctx.exit() 

1334 except (EOFError, KeyboardInterrupt) as e: 

1335 echo(file=sys.stderr) 

1336 raise Abort() from e 

1337 except ClickException as e: 

1338 if not standalone_mode: 

1339 raise 

1340 e.show() 

1341 sys.exit(e.exit_code) 

1342 except OSError as e: 

1343 if e.errno == errno.EPIPE: 

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

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

1346 sys.exit(1) 

1347 else: 

1348 raise 

1349 except Exit as e: 

1350 if standalone_mode: 

1351 sys.exit(e.exit_code) 

1352 else: 

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

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

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

1356 # would return its result 

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

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

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

1360 # tell the difference between the two 

1361 return e.exit_code 

1362 except Abort: 

1363 if not standalone_mode: 

1364 raise 

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

1366 sys.exit(1) 

1367 

1368 def _main_shell_completion( 

1369 self, 

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

1371 prog_name: str, 

1372 complete_var: str | None = None, 

1373 ) -> None: 

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

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

1376 program is invoked. 

1377 

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

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

1380 the completion instruction. Defaults to 

1381 ``_{PROG_NAME}_COMPLETE``. 

1382 

1383 .. versionchanged:: 8.2.0 

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

1385 """ 

1386 if complete_var is None: 

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

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

1389 

1390 instruction = os.environ.get(complete_var) 

1391 

1392 if not instruction: 

1393 return 

1394 

1395 from .shell_completion import shell_complete 

1396 

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

1398 sys.exit(rv) 

1399 

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

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

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

1403 

1404 

1405class _FakeSubclassCheck(type): 

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

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

1408 

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

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

1411 

1412 

1413class _BaseCommand(Command, metaclass=_FakeSubclassCheck): 

1414 """ 

1415 .. deprecated:: 8.2 

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

1417 """ 

1418 

1419 

1420class Group(Command): 

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

1422 

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

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

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

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

1427 subcommand is not given. 

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

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

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

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

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

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

1434 matched, and so on. 

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

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

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

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

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

1440 ``chain`` is enabled. 

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

1442 

1443 .. versionchanged:: 8.2 

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

1445 

1446 .. versionchanged:: 8.0 

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

1448 """ 

1449 

1450 allow_extra_args = True 

1451 allow_interspersed_args = False 

1452 

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

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

1455 #: subcommands use a custom command class. 

1456 #: 

1457 #: .. versionadded:: 8.0 

1458 command_class: type[Command] | None = None 

1459 

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

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

1462 #: subgroups use a custom group class. 

1463 #: 

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

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

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

1467 #: custom groups. 

1468 #: 

1469 #: .. versionadded:: 8.0 

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

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

1472 

1473 def __init__( 

1474 self, 

1475 name: str | None = None, 

1476 commands: cabc.MutableMapping[str, Command] 

1477 | cabc.Sequence[Command] 

1478 | None = None, 

1479 invoke_without_command: bool = False, 

1480 no_args_is_help: bool | None = None, 

1481 subcommand_metavar: str | None = None, 

1482 chain: bool = False, 

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

1484 **kwargs: t.Any, 

1485 ) -> None: 

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

1487 

1488 if commands is None: 

1489 commands = {} 

1490 elif isinstance(commands, abc.Sequence): 

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

1492 

1493 #: The registered subcommands by their exported names. 

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

1495 

1496 if no_args_is_help is None: 

1497 no_args_is_help = not invoke_without_command 

1498 

1499 self.no_args_is_help = no_args_is_help 

1500 self.invoke_without_command = invoke_without_command 

1501 

1502 if subcommand_metavar is None: 

1503 if chain: 

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

1505 else: 

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

1507 

1508 self.subcommand_metavar = subcommand_metavar 

1509 self.chain = chain 

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

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

1512 self._result_callback = result_callback 

1513 

1514 if self.chain: 

1515 for param in self.params: 

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

1517 raise RuntimeError( 

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

1519 ) 

1520 

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

1522 info_dict = super().to_info_dict(ctx) 

1523 commands = {} 

1524 

1525 for name in self.list_commands(ctx): 

1526 command = self.get_command(ctx, name) 

1527 

1528 if command is None: 

1529 continue 

1530 

1531 sub_ctx = ctx._make_sub_context(command) 

1532 

1533 with sub_ctx.scope(cleanup=False): 

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

1535 

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

1537 return info_dict 

1538 

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

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

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

1542 """ 

1543 name = name or cmd.name 

1544 if name is None: 

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

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

1547 self.commands[name] = cmd 

1548 

1549 @t.overload 

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

1551 ... 

1552 

1553 @t.overload 

1554 def command( 

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

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

1557 ... 

1558 

1559 def command( 

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

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

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

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

1564 immediately registers the created command with this group by 

1565 calling :meth:`add_command`. 

1566 

1567 To customize the command class used, set the 

1568 :attr:`command_class` attribute. 

1569 

1570 .. versionchanged:: 8.1 

1571 This decorator can be applied without parentheses. 

1572 

1573 .. versionchanged:: 8.0 

1574 Added the :attr:`command_class` attribute. 

1575 """ 

1576 from .decorators import command 

1577 

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

1579 

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

1581 assert ( 

1582 len(args) == 1 and not kwargs 

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

1584 (func,) = args 

1585 args = () 

1586 

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

1588 kwargs["cls"] = self.command_class 

1589 

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

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

1592 self.add_command(cmd) 

1593 return cmd 

1594 

1595 if func is not None: 

1596 return decorator(func) 

1597 

1598 return decorator 

1599 

1600 @t.overload 

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

1602 ... 

1603 

1604 @t.overload 

1605 def group( 

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

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

1608 ... 

1609 

1610 def group( 

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

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

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

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

1615 immediately registers the created group with this group by 

1616 calling :meth:`add_command`. 

1617 

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

1619 attribute. 

1620 

1621 .. versionchanged:: 8.1 

1622 This decorator can be applied without parentheses. 

1623 

1624 .. versionchanged:: 8.0 

1625 Added the :attr:`group_class` attribute. 

1626 """ 

1627 from .decorators import group 

1628 

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

1630 

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

1632 assert ( 

1633 len(args) == 1 and not kwargs 

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

1635 (func,) = args 

1636 args = () 

1637 

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

1639 if self.group_class is type: 

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

1641 else: 

1642 kwargs["cls"] = self.group_class 

1643 

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

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

1646 self.add_command(cmd) 

1647 return cmd 

1648 

1649 if func is not None: 

1650 return decorator(func) 

1651 

1652 return decorator 

1653 

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

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

1656 result callback is already registered this will chain them but 

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

1658 callback is invoked with the return value of the subcommand 

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

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

1661 to the main callback. 

1662 

1663 Example:: 

1664 

1665 @click.group() 

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

1667 def cli(input): 

1668 return 42 

1669 

1670 @cli.result_callback() 

1671 def process_result(result, input): 

1672 return result + input 

1673 

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

1675 callback will be removed. 

1676 

1677 .. versionchanged:: 8.0 

1678 Renamed from ``resultcallback``. 

1679 

1680 .. versionadded:: 3.0 

1681 """ 

1682 

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

1684 old_callback = self._result_callback 

1685 

1686 if old_callback is None or replace: 

1687 self._result_callback = f 

1688 return f 

1689 

1690 def function(__value, *args, **kwargs): # type: ignore 

1691 inner = old_callback(__value, *args, **kwargs) 

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

1693 

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

1695 return rv 

1696 

1697 return decorator 

1698 

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

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

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

1702 """ 

1703 return self.commands.get(cmd_name) 

1704 

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

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

1707 return sorted(self.commands) 

1708 

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

1710 rv = super().collect_usage_pieces(ctx) 

1711 rv.append(self.subcommand_metavar) 

1712 return rv 

1713 

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

1715 super().format_options(ctx, formatter) 

1716 self.format_commands(ctx, formatter) 

1717 

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

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

1720 after the options. 

1721 """ 

1722 commands = [] 

1723 for subcommand in self.list_commands(ctx): 

1724 cmd = self.get_command(ctx, subcommand) 

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

1726 if cmd is None: 

1727 continue 

1728 if cmd.hidden: 

1729 continue 

1730 

1731 commands.append((subcommand, cmd)) 

1732 

1733 # allow for 3 times the default spacing 

1734 if len(commands): 

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

1736 

1737 rows = [] 

1738 for subcommand, cmd in commands: 

1739 help = cmd.get_short_help_str(limit) 

1740 rows.append((subcommand, help)) 

1741 

1742 if rows: 

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

1744 formatter.write_dl(rows) 

1745 

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

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

1748 echo(ctx.get_help(), color=ctx.color) 

1749 ctx.exit() 

1750 

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

1752 

1753 if self.chain: 

1754 ctx._protected_args = rest 

1755 ctx.args = [] 

1756 elif rest: 

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

1758 

1759 return ctx.args 

1760 

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

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

1763 if self._result_callback is not None: 

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

1765 return value 

1766 

1767 if not ctx._protected_args: 

1768 if self.invoke_without_command: 

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

1770 # invoked with the group return value for regular 

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

1772 with ctx: 

1773 rv = super().invoke(ctx) 

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

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

1776 

1777 # Fetch args back out 

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

1779 ctx.args = [] 

1780 ctx._protected_args = [] 

1781 

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

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

1784 # name of the command to invoke. 

1785 if not self.chain: 

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

1787 # resources until the result processor has worked. 

1788 with ctx: 

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

1790 assert cmd is not None 

1791 ctx.invoked_subcommand = cmd_name 

1792 super().invoke(ctx) 

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

1794 with sub_ctx: 

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

1796 

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

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

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

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

1801 # but nothing else. 

1802 with ctx: 

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

1804 super().invoke(ctx) 

1805 

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

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

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

1809 contexts = [] 

1810 while args: 

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

1812 assert cmd is not None 

1813 sub_ctx = cmd.make_context( 

1814 cmd_name, 

1815 args, 

1816 parent=ctx, 

1817 allow_extra_args=True, 

1818 allow_interspersed_args=False, 

1819 ) 

1820 contexts.append(sub_ctx) 

1821 args, sub_ctx.args = sub_ctx.args, [] 

1822 

1823 rv = [] 

1824 for sub_ctx in contexts: 

1825 with sub_ctx: 

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

1827 return _process_result(rv) 

1828 

1829 def resolve_command( 

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

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

1832 cmd_name = make_str(args[0]) 

1833 original_cmd_name = cmd_name 

1834 

1835 # Get the command 

1836 cmd = self.get_command(ctx, cmd_name) 

1837 

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

1839 # function available, we try with that one. 

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

1841 cmd_name = ctx.token_normalize_func(cmd_name) 

1842 cmd = self.get_command(ctx, cmd_name) 

1843 

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

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

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

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

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

1849 # place. 

1850 if cmd is None and not ctx.resilient_parsing: 

1851 if _split_opt(cmd_name)[0]: 

1852 self.parse_args(ctx, ctx.args) 

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

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

1855 

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

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

1858 at the names of options, subcommands, and chained 

1859 multi-commands. 

1860 

1861 :param ctx: Invocation context for this command. 

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

1863 

1864 .. versionadded:: 8.0 

1865 """ 

1866 from click.shell_completion import CompletionItem 

1867 

1868 results = [ 

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

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

1871 ] 

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

1873 return results 

1874 

1875 

1876class _MultiCommand(Group, metaclass=_FakeSubclassCheck): 

1877 """ 

1878 .. deprecated:: 8.2 

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

1880 """ 

1881 

1882 

1883class CommandCollection(Group): 

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

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

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

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

1888 commands in many groups into this one group. 

1889 

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

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

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

1893 

1894 .. versionchanged:: 8.2 

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

1896 group, then each of its sources. 

1897 """ 

1898 

1899 def __init__( 

1900 self, 

1901 name: str | None = None, 

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

1903 **kwargs: t.Any, 

1904 ) -> None: 

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

1906 #: The list of registered groups. 

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

1908 

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

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

1911 self.sources.append(group) 

1912 

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

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

1915 

1916 if rv is not None: 

1917 return rv 

1918 

1919 for source in self.sources: 

1920 rv = source.get_command(ctx, cmd_name) 

1921 

1922 if rv is not None: 

1923 if self.chain: 

1924 _check_nested_chain(self, cmd_name, rv) 

1925 

1926 return rv 

1927 

1928 return None 

1929 

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

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

1932 

1933 for source in self.sources: 

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

1935 

1936 return sorted(rv) 

1937 

1938 

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

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

1941 error, or return an iterator over the value. 

1942 """ 

1943 if isinstance(value, str): 

1944 raise TypeError 

1945 

1946 return iter(value) 

1947 

1948 

1949class Parameter: 

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

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

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

1953 intentionally not finalized. 

1954 

1955 Some settings are supported by both options and arguments. 

1956 

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

1958 argument. This is a list of flags or argument 

1959 names. 

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

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

1962 automatically if supported. 

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

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

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

1966 without any arguments. 

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

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

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

1970 including prompts. 

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

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

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

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

1975 parameters are collected. 

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

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

1978 to the command callback and stored on the context, 

1979 otherwise it's skipped. 

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

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

1982 order of processing. 

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

1984 that should be checked. 

1985 :param shell_complete: A function that returns custom shell 

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

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

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

1989 strings. 

1990 

1991 .. versionchanged:: 8.0 

1992 ``process_value`` validates required parameters and bounded 

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

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

1995 ``full_process_value`` is removed. 

1996 

1997 .. versionchanged:: 8.0 

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

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

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

2001 new requirements. 

2002 

2003 .. versionchanged:: 8.0 

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

2005 tuples. 

2006 

2007 .. versionchanged:: 8.0 

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

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

2010 default to ``()``. 

2011 

2012 .. versionchanged:: 7.1 

2013 Empty environment variables are ignored rather than taking the 

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

2015 variables if they can't unset them. 

2016 

2017 .. versionchanged:: 2.0 

2018 Changed signature for parameter callback to also be passed the 

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

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

2021 """ 

2022 

2023 param_type_name = "parameter" 

2024 

2025 def __init__( 

2026 self, 

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

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

2029 required: bool = False, 

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

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

2032 nargs: int | None = None, 

2033 multiple: bool = False, 

2034 metavar: str | None = None, 

2035 expose_value: bool = True, 

2036 is_eager: bool = False, 

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

2038 shell_complete: t.Callable[ 

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

2040 ] 

2041 | None = None, 

2042 ) -> None: 

2043 self.name: str | None 

2044 self.opts: list[str] 

2045 self.secondary_opts: list[str] 

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

2047 param_decls or (), expose_value 

2048 ) 

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

2050 

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

2052 # information available. 

2053 if nargs is None: 

2054 if self.type.is_composite: 

2055 nargs = self.type.arity 

2056 else: 

2057 nargs = 1 

2058 

2059 self.required = required 

2060 self.callback = callback 

2061 self.nargs = nargs 

2062 self.multiple = multiple 

2063 self.expose_value = expose_value 

2064 self.default = default 

2065 self.is_eager = is_eager 

2066 self.metavar = metavar 

2067 self.envvar = envvar 

2068 self._custom_shell_complete = shell_complete 

2069 

2070 if __debug__: 

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

2072 raise ValueError( 

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

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

2075 ) 

2076 

2077 # Skip no default or callable default. 

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

2079 

2080 if check_default is not None: 

2081 if multiple: 

2082 try: 

2083 # Only check the first value against nargs. 

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

2085 except TypeError: 

2086 raise ValueError( 

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

2088 ) from None 

2089 

2090 # Can be None for multiple with empty default. 

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

2092 try: 

2093 _check_iter(check_default) 

2094 except TypeError: 

2095 if multiple: 

2096 message = ( 

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

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

2099 ) 

2100 else: 

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

2102 

2103 raise ValueError(message) from None 

2104 

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

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

2107 raise ValueError( 

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

2109 ) 

2110 

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

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

2113 user-facing documentation. 

2114 

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

2116 CLI structure. 

2117 

2118 .. versionadded:: 8.0 

2119 """ 

2120 return { 

2121 "name": self.name, 

2122 "param_type_name": self.param_type_name, 

2123 "opts": self.opts, 

2124 "secondary_opts": self.secondary_opts, 

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

2126 "required": self.required, 

2127 "nargs": self.nargs, 

2128 "multiple": self.multiple, 

2129 "default": self.default, 

2130 "envvar": self.envvar, 

2131 } 

2132 

2133 def __repr__(self) -> str: 

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

2135 

2136 def _parse_decls( 

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

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

2139 raise NotImplementedError() 

2140 

2141 @property 

2142 def human_readable_name(self) -> str: 

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

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

2145 """ 

2146 return self.name # type: ignore 

2147 

2148 def make_metavar(self) -> str: 

2149 if self.metavar is not None: 

2150 return self.metavar 

2151 

2152 metavar = self.type.get_metavar(self) 

2153 

2154 if metavar is None: 

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

2156 

2157 if self.nargs != 1: 

2158 metavar += "..." 

2159 

2160 return metavar 

2161 

2162 @t.overload 

2163 def get_default(self, ctx: Context, call: t.Literal[True] = True) -> t.Any | None: 

2164 ... 

2165 

2166 @t.overload 

2167 def get_default( 

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

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

2170 ... 

2171 

2172 def get_default( 

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

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

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

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

2177 

2178 :param ctx: Current context. 

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

2180 return the callable instead. 

2181 

2182 .. versionchanged:: 8.0.2 

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

2184 

2185 .. versionchanged:: 8.0.1 

2186 Type casting can fail in resilient parsing mode. Invalid 

2187 defaults will not prevent showing help text. 

2188 

2189 .. versionchanged:: 8.0 

2190 Looks at ``ctx.default_map`` first. 

2191 

2192 .. versionchanged:: 8.0 

2193 Added the ``call`` parameter. 

2194 """ 

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

2196 

2197 if value is None: 

2198 value = self.default 

2199 

2200 if call and callable(value): 

2201 value = value() 

2202 

2203 return value 

2204 

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

2206 raise NotImplementedError() 

2207 

2208 def consume_value( 

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

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

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

2212 source = ParameterSource.COMMANDLINE 

2213 

2214 if value is None: 

2215 value = self.value_from_envvar(ctx) 

2216 source = ParameterSource.ENVIRONMENT 

2217 

2218 if value is None: 

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

2220 source = ParameterSource.DEFAULT_MAP 

2221 

2222 if value is None: 

2223 value = self.get_default(ctx) 

2224 source = ParameterSource.DEFAULT 

2225 

2226 return value, source 

2227 

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

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

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

2231 """ 

2232 if value is None: 

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

2234 

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

2236 try: 

2237 return _check_iter(value) 

2238 except TypeError: 

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

2240 # the parser should construct an iterable when parsing 

2241 # the command line. 

2242 raise BadParameter( 

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

2244 ) from None 

2245 

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

2247 

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

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

2250 

2251 elif self.nargs == -1: 

2252 

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

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

2255 

2256 else: # nargs > 1 

2257 

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

2259 value = tuple(check_iter(value)) 

2260 

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

2262 raise BadParameter( 

2263 ngettext( 

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

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

2266 len(value), 

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

2268 ctx=ctx, 

2269 param=self, 

2270 ) 

2271 

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

2273 

2274 if self.multiple: 

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

2276 

2277 return convert(value) 

2278 

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

2280 if value is None: 

2281 return True 

2282 

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

2284 return True 

2285 

2286 return False 

2287 

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

2289 value = self.type_cast_value(ctx, value) 

2290 

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

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

2293 

2294 if self.callback is not None: 

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

2296 

2297 return value 

2298 

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

2300 if self.envvar is None: 

2301 return None 

2302 

2303 if isinstance(self.envvar, str): 

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

2305 

2306 if rv: 

2307 return rv 

2308 else: 

2309 for envvar in self.envvar: 

2310 rv = os.environ.get(envvar) 

2311 

2312 if rv: 

2313 return rv 

2314 

2315 return None 

2316 

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

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

2319 

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

2321 rv = self.type.split_envvar_value(rv) 

2322 

2323 return rv 

2324 

2325 def handle_parse_result( 

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

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

2328 with augment_usage_errors(ctx, param=self): 

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

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

2331 

2332 try: 

2333 value = self.process_value(ctx, value) 

2334 except Exception: 

2335 if not ctx.resilient_parsing: 

2336 raise 

2337 

2338 value = None 

2339 

2340 if self.expose_value: 

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

2342 

2343 return value, args 

2344 

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

2346 pass 

2347 

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

2349 return [] 

2350 

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

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

2353 indicate which param caused the error. 

2354 """ 

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

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

2357 

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

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

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

2361 Otherwise, the :attr:`type` 

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

2363 

2364 :param ctx: Invocation context for this command. 

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

2366 

2367 .. versionadded:: 8.0 

2368 """ 

2369 if self._custom_shell_complete is not None: 

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

2371 

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

2373 from click.shell_completion import CompletionItem 

2374 

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

2376 

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

2378 

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

2380 

2381 

2382class Option(Parameter): 

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

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

2385 

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

2387 

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

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

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

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

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

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

2394 its value is ``False``. 

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

2396 shown on the help page. Normally, environment variables are not 

2397 shown. 

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

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

2400 will be the option name capitalized. 

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

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

2403 ``True`` to customize the message. 

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

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

2406 without a value. 

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

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

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

2410 auto detection. 

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

2412 enabled. This is set to a boolean automatically if 

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

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

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

2416 in how it works but supports arbitrary number of 

2417 arguments. 

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

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

2420 parameter will be pulled from an environment 

2421 variable in case a prefix is defined on the 

2422 context. 

2423 :param help: the help string. 

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

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

2426 

2427 .. versionchanged:: 8.1.0 

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

2429 ``@option`` decorator. 

2430 

2431 .. versionchanged:: 8.1.0 

2432 The ``show_default`` parameter overrides 

2433 ``Context.show_default``. 

2434 

2435 .. versionchanged:: 8.1.0 

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

2437 default value is ``False``. 

2438 

2439 .. versionchanged:: 8.0.1 

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

2441 """ 

2442 

2443 param_type_name = "option" 

2444 

2445 def __init__( 

2446 self, 

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

2448 show_default: bool | str | None = None, 

2449 prompt: bool | str = False, 

2450 confirmation_prompt: bool | str = False, 

2451 prompt_required: bool = True, 

2452 hide_input: bool = False, 

2453 is_flag: bool | None = None, 

2454 flag_value: t.Any | None = None, 

2455 multiple: bool = False, 

2456 count: bool = False, 

2457 allow_from_autoenv: bool = True, 

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

2459 help: str | None = None, 

2460 hidden: bool = False, 

2461 show_choices: bool = True, 

2462 show_envvar: bool = False, 

2463 **attrs: t.Any, 

2464 ) -> None: 

2465 if help: 

2466 help = inspect.cleandoc(help) 

2467 

2468 default_is_missing = "default" not in attrs 

2469 super().__init__(param_decls, type=type, multiple=multiple, **attrs) 

2470 

2471 if prompt is True: 

2472 if self.name is None: 

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

2474 

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

2476 elif prompt is False: 

2477 prompt_text = None 

2478 else: 

2479 prompt_text = prompt 

2480 

2481 self.prompt = prompt_text 

2482 self.confirmation_prompt = confirmation_prompt 

2483 self.prompt_required = prompt_required 

2484 self.hide_input = hide_input 

2485 self.hidden = hidden 

2486 

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

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

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

2490 

2491 if is_flag is None: 

2492 if flag_value is not None: 

2493 # Implicitly a flag because flag_value was set. 

2494 is_flag = True 

2495 elif self._flag_needs_value: 

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

2497 is_flag = False 

2498 else: 

2499 # Implicitly a flag because flag options were given. 

2500 is_flag = bool(self.secondary_opts) 

2501 elif is_flag is False and not self._flag_needs_value: 

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

2503 # flag if flag_value is set. 

2504 self._flag_needs_value = flag_value is not None 

2505 

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

2507 

2508 if is_flag and default_is_missing and not self.required: 

2509 if multiple: 

2510 self.default = () 

2511 else: 

2512 self.default = False 

2513 

2514 if flag_value is None: 

2515 flag_value = not self.default 

2516 

2517 self.type: types.ParamType 

2518 if is_flag and type is None: 

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

2520 # default. 

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

2522 

2523 self.is_flag: bool = is_flag 

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

2525 self.flag_value: t.Any = flag_value 

2526 

2527 # Counting 

2528 self.count = count 

2529 if count: 

2530 if type is None: 

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

2532 if default_is_missing: 

2533 self.default = 0 

2534 

2535 self.allow_from_autoenv = allow_from_autoenv 

2536 self.help = help 

2537 self.show_default = show_default 

2538 self.show_choices = show_choices 

2539 self.show_envvar = show_envvar 

2540 

2541 if __debug__: 

2542 if self.nargs == -1: 

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

2544 

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

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

2547 

2548 if not self.is_bool_flag and self.secondary_opts: 

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

2550 

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

2552 raise TypeError( 

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

2554 ) 

2555 

2556 if self.count: 

2557 if self.multiple: 

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

2559 

2560 if self.is_flag: 

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

2562 

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

2564 info_dict = super().to_info_dict() 

2565 info_dict.update( 

2566 help=self.help, 

2567 prompt=self.prompt, 

2568 is_flag=self.is_flag, 

2569 flag_value=self.flag_value, 

2570 count=self.count, 

2571 hidden=self.hidden, 

2572 ) 

2573 return info_dict 

2574 

2575 def _parse_decls( 

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

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

2578 opts = [] 

2579 secondary_opts = [] 

2580 name = None 

2581 possible_names = [] 

2582 

2583 for decl in decls: 

2584 if decl.isidentifier(): 

2585 if name is not None: 

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

2587 name = decl 

2588 else: 

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

2590 if split_char in decl: 

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

2592 first = first.rstrip() 

2593 if first: 

2594 possible_names.append(_split_opt(first)) 

2595 opts.append(first) 

2596 second = second.lstrip() 

2597 if second: 

2598 secondary_opts.append(second.lstrip()) 

2599 if first == second: 

2600 raise ValueError( 

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

2602 " same flag for true/false." 

2603 ) 

2604 else: 

2605 possible_names.append(_split_opt(decl)) 

2606 opts.append(decl) 

2607 

2608 if name is None and possible_names: 

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

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

2611 if not name.isidentifier(): 

2612 name = None 

2613 

2614 if name is None: 

2615 if not expose_value: 

2616 return None, opts, secondary_opts 

2617 raise TypeError("Could not determine name for option") 

2618 

2619 if not opts and not secondary_opts: 

2620 raise TypeError( 

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

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

2623 f" you mean to pass '--{name}'?" 

2624 ) 

2625 

2626 return name, opts, secondary_opts 

2627 

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

2629 if self.multiple: 

2630 action = "append" 

2631 elif self.count: 

2632 action = "count" 

2633 else: 

2634 action = "store" 

2635 

2636 if self.is_flag: 

2637 action = f"{action}_const" 

2638 

2639 if self.is_bool_flag and self.secondary_opts: 

2640 parser.add_option( 

2641 obj=self, opts=self.opts, dest=self.name, action=action, const=True 

2642 ) 

2643 parser.add_option( 

2644 obj=self, 

2645 opts=self.secondary_opts, 

2646 dest=self.name, 

2647 action=action, 

2648 const=False, 

2649 ) 

2650 else: 

2651 parser.add_option( 

2652 obj=self, 

2653 opts=self.opts, 

2654 dest=self.name, 

2655 action=action, 

2656 const=self.flag_value, 

2657 ) 

2658 else: 

2659 parser.add_option( 

2660 obj=self, 

2661 opts=self.opts, 

2662 dest=self.name, 

2663 action=action, 

2664 nargs=self.nargs, 

2665 ) 

2666 

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

2668 if self.hidden: 

2669 return None 

2670 

2671 any_prefix_is_slash = False 

2672 

2673 def _write_opts(opts: cabc.Sequence[str]) -> str: 

2674 nonlocal any_prefix_is_slash 

2675 

2676 rv, any_slashes = join_options(opts) 

2677 

2678 if any_slashes: 

2679 any_prefix_is_slash = True 

2680 

2681 if not self.is_flag and not self.count: 

2682 rv += f" {self.make_metavar()}" 

2683 

2684 return rv 

2685 

2686 rv = [_write_opts(self.opts)] 

2687 

2688 if self.secondary_opts: 

2689 rv.append(_write_opts(self.secondary_opts)) 

2690 

2691 help = self.help or "" 

2692 extra = [] 

2693 

2694 if self.show_envvar: 

2695 envvar = self.envvar 

2696 

2697 if envvar is None: 

2698 if ( 

2699 self.allow_from_autoenv 

2700 and ctx.auto_envvar_prefix is not None 

2701 and self.name is not None 

2702 ): 

2703 envvar = f"{ctx.auto_envvar_prefix}_{self.name.upper()}" 

2704 

2705 if envvar is not None: 

2706 var_str = ( 

2707 envvar 

2708 if isinstance(envvar, str) 

2709 else ", ".join(str(d) for d in envvar) 

2710 ) 

2711 extra.append(_("env var: {var}").format(var=var_str)) 

2712 

2713 # Temporarily enable resilient parsing to avoid type casting 

2714 # failing for the default. Might be possible to extend this to 

2715 # help formatting in general. 

2716 resilient = ctx.resilient_parsing 

2717 ctx.resilient_parsing = True 

2718 

2719 try: 

2720 default_value = self.get_default(ctx, call=False) 

2721 finally: 

2722 ctx.resilient_parsing = resilient 

2723 

2724 show_default = False 

2725 show_default_is_str = False 

2726 

2727 if self.show_default is not None: 

2728 if isinstance(self.show_default, str): 

2729 show_default_is_str = show_default = True 

2730 else: 

2731 show_default = self.show_default 

2732 elif ctx.show_default is not None: 

2733 show_default = ctx.show_default 

2734 

2735 if show_default_is_str or (show_default and (default_value is not None)): 

2736 if show_default_is_str: 

2737 default_string = f"({self.show_default})" 

2738 elif isinstance(default_value, (list, tuple)): 

2739 default_string = ", ".join(str(d) for d in default_value) 

2740 elif inspect.isfunction(default_value): 

2741 default_string = _("(dynamic)") 

2742 elif self.is_bool_flag and self.secondary_opts: 

2743 # For boolean flags that have distinct True/False opts, 

2744 # use the opt without prefix instead of the value. 

2745 default_string = _split_opt( 

2746 (self.opts if self.default else self.secondary_opts)[0] 

2747 )[1] 

2748 elif self.is_bool_flag and not self.secondary_opts and not default_value: 

2749 default_string = "" 

2750 else: 

2751 default_string = str(default_value) 

2752 

2753 if default_string: 

2754 extra.append(_("default: {default}").format(default=default_string)) 

2755 

2756 if ( 

2757 isinstance(self.type, types._NumberRangeBase) 

2758 # skip count with default range type 

2759 and not (self.count and self.type.min == 0 and self.type.max is None) 

2760 ): 

2761 range_str = self.type._describe_range() 

2762 

2763 if range_str: 

2764 extra.append(range_str) 

2765 

2766 if self.required: 

2767 extra.append(_("required")) 

2768 

2769 if extra: 

2770 extra_str = "; ".join(extra) 

2771 help = f"{help} [{extra_str}]" if help else f"[{extra_str}]" 

2772 

2773 return ("; " if any_prefix_is_slash else " / ").join(rv), help 

2774 

2775 @t.overload 

2776 def get_default(self, ctx: Context, call: t.Literal[True] = True) -> t.Any | None: 

2777 ... 

2778 

2779 @t.overload 

2780 def get_default( 

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

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

2783 ... 

2784 

2785 def get_default( 

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

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

2788 # If we're a non boolean flag our default is more complex because 

2789 # we need to look at all flags in the same group to figure out 

2790 # if we're the default one in which case we return the flag 

2791 # value as default. 

2792 if self.is_flag and not self.is_bool_flag: 

2793 for param in ctx.command.params: 

2794 if param.name == self.name and param.default: 

2795 return t.cast(Option, param).flag_value 

2796 

2797 return None 

2798 

2799 return super().get_default(ctx, call=call) 

2800 

2801 def prompt_for_value(self, ctx: Context) -> t.Any: 

2802 """This is an alternative flow that can be activated in the full 

2803 value processing if a value does not exist. It will prompt the 

2804 user until a valid value exists and then returns the processed 

2805 value as result. 

2806 """ 

2807 assert self.prompt is not None 

2808 

2809 # Calculate the default before prompting anything to be stable. 

2810 default = self.get_default(ctx) 

2811 

2812 # If this is a prompt for a flag we need to handle this 

2813 # differently. 

2814 if self.is_bool_flag: 

2815 return confirm(self.prompt, default) 

2816 

2817 return prompt( 

2818 self.prompt, 

2819 default=default, 

2820 type=self.type, 

2821 hide_input=self.hide_input, 

2822 show_choices=self.show_choices, 

2823 confirmation_prompt=self.confirmation_prompt, 

2824 value_proc=lambda x: self.process_value(ctx, x), 

2825 ) 

2826 

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

2828 rv = super().resolve_envvar_value(ctx) 

2829 

2830 if rv is not None: 

2831 return rv 

2832 

2833 if ( 

2834 self.allow_from_autoenv 

2835 and ctx.auto_envvar_prefix is not None 

2836 and self.name is not None 

2837 ): 

2838 envvar = f"{ctx.auto_envvar_prefix}_{self.name.upper()}" 

2839 rv = os.environ.get(envvar) 

2840 

2841 if rv: 

2842 return rv 

2843 

2844 return None 

2845 

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

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

2848 

2849 if rv is None: 

2850 return None 

2851 

2852 value_depth = (self.nargs != 1) + bool(self.multiple) 

2853 

2854 if value_depth > 0: 

2855 rv = self.type.split_envvar_value(rv) 

2856 

2857 if self.multiple and self.nargs != 1: 

2858 rv = batch(rv, self.nargs) 

2859 

2860 return rv 

2861 

2862 def consume_value( 

2863 self, ctx: Context, opts: cabc.Mapping[str, Parameter] 

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

2865 value, source = super().consume_value(ctx, opts) 

2866 

2867 # The parser will emit a sentinel value if the option can be 

2868 # given as a flag without a value. This is different from None 

2869 # to distinguish from the flag not being given at all. 

2870 if value is _flag_needs_value: 

2871 if self.prompt is not None and not ctx.resilient_parsing: 

2872 value = self.prompt_for_value(ctx) 

2873 source = ParameterSource.PROMPT 

2874 else: 

2875 value = self.flag_value 

2876 source = ParameterSource.COMMANDLINE 

2877 

2878 elif ( 

2879 self.multiple 

2880 and value is not None 

2881 and any(v is _flag_needs_value for v in value) 

2882 ): 

2883 value = [self.flag_value if v is _flag_needs_value else v for v in value] 

2884 source = ParameterSource.COMMANDLINE 

2885 

2886 # The value wasn't set, or used the param's default, prompt if 

2887 # prompting is enabled. 

2888 elif ( 

2889 source in {None, ParameterSource.DEFAULT} 

2890 and self.prompt is not None 

2891 and (self.required or self.prompt_required) 

2892 and not ctx.resilient_parsing 

2893 ): 

2894 value = self.prompt_for_value(ctx) 

2895 source = ParameterSource.PROMPT 

2896 

2897 return value, source 

2898 

2899 

2900class Argument(Parameter): 

2901 """Arguments are positional parameters to a command. They generally 

2902 provide fewer features than options but can have infinite ``nargs`` 

2903 and are required by default. 

2904 

2905 All parameters are passed onwards to the constructor of :class:`Parameter`. 

2906 """ 

2907 

2908 param_type_name = "argument" 

2909 

2910 def __init__( 

2911 self, 

2912 param_decls: cabc.Sequence[str], 

2913 required: bool | None = None, 

2914 **attrs: t.Any, 

2915 ) -> None: 

2916 if required is None: 

2917 if attrs.get("default") is not None: 

2918 required = False 

2919 else: 

2920 required = attrs.get("nargs", 1) > 0 

2921 

2922 if "multiple" in attrs: 

2923 raise TypeError("__init__() got an unexpected keyword argument 'multiple'.") 

2924 

2925 super().__init__(param_decls, required=required, **attrs) 

2926 

2927 if __debug__: 

2928 if self.default is not None and self.nargs == -1: 

2929 raise TypeError("'default' is not supported for nargs=-1.") 

2930 

2931 @property 

2932 def human_readable_name(self) -> str: 

2933 if self.metavar is not None: 

2934 return self.metavar 

2935 return self.name.upper() # type: ignore 

2936 

2937 def make_metavar(self) -> str: 

2938 if self.metavar is not None: 

2939 return self.metavar 

2940 var = self.type.get_metavar(self) 

2941 if not var: 

2942 var = self.name.upper() # type: ignore 

2943 if not self.required: 

2944 var = f"[{var}]" 

2945 if self.nargs != 1: 

2946 var += "..." 

2947 return var 

2948 

2949 def _parse_decls( 

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

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

2952 if not decls: 

2953 if not expose_value: 

2954 return None, [], [] 

2955 raise TypeError("Could not determine name for argument") 

2956 if len(decls) == 1: 

2957 name = arg = decls[0] 

2958 name = name.replace("-", "_").lower() 

2959 else: 

2960 raise TypeError( 

2961 "Arguments take exactly one parameter declaration, got" 

2962 f" {len(decls)}." 

2963 ) 

2964 return name, [arg], [] 

2965 

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

2967 return [self.make_metavar()] 

2968 

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

2970 return f"'{self.make_metavar()}'" 

2971 

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

2973 parser.add_argument(dest=self.name, nargs=self.nargs, obj=self) 

2974 

2975 

2976def __getattr__(name: str) -> object: 

2977 import warnings 

2978 

2979 if name == "BaseCommand": 

2980 warnings.warn( 

2981 "'BaseCommand' is deprecated and will be removed in Click 9.0. Use" 

2982 " 'Command' instead.", 

2983 DeprecationWarning, 

2984 stacklevel=2, 

2985 ) 

2986 return _BaseCommand 

2987 

2988 if name == "MultiCommand": 

2989 warnings.warn( 

2990 "'MultiCommand' is deprecated and will be removed in Click 9.0. Use" 

2991 " 'Group' instead.", 

2992 DeprecationWarning, 

2993 stacklevel=2, 

2994 ) 

2995 return _MultiCommand 

2996 

2997 raise AttributeError(name)