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

1151 statements  

« prev     ^ index     » next       coverage.py v7.2.7, created at 2023-06-07 07:07 +0000

1import enum 

2import errno 

3import inspect 

4import os 

5import sys 

6import typing as t 

7from collections import abc 

8from contextlib import contextmanager 

9from contextlib import ExitStack 

10from functools import partial 

11from functools import update_wrapper 

12from gettext import gettext as _ 

13from gettext import ngettext 

14from itertools import repeat 

15 

16from . import types 

17from .exceptions import Abort 

18from .exceptions import BadParameter 

19from .exceptions import ClickException 

20from .exceptions import Exit 

21from .exceptions import MissingParameter 

22from .exceptions import UsageError 

23from .formatting import HelpFormatter 

24from .formatting import join_options 

25from .globals import pop_context 

26from .globals import push_context 

27from .parser import _flag_needs_value 

28from .parser import OptionParser 

29from .parser import split_opt 

30from .termui import confirm 

31from .termui import prompt 

32from .termui import style 

33from .utils import _detect_program_name 

34from .utils import _expand_args 

35from .utils import echo 

36from .utils import make_default_short_help 

37from .utils import make_str 

38from .utils import PacifyFlushWrapper 

39 

40if t.TYPE_CHECKING: 

41 import typing_extensions as te 

42 from .shell_completion import CompletionItem 

43 

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

45V = t.TypeVar("V") 

46 

47 

48def _complete_visible_commands( 

49 ctx: "Context", incomplete: str 

50) -> t.Iterator[t.Tuple[str, "Command"]]: 

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

52 incomplete value and aren't hidden. 

53 

54 :param ctx: Invocation context for the group. 

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

56 """ 

57 multi = t.cast(MultiCommand, ctx.command) 

58 

59 for name in multi.list_commands(ctx): 

60 if name.startswith(incomplete): 

61 command = multi.get_command(ctx, name) 

62 

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

64 yield name, command 

65 

66 

67def _check_multicommand( 

68 base_command: "MultiCommand", cmd_name: str, cmd: "Command", register: bool = False 

69) -> None: 

70 if not base_command.chain or not isinstance(cmd, MultiCommand): 

71 return 

72 if register: 

73 hint = ( 

74 "It is not possible to add multi commands as children to" 

75 " another multi command that is in chain mode." 

76 ) 

77 else: 

78 hint = ( 

79 "Found a multi command as subcommand to a multi command" 

80 " that is in chain mode. This is not supported." 

81 ) 

82 raise RuntimeError( 

83 f"{hint}. Command {base_command.name!r} is set to chain and" 

84 f" {cmd_name!r} was added as a subcommand but it in itself is a" 

85 f" multi command. ({cmd_name!r} is a {type(cmd).__name__}" 

86 f" within a chained {type(base_command).__name__} named" 

87 f" {base_command.name!r})." 

88 ) 

89 

90 

91def batch(iterable: t.Iterable[V], batch_size: int) -> t.List[t.Tuple[V, ...]]: 

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

93 

94 

95@contextmanager 

96def augment_usage_errors( 

97 ctx: "Context", param: t.Optional["Parameter"] = None 

98) -> t.Iterator[None]: 

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

100 try: 

101 yield 

102 except BadParameter as e: 

103 if e.ctx is None: 

104 e.ctx = ctx 

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

106 e.param = param 

107 raise 

108 except UsageError as e: 

109 if e.ctx is None: 

110 e.ctx = ctx 

111 raise 

112 

113 

114def iter_params_for_processing( 

115 invocation_order: t.Sequence["Parameter"], 

116 declaration_order: t.Sequence["Parameter"], 

117) -> t.List["Parameter"]: 

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

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

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

121 """ 

122 

123 def sort_key(item: "Parameter") -> t.Tuple[bool, float]: 

124 try: 

125 idx: float = invocation_order.index(item) 

126 except ValueError: 

127 idx = float("inf") 

128 

129 return not item.is_eager, idx 

130 

131 return sorted(declaration_order, key=sort_key) 

132 

133 

134class ParameterSource(enum.Enum): 

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

136 parameter's value. 

137 

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

139 source for a parameter by name. 

140 

141 .. versionchanged:: 8.0 

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

143 

144 .. versionchanged:: 8.0 

145 Added the ``PROMPT`` value. 

146 """ 

147 

148 COMMANDLINE = enum.auto() 

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

150 ENVIRONMENT = enum.auto() 

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

152 DEFAULT = enum.auto() 

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

154 DEFAULT_MAP = enum.auto() 

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

156 PROMPT = enum.auto() 

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

158 

159 

160class Context: 

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

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

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

164 

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

166 control special execution features such as reading data from 

167 environment variables. 

168 

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

170 :meth:`close` on teardown. 

171 

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

173 :param parent: the parent context. 

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

175 is the most descriptive name for the script or 

176 command. For the toplevel script it is usually 

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

178 the name of the script. 

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

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

181 variables. If this is `None` then reading 

182 from environment variables is disabled. This 

183 does not affect manually set environment 

184 variables which are always read. 

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

186 for parameters. 

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

188 inherit from parent context. If no context 

189 defines the terminal width then auto 

190 detection will be applied. 

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

192 Click (this currently only affects help 

193 pages). This defaults to 80 characters if 

194 not overridden. In other words: even if the 

195 terminal is larger than that, Click will not 

196 format things wider than 80 characters by 

197 default. In addition to that, formatters might 

198 add some safety mapping on the right. 

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

200 parse without any interactivity or callback 

201 invocation. Default values will also be 

202 ignored. This is useful for implementing 

203 things such as completion support. 

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

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

206 kept on the context. The default is to inherit 

207 from the command. 

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

209 and arguments cannot be mixed. The 

210 default is to inherit from the command. 

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

212 not know and keeps them for later 

213 processing. 

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

215 the default help parameter is named. The 

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

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

218 normalize tokens (options, choices, 

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

220 implement case insensitive behavior. 

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

222 default is autodetection. This is only needed if ANSI 

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

224 default not the case. This for instance would affect 

225 help output. 

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

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

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

229 specific command. 

230 

231 .. versionchanged:: 8.1 

232 The ``show_default`` parameter is overridden by 

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

234 

235 .. versionchanged:: 8.0 

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

237 parent context. 

238 

239 .. versionchanged:: 7.1 

240 Added the ``show_default`` parameter. 

241 

242 .. versionchanged:: 4.0 

243 Added the ``color``, ``ignore_unknown_options``, and 

244 ``max_content_width`` parameters. 

245 

246 .. versionchanged:: 3.0 

247 Added the ``allow_extra_args`` and ``allow_interspersed_args`` 

248 parameters. 

249 

250 .. versionchanged:: 2.0 

251 Added the ``resilient_parsing``, ``help_option_names``, and 

252 ``token_normalize_func`` parameters. 

253 """ 

254 

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

256 #: 

257 #: .. versionadded:: 8.0 

258 formatter_class: t.Type["HelpFormatter"] = HelpFormatter 

259 

260 def __init__( 

261 self, 

262 command: "Command", 

263 parent: t.Optional["Context"] = None, 

264 info_name: t.Optional[str] = None, 

265 obj: t.Optional[t.Any] = None, 

266 auto_envvar_prefix: t.Optional[str] = None, 

267 default_map: t.Optional[t.MutableMapping[str, t.Any]] = None, 

268 terminal_width: t.Optional[int] = None, 

269 max_content_width: t.Optional[int] = None, 

270 resilient_parsing: bool = False, 

271 allow_extra_args: t.Optional[bool] = None, 

272 allow_interspersed_args: t.Optional[bool] = None, 

273 ignore_unknown_options: t.Optional[bool] = None, 

274 help_option_names: t.Optional[t.List[str]] = None, 

275 token_normalize_func: t.Optional[t.Callable[[str], str]] = None, 

276 color: t.Optional[bool] = None, 

277 show_default: t.Optional[bool] = None, 

278 ) -> None: 

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

280 self.parent = parent 

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

282 self.command = command 

283 #: the descriptive information name 

284 self.info_name = info_name 

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

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

287 self.params: t.Dict[str, t.Any] = {} 

288 #: the leftover arguments. 

289 self.args: t.List[str] = [] 

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

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

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

293 #: to implement nested parsing. 

294 self.protected_args: t.List[str] = [] 

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

296 self._opt_prefixes: t.Set[str] = set(parent._opt_prefixes) if parent else set() 

297 

298 if obj is None and parent is not None: 

299 obj = parent.obj 

300 

301 #: the user object stored. 

302 self.obj: t.Any = obj 

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

304 

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

306 if ( 

307 default_map is None 

308 and info_name is not None 

309 and parent is not None 

310 and parent.default_map is not None 

311 ): 

312 default_map = parent.default_map.get(info_name) 

313 

314 self.default_map: t.Optional[t.MutableMapping[str, t.Any]] = default_map 

315 

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

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

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

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

320 #: the name of the subcommand to execute. 

321 #: 

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

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

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

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

326 self.invoked_subcommand: t.Optional[str] = None 

327 

328 if terminal_width is None and parent is not None: 

329 terminal_width = parent.terminal_width 

330 

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

332 self.terminal_width: t.Optional[int] = terminal_width 

333 

334 if max_content_width is None and parent is not None: 

335 max_content_width = parent.max_content_width 

336 

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

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

339 self.max_content_width: t.Optional[int] = max_content_width 

340 

341 if allow_extra_args is None: 

342 allow_extra_args = command.allow_extra_args 

343 

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

345 #: fail on parsing. 

346 #: 

347 #: .. versionadded:: 3.0 

348 self.allow_extra_args = allow_extra_args 

349 

350 if allow_interspersed_args is None: 

351 allow_interspersed_args = command.allow_interspersed_args 

352 

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

354 #: options or not. 

355 #: 

356 #: .. versionadded:: 3.0 

357 self.allow_interspersed_args: bool = allow_interspersed_args 

358 

359 if ignore_unknown_options is None: 

360 ignore_unknown_options = command.ignore_unknown_options 

361 

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

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

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

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

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

367 #: forward all arguments. 

368 #: 

369 #: .. versionadded:: 4.0 

370 self.ignore_unknown_options: bool = ignore_unknown_options 

371 

372 if help_option_names is None: 

373 if parent is not None: 

374 help_option_names = parent.help_option_names 

375 else: 

376 help_option_names = ["--help"] 

377 

378 #: The names for the help options. 

379 self.help_option_names: t.List[str] = help_option_names 

380 

381 if token_normalize_func is None and parent is not None: 

382 token_normalize_func = parent.token_normalize_func 

383 

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

385 #: options, choices, commands etc. 

386 self.token_normalize_func: t.Optional[ 

387 t.Callable[[str], str] 

388 ] = token_normalize_func 

389 

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

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

392 #: will be ignored. Useful for completion. 

393 self.resilient_parsing: bool = resilient_parsing 

394 

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

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

397 # prefix automatically. 

398 if auto_envvar_prefix is None: 

399 if ( 

400 parent is not None 

401 and parent.auto_envvar_prefix is not None 

402 and self.info_name is not None 

403 ): 

404 auto_envvar_prefix = ( 

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

406 ) 

407 else: 

408 auto_envvar_prefix = auto_envvar_prefix.upper() 

409 

410 if auto_envvar_prefix is not None: 

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

412 

413 self.auto_envvar_prefix: t.Optional[str] = auto_envvar_prefix 

414 

415 if color is None and parent is not None: 

416 color = parent.color 

417 

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

419 self.color: t.Optional[bool] = color 

420 

421 if show_default is None and parent is not None: 

422 show_default = parent.show_default 

423 

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

425 self.show_default: t.Optional[bool] = show_default 

426 

427 self._close_callbacks: t.List[t.Callable[[], t.Any]] = [] 

428 self._depth = 0 

429 self._parameter_source: t.Dict[str, ParameterSource] = {} 

430 self._exit_stack = ExitStack() 

431 

432 def to_info_dict(self) -> t.Dict[str, t.Any]: 

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

434 user-facing documentation. This traverses the entire CLI 

435 structure. 

436 

437 .. code-block:: python 

438 

439 with Context(cli) as ctx: 

440 info = ctx.to_info_dict() 

441 

442 .. versionadded:: 8.0 

443 """ 

444 return { 

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

446 "info_name": self.info_name, 

447 "allow_extra_args": self.allow_extra_args, 

448 "allow_interspersed_args": self.allow_interspersed_args, 

449 "ignore_unknown_options": self.ignore_unknown_options, 

450 "auto_envvar_prefix": self.auto_envvar_prefix, 

451 } 

452 

453 def __enter__(self) -> "Context": 

454 self._depth += 1 

455 push_context(self) 

456 return self 

457 

458 def __exit__(self, *_: t.Any) -> None: 

459 self._depth -= 1 

460 if self._depth == 0: 

461 self.close() 

462 pop_context() 

463 

464 @contextmanager 

465 def scope(self, cleanup: bool = True) -> t.Iterator["Context"]: 

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

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

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

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

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

471 

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

473 used as a context manager. 

474 

475 Example usage:: 

476 

477 with ctx.scope(): 

478 assert get_current_context() is ctx 

479 

480 This is equivalent:: 

481 

482 with ctx: 

483 assert get_current_context() is ctx 

484 

485 .. versionadded:: 5.0 

486 

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

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

489 some situations the context only wants to be 

490 temporarily pushed in which case this can be disabled. 

491 Nested pushes automatically defer the cleanup. 

492 """ 

493 if not cleanup: 

494 self._depth += 1 

495 try: 

496 with self as rv: 

497 yield rv 

498 finally: 

499 if not cleanup: 

500 self._depth -= 1 

501 

502 @property 

503 def meta(self) -> t.Dict[str, t.Any]: 

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

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

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

507 that code to manage this dictionary well. 

508 

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

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

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

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

513 the system. 

514 

515 Example usage:: 

516 

517 LANG_KEY = f'{__name__}.lang' 

518 

519 def set_language(value): 

520 ctx = get_current_context() 

521 ctx.meta[LANG_KEY] = value 

522 

523 def get_language(): 

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

525 

526 .. versionadded:: 5.0 

527 """ 

528 return self._meta 

529 

530 def make_formatter(self) -> HelpFormatter: 

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

532 usage output. 

533 

534 To quickly customize the formatter class used without overriding 

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

536 

537 .. versionchanged:: 8.0 

538 Added the :attr:`formatter_class` attribute. 

539 """ 

540 return self.formatter_class( 

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

542 ) 

543 

544 def with_resource(self, context_manager: t.ContextManager[V]) -> V: 

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

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

547 popped. 

548 

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

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

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

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

553 

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

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

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

557 

558 .. code-block:: python 

559 

560 @click.group() 

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

562 @click.pass_context 

563 def cli(ctx): 

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

565 

566 :param context_manager: The context manager to enter. 

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

568 

569 .. versionadded:: 8.0 

570 """ 

571 return self._exit_stack.enter_context(context_manager) 

572 

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

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

575 

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

577 execution. Resources that support Python's context manager 

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

579 registered with :meth:`with_resource` instead. 

580 

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

582 """ 

583 return self._exit_stack.callback(f) 

584 

585 def close(self) -> None: 

586 """Invoke all close callbacks registered with 

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

588 with :meth:`with_resource`. 

589 """ 

590 self._exit_stack.close() 

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

592 self._exit_stack = ExitStack() 

593 

594 @property 

595 def command_path(self) -> str: 

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

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

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

599 """ 

600 rv = "" 

601 if self.info_name is not None: 

602 rv = self.info_name 

603 if self.parent is not None: 

604 parent_command_path = [self.parent.command_path] 

605 

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

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

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

609 

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

611 return rv.lstrip() 

612 

613 def find_root(self) -> "Context": 

614 """Finds the outermost context.""" 

615 node = self 

616 while node.parent is not None: 

617 node = node.parent 

618 return node 

619 

620 def find_object(self, object_type: t.Type[V]) -> t.Optional[V]: 

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

622 node: t.Optional["Context"] = self 

623 

624 while node is not None: 

625 if isinstance(node.obj, object_type): 

626 return node.obj 

627 

628 node = node.parent 

629 

630 return None 

631 

632 def ensure_object(self, object_type: t.Type[V]) -> V: 

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

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

635 """ 

636 rv = self.find_object(object_type) 

637 if rv is None: 

638 self.obj = rv = object_type() 

639 return rv 

640 

641 @t.overload 

642 def lookup_default( 

643 self, name: str, call: "te.Literal[True]" = True 

644 ) -> t.Optional[t.Any]: 

645 ... 

646 

647 @t.overload 

648 def lookup_default( 

649 self, name: str, call: "te.Literal[False]" = ... 

650 ) -> t.Optional[t.Union[t.Any, t.Callable[[], t.Any]]]: 

651 ... 

652 

653 def lookup_default(self, name: str, call: bool = True) -> t.Optional[t.Any]: 

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

655 

656 :param name: Name of the parameter. 

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

658 return the callable instead. 

659 

660 .. versionchanged:: 8.0 

661 Added the ``call`` parameter. 

662 """ 

663 if self.default_map is not None: 

664 value = self.default_map.get(name) 

665 

666 if call and callable(value): 

667 return value() 

668 

669 return value 

670 

671 return None 

672 

673 def fail(self, message: str) -> "te.NoReturn": 

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

675 message. 

676 

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

678 """ 

679 raise UsageError(message, self) 

680 

681 def abort(self) -> "te.NoReturn": 

682 """Aborts the script.""" 

683 raise Abort() 

684 

685 def exit(self, code: int = 0) -> "te.NoReturn": 

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

687 raise Exit(code) 

688 

689 def get_usage(self) -> str: 

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

691 context and command. 

692 """ 

693 return self.command.get_usage(self) 

694 

695 def get_help(self) -> str: 

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

697 context and command. 

698 """ 

699 return self.command.get_help(self) 

700 

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

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

703 for a new command. 

704 

705 :meta private: 

706 """ 

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

708 

709 @t.overload 

710 def invoke( 

711 __self, # noqa: B902 

712 __callback: "t.Callable[..., V]", 

713 *args: t.Any, 

714 **kwargs: t.Any, 

715 ) -> V: 

716 ... 

717 

718 @t.overload 

719 def invoke( 

720 __self, # noqa: B902 

721 __callback: "Command", 

722 *args: t.Any, 

723 **kwargs: t.Any, 

724 ) -> t.Any: 

725 ... 

726 

727 def invoke( 

728 __self, # noqa: B902 

729 __callback: t.Union["Command", "t.Callable[..., V]"], 

730 *args: t.Any, 

731 **kwargs: t.Any, 

732 ) -> t.Union[t.Any, V]: 

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

734 are two ways to invoke this method: 

735 

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

737 keyword arguments are forwarded directly to the function. 

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

739 arguments are forwarded as well but proper click parameters 

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

741 will fill in defaults. 

742 

743 Note that before Click 3.2 keyword arguments were not properly filled 

744 in against the intention of this code and no context was created. For 

745 more information about this change and why it was done in a bugfix 

746 release see :ref:`upgrade-to-3.2`. 

747 

748 .. versionchanged:: 8.0 

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

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

751 """ 

752 if isinstance(__callback, Command): 

753 other_cmd = __callback 

754 

755 if other_cmd.callback is None: 

756 raise TypeError( 

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

758 ) 

759 else: 

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

761 

762 ctx = __self._make_sub_context(other_cmd) 

763 

764 for param in other_cmd.params: 

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

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

767 ctx, param.get_default(ctx) 

768 ) 

769 

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

771 # them on in subsequent calls. 

772 ctx.params.update(kwargs) 

773 else: 

774 ctx = __self 

775 

776 with augment_usage_errors(__self): 

777 with ctx: 

778 return __callback(*args, **kwargs) 

779 

780 def forward( 

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

782 ) -> t.Any: 

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

784 arguments from the current context if the other command expects 

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

786 

787 .. versionchanged:: 8.0 

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

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

790 """ 

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

792 if not isinstance(__cmd, Command): 

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

794 

795 for param in __self.params: 

796 if param not in kwargs: 

797 kwargs[param] = __self.params[param] 

798 

799 return __self.invoke(__cmd, *args, **kwargs) 

800 

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

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

803 from which the value of the parameter was obtained. 

804 

805 :param name: The name of the parameter. 

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

807 """ 

808 self._parameter_source[name] = source 

809 

810 def get_parameter_source(self, name: str) -> t.Optional[ParameterSource]: 

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

812 from which the value of the parameter was obtained. 

813 

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

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

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

817 value was actually taken from the default. 

818 

819 :param name: The name of the parameter. 

820 :rtype: ParameterSource 

821 

822 .. versionchanged:: 8.0 

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

824 source. 

825 """ 

826 return self._parameter_source.get(name) 

827 

828 

829class BaseCommand: 

830 """The base command implements the minimal API contract of commands. 

831 Most code will never use this as it does not implement a lot of useful 

832 functionality but it can act as the direct subclass of alternative 

833 parsing methods that do not depend on the Click parser. 

834 

835 For instance, this can be used to bridge Click and other systems like 

836 argparse or docopt. 

837 

838 Because base commands do not implement a lot of the API that other 

839 parts of Click take for granted, they are not supported for all 

840 operations. For instance, they cannot be used with the decorators 

841 usually and they have no built-in callback system. 

842 

843 .. versionchanged:: 2.0 

844 Added the `context_settings` parameter. 

845 

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

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

848 passed to the context object. 

849 """ 

850 

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

852 #: 

853 #: .. versionadded:: 8.0 

854 context_class: t.Type[Context] = Context 

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

856 allow_extra_args = False 

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

858 allow_interspersed_args = True 

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

860 ignore_unknown_options = False 

861 

862 def __init__( 

863 self, 

864 name: t.Optional[str], 

865 context_settings: t.Optional[t.MutableMapping[str, t.Any]] = None, 

866 ) -> None: 

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

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

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

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

871 self.name = name 

872 

873 if context_settings is None: 

874 context_settings = {} 

875 

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

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

878 

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

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

881 user-facing documentation. This traverses the entire structure 

882 below this command. 

883 

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

885 CLI structure. 

886 

887 :param ctx: A :class:`Context` representing this command. 

888 

889 .. versionadded:: 8.0 

890 """ 

891 return {"name": self.name} 

892 

893 def __repr__(self) -> str: 

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

895 

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

897 raise NotImplementedError("Base commands cannot get usage") 

898 

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

900 raise NotImplementedError("Base commands cannot get help") 

901 

902 def make_context( 

903 self, 

904 info_name: t.Optional[str], 

905 args: t.List[str], 

906 parent: t.Optional[Context] = None, 

907 **extra: t.Any, 

908 ) -> Context: 

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

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

911 invoke the actual command callback though. 

912 

913 To quickly customize the context class used without overriding 

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

915 

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

917 is the most descriptive name for the script or 

918 command. For the toplevel script it's usually 

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

920 the name of the command. 

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

922 :param parent: the parent context if available. 

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

924 constructor. 

925 

926 .. versionchanged:: 8.0 

927 Added the :attr:`context_class` attribute. 

928 """ 

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

930 if key not in extra: 

931 extra[key] = value 

932 

933 ctx = self.context_class( 

934 self, info_name=info_name, parent=parent, **extra # type: ignore 

935 ) 

936 

937 with ctx.scope(cleanup=False): 

938 self.parse_args(ctx, args) 

939 return ctx 

940 

941 def parse_args(self, ctx: Context, args: t.List[str]) -> t.List[str]: 

942 """Given a context and a list of arguments this creates the parser 

943 and parses the arguments, then modifies the context as necessary. 

944 This is automatically invoked by :meth:`make_context`. 

945 """ 

946 raise NotImplementedError("Base commands do not know how to parse arguments.") 

947 

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

949 """Given a context, this invokes the command. The default 

950 implementation is raising a not implemented error. 

951 """ 

952 raise NotImplementedError("Base commands are not invocable by default") 

953 

954 def shell_complete(self, ctx: Context, incomplete: str) -> t.List["CompletionItem"]: 

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

956 at the names of chained multi-commands. 

957 

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

959 commands are valid at any point during command completion. Other 

960 command classes will return more completions. 

961 

962 :param ctx: Invocation context for this command. 

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

964 

965 .. versionadded:: 8.0 

966 """ 

967 from click.shell_completion import CompletionItem 

968 

969 results: t.List["CompletionItem"] = [] 

970 

971 while ctx.parent is not None: 

972 ctx = ctx.parent 

973 

974 if isinstance(ctx.command, MultiCommand) and ctx.command.chain: 

975 results.extend( 

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

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

978 if name not in ctx.protected_args 

979 ) 

980 

981 return results 

982 

983 @t.overload 

984 def main( 

985 self, 

986 args: t.Optional[t.Sequence[str]] = None, 

987 prog_name: t.Optional[str] = None, 

988 complete_var: t.Optional[str] = None, 

989 standalone_mode: "te.Literal[True]" = True, 

990 **extra: t.Any, 

991 ) -> "te.NoReturn": 

992 ... 

993 

994 @t.overload 

995 def main( 

996 self, 

997 args: t.Optional[t.Sequence[str]] = None, 

998 prog_name: t.Optional[str] = None, 

999 complete_var: t.Optional[str] = None, 

1000 standalone_mode: bool = ..., 

1001 **extra: t.Any, 

1002 ) -> t.Any: 

1003 ... 

1004 

1005 def main( 

1006 self, 

1007 args: t.Optional[t.Sequence[str]] = None, 

1008 prog_name: t.Optional[str] = None, 

1009 complete_var: t.Optional[str] = None, 

1010 standalone_mode: bool = True, 

1011 windows_expand_args: bool = True, 

1012 **extra: t.Any, 

1013 ) -> t.Any: 

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

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

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

1017 needs to be caught. 

1018 

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

1020 a :class:`Command`. 

1021 

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

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

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

1025 the program name is constructed by taking the file 

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

1027 :param complete_var: the environment variable that controls the 

1028 bash completion support. The default is 

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

1030 uppercase. 

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

1032 in standalone mode. Click will then 

1033 handle exceptions and convert them into 

1034 error messages and the function will never 

1035 return but shut down the interpreter. If 

1036 this is set to `False` they will be 

1037 propagated to the caller and the return 

1038 value of this function is the return value 

1039 of :meth:`invoke`. 

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

1041 env vars in command line args on Windows. 

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

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

1044 

1045 .. versionchanged:: 8.0.1 

1046 Added the ``windows_expand_args`` parameter to allow 

1047 disabling command line arg expansion on Windows. 

1048 

1049 .. versionchanged:: 8.0 

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

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

1052 

1053 .. versionchanged:: 3.0 

1054 Added the ``standalone_mode`` parameter. 

1055 """ 

1056 if args is None: 

1057 args = sys.argv[1:] 

1058 

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

1060 args = _expand_args(args) 

1061 else: 

1062 args = list(args) 

1063 

1064 if prog_name is None: 

1065 prog_name = _detect_program_name() 

1066 

1067 # Process shell completion requests and exit early. 

1068 self._main_shell_completion(extra, prog_name, complete_var) 

1069 

1070 try: 

1071 try: 

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

1073 rv = self.invoke(ctx) 

1074 if not standalone_mode: 

1075 return rv 

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

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

1078 # has obvious effects 

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

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

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

1082 # by its truthiness/falsiness 

1083 ctx.exit() 

1084 except (EOFError, KeyboardInterrupt): 

1085 echo(file=sys.stderr) 

1086 raise Abort() from None 

1087 except ClickException as e: 

1088 if not standalone_mode: 

1089 raise 

1090 e.show() 

1091 sys.exit(e.exit_code) 

1092 except OSError as e: 

1093 if e.errno == errno.EPIPE: 

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

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

1096 sys.exit(1) 

1097 else: 

1098 raise 

1099 except Exit as e: 

1100 if standalone_mode: 

1101 sys.exit(e.exit_code) 

1102 else: 

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

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

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

1106 # would return its result 

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

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

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

1110 # tell the difference between the two 

1111 return e.exit_code 

1112 except Abort: 

1113 if not standalone_mode: 

1114 raise 

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

1116 sys.exit(1) 

1117 

1118 def _main_shell_completion( 

1119 self, 

1120 ctx_args: t.MutableMapping[str, t.Any], 

1121 prog_name: str, 

1122 complete_var: t.Optional[str] = None, 

1123 ) -> None: 

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

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

1126 program is invoked. 

1127 

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

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

1130 the completion instruction. Defaults to 

1131 ``_{PROG_NAME}_COMPLETE``. 

1132 """ 

1133 if complete_var is None: 

1134 complete_var = f"_{prog_name}_COMPLETE".replace("-", "_").upper() 

1135 

1136 instruction = os.environ.get(complete_var) 

1137 

1138 if not instruction: 

1139 return 

1140 

1141 from .shell_completion import shell_complete 

1142 

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

1144 sys.exit(rv) 

1145 

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

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

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

1149 

1150 

1151class Command(BaseCommand): 

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

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

1154 more parsing to commands nested below it. 

1155 

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

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

1158 passed to the context object. 

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

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

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

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

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

1164 help page after everything else. 

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

1166 shown on the command listing of the parent command. 

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

1168 option. This can be disabled by this parameter. 

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

1170 provided. This option is disabled by default. 

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

1172 if no arguments are passed 

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

1174 

1175 :param deprecated: issues a message indicating that 

1176 the command is deprecated. 

1177 

1178 .. versionchanged:: 8.1 

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

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

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

1182 

1183 .. versionchanged:: 8.0 

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

1185 

1186 .. versionchanged:: 7.1 

1187 Added the ``no_args_is_help`` parameter. 

1188 

1189 .. versionchanged:: 2.0 

1190 Added the ``context_settings`` parameter. 

1191 """ 

1192 

1193 def __init__( 

1194 self, 

1195 name: t.Optional[str], 

1196 context_settings: t.Optional[t.MutableMapping[str, t.Any]] = None, 

1197 callback: t.Optional[t.Callable[..., t.Any]] = None, 

1198 params: t.Optional[t.List["Parameter"]] = None, 

1199 help: t.Optional[str] = None, 

1200 epilog: t.Optional[str] = None, 

1201 short_help: t.Optional[str] = None, 

1202 options_metavar: t.Optional[str] = "[OPTIONS]", 

1203 add_help_option: bool = True, 

1204 no_args_is_help: bool = False, 

1205 hidden: bool = False, 

1206 deprecated: bool = False, 

1207 ) -> None: 

1208 super().__init__(name, context_settings) 

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

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

1211 self.callback = callback 

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

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

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

1215 self.params: t.List["Parameter"] = params or [] 

1216 self.help = help 

1217 self.epilog = epilog 

1218 self.options_metavar = options_metavar 

1219 self.short_help = short_help 

1220 self.add_help_option = add_help_option 

1221 self.no_args_is_help = no_args_is_help 

1222 self.hidden = hidden 

1223 self.deprecated = deprecated 

1224 

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

1226 info_dict = super().to_info_dict(ctx) 

1227 info_dict.update( 

1228 params=[param.to_info_dict() for param in self.get_params(ctx)], 

1229 help=self.help, 

1230 epilog=self.epilog, 

1231 short_help=self.short_help, 

1232 hidden=self.hidden, 

1233 deprecated=self.deprecated, 

1234 ) 

1235 return info_dict 

1236 

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

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

1239 

1240 Calls :meth:`format_usage` internally. 

1241 """ 

1242 formatter = ctx.make_formatter() 

1243 self.format_usage(ctx, formatter) 

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

1245 

1246 def get_params(self, ctx: Context) -> t.List["Parameter"]: 

1247 rv = self.params 

1248 help_option = self.get_help_option(ctx) 

1249 

1250 if help_option is not None: 

1251 rv = [*rv, help_option] 

1252 

1253 return rv 

1254 

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

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

1257 

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

1259 """ 

1260 pieces = self.collect_usage_pieces(ctx) 

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

1262 

1263 def collect_usage_pieces(self, ctx: Context) -> t.List[str]: 

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

1265 it as a list of strings. 

1266 """ 

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

1268 

1269 for param in self.get_params(ctx): 

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

1271 

1272 return rv 

1273 

1274 def get_help_option_names(self, ctx: Context) -> t.List[str]: 

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

1276 all_names = set(ctx.help_option_names) 

1277 for param in self.params: 

1278 all_names.difference_update(param.opts) 

1279 all_names.difference_update(param.secondary_opts) 

1280 return list(all_names) 

1281 

1282 def get_help_option(self, ctx: Context) -> t.Optional["Option"]: 

1283 """Returns the help option object.""" 

1284 help_options = self.get_help_option_names(ctx) 

1285 

1286 if not help_options or not self.add_help_option: 

1287 return None 

1288 

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

1290 if value and not ctx.resilient_parsing: 

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

1292 ctx.exit() 

1293 

1294 return Option( 

1295 help_options, 

1296 is_flag=True, 

1297 is_eager=True, 

1298 expose_value=False, 

1299 callback=show_help, 

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

1301 ) 

1302 

1303 def make_parser(self, ctx: Context) -> OptionParser: 

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

1305 parser = OptionParser(ctx) 

1306 for param in self.get_params(ctx): 

1307 param.add_to_parser(parser, ctx) 

1308 return parser 

1309 

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

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

1312 

1313 Calls :meth:`format_help` internally. 

1314 """ 

1315 formatter = ctx.make_formatter() 

1316 self.format_help(ctx, formatter) 

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

1318 

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

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

1321 long help string. 

1322 """ 

1323 if self.short_help: 

1324 text = inspect.cleandoc(self.short_help) 

1325 elif self.help: 

1326 text = make_default_short_help(self.help, limit) 

1327 else: 

1328 text = "" 

1329 

1330 if self.deprecated: 

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

1332 

1333 return text.strip() 

1334 

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

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

1337 

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

1339 

1340 This calls the following methods: 

1341 

1342 - :meth:`format_usage` 

1343 - :meth:`format_help_text` 

1344 - :meth:`format_options` 

1345 - :meth:`format_epilog` 

1346 """ 

1347 self.format_usage(ctx, formatter) 

1348 self.format_help_text(ctx, formatter) 

1349 self.format_options(ctx, formatter) 

1350 self.format_epilog(ctx, formatter) 

1351 

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

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

1354 text = self.help if self.help is not None else "" 

1355 

1356 if self.deprecated: 

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

1358 

1359 if text: 

1360 text = inspect.cleandoc(text).partition("\f")[0] 

1361 formatter.write_paragraph() 

1362 

1363 with formatter.indentation(): 

1364 formatter.write_text(text) 

1365 

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

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

1368 opts = [] 

1369 for param in self.get_params(ctx): 

1370 rv = param.get_help_record(ctx) 

1371 if rv is not None: 

1372 opts.append(rv) 

1373 

1374 if opts: 

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

1376 formatter.write_dl(opts) 

1377 

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

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

1380 if self.epilog: 

1381 epilog = inspect.cleandoc(self.epilog) 

1382 formatter.write_paragraph() 

1383 

1384 with formatter.indentation(): 

1385 formatter.write_text(epilog) 

1386 

1387 def parse_args(self, ctx: Context, args: t.List[str]) -> t.List[str]: 

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

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

1390 ctx.exit() 

1391 

1392 parser = self.make_parser(ctx) 

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

1394 

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

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

1397 

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

1399 ctx.fail( 

1400 ngettext( 

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

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

1403 len(args), 

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

1405 ) 

1406 

1407 ctx.args = args 

1408 ctx._opt_prefixes.update(parser._opt_prefixes) 

1409 return args 

1410 

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

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

1413 in the right way. 

1414 """ 

1415 if self.deprecated: 

1416 message = _( 

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

1418 ).format(name=self.name) 

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

1420 

1421 if self.callback is not None: 

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

1423 

1424 def shell_complete(self, ctx: Context, incomplete: str) -> t.List["CompletionItem"]: 

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

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

1427 

1428 :param ctx: Invocation context for this command. 

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

1430 

1431 .. versionadded:: 8.0 

1432 """ 

1433 from click.shell_completion import CompletionItem 

1434 

1435 results: t.List["CompletionItem"] = [] 

1436 

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

1438 for param in self.get_params(ctx): 

1439 if ( 

1440 not isinstance(param, Option) 

1441 or param.hidden 

1442 or ( 

1443 not param.multiple 

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

1445 is ParameterSource.COMMANDLINE 

1446 ) 

1447 ): 

1448 continue 

1449 

1450 results.extend( 

1451 CompletionItem(name, help=param.help) 

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

1453 if name.startswith(incomplete) 

1454 ) 

1455 

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

1457 return results 

1458 

1459 

1460class MultiCommand(Command): 

1461 """A multi command is the basic implementation of a command that 

1462 dispatches to subcommands. The most common version is the 

1463 :class:`Group`. 

1464 

1465 :param invoke_without_command: this controls how the multi command itself 

1466 is invoked. By default it's only invoked 

1467 if a subcommand is provided. 

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

1469 provided. This option is enabled by default if 

1470 `invoke_without_command` is disabled or disabled 

1471 if it's enabled. If enabled this will add 

1472 ``--help`` as argument if no arguments are 

1473 passed. 

1474 :param subcommand_metavar: the string that is used in the documentation 

1475 to indicate the subcommand place. 

1476 :param chain: if this is set to `True` chaining of multiple subcommands 

1477 is enabled. This restricts the form of commands in that 

1478 they cannot have optional arguments but it allows 

1479 multiple commands to be chained together. 

1480 :param result_callback: The result callback to attach to this multi 

1481 command. This can be set or changed later with the 

1482 :meth:`result_callback` decorator. 

1483 :param attrs: Other command arguments described in :class:`Command`. 

1484 """ 

1485 

1486 allow_extra_args = True 

1487 allow_interspersed_args = False 

1488 

1489 def __init__( 

1490 self, 

1491 name: t.Optional[str] = None, 

1492 invoke_without_command: bool = False, 

1493 no_args_is_help: t.Optional[bool] = None, 

1494 subcommand_metavar: t.Optional[str] = None, 

1495 chain: bool = False, 

1496 result_callback: t.Optional[t.Callable[..., t.Any]] = None, 

1497 **attrs: t.Any, 

1498 ) -> None: 

1499 super().__init__(name, **attrs) 

1500 

1501 if no_args_is_help is None: 

1502 no_args_is_help = not invoke_without_command 

1503 

1504 self.no_args_is_help = no_args_is_help 

1505 self.invoke_without_command = invoke_without_command 

1506 

1507 if subcommand_metavar is None: 

1508 if chain: 

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

1510 else: 

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

1512 

1513 self.subcommand_metavar = subcommand_metavar 

1514 self.chain = chain 

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

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

1517 self._result_callback = result_callback 

1518 

1519 if self.chain: 

1520 for param in self.params: 

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

1522 raise RuntimeError( 

1523 "Multi commands in chain mode cannot have" 

1524 " optional arguments." 

1525 ) 

1526 

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

1528 info_dict = super().to_info_dict(ctx) 

1529 commands = {} 

1530 

1531 for name in self.list_commands(ctx): 

1532 command = self.get_command(ctx, name) 

1533 

1534 if command is None: 

1535 continue 

1536 

1537 sub_ctx = ctx._make_sub_context(command) 

1538 

1539 with sub_ctx.scope(cleanup=False): 

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

1541 

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

1543 return info_dict 

1544 

1545 def collect_usage_pieces(self, ctx: Context) -> t.List[str]: 

1546 rv = super().collect_usage_pieces(ctx) 

1547 rv.append(self.subcommand_metavar) 

1548 return rv 

1549 

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

1551 super().format_options(ctx, formatter) 

1552 self.format_commands(ctx, formatter) 

1553 

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

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

1556 result callback is already registered this will chain them but 

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

1558 callback is invoked with the return value of the subcommand 

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

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

1561 to the main callback. 

1562 

1563 Example:: 

1564 

1565 @click.group() 

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

1567 def cli(input): 

1568 return 42 

1569 

1570 @cli.result_callback() 

1571 def process_result(result, input): 

1572 return result + input 

1573 

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

1575 callback will be removed. 

1576 

1577 .. versionchanged:: 8.0 

1578 Renamed from ``resultcallback``. 

1579 

1580 .. versionadded:: 3.0 

1581 """ 

1582 

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

1584 old_callback = self._result_callback 

1585 

1586 if old_callback is None or replace: 

1587 self._result_callback = f 

1588 return f 

1589 

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

1591 inner = old_callback(__value, *args, **kwargs) # type: ignore 

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

1593 

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

1595 return rv 

1596 

1597 return decorator 

1598 

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

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

1601 after the options. 

1602 """ 

1603 commands = [] 

1604 for subcommand in self.list_commands(ctx): 

1605 cmd = self.get_command(ctx, subcommand) 

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

1607 if cmd is None: 

1608 continue 

1609 if cmd.hidden: 

1610 continue 

1611 

1612 commands.append((subcommand, cmd)) 

1613 

1614 # allow for 3 times the default spacing 

1615 if len(commands): 

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

1617 

1618 rows = [] 

1619 for subcommand, cmd in commands: 

1620 help = cmd.get_short_help_str(limit) 

1621 rows.append((subcommand, help)) 

1622 

1623 if rows: 

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

1625 formatter.write_dl(rows) 

1626 

1627 def parse_args(self, ctx: Context, args: t.List[str]) -> t.List[str]: 

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

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

1630 ctx.exit() 

1631 

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

1633 

1634 if self.chain: 

1635 ctx.protected_args = rest 

1636 ctx.args = [] 

1637 elif rest: 

1638 ctx.protected_args, ctx.args = rest[:1], rest[1:] 

1639 

1640 return ctx.args 

1641 

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

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

1644 if self._result_callback is not None: 

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

1646 return value 

1647 

1648 if not ctx.protected_args: 

1649 if self.invoke_without_command: 

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

1651 # invoked with the group return value for regular 

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

1653 with ctx: 

1654 rv = super().invoke(ctx) 

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

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

1657 

1658 # Fetch args back out 

1659 args = [*ctx.protected_args, *ctx.args] 

1660 ctx.args = [] 

1661 ctx.protected_args = [] 

1662 

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

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

1665 # name of the command to invoke. 

1666 if not self.chain: 

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

1668 # resources until the result processor has worked. 

1669 with ctx: 

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

1671 assert cmd is not None 

1672 ctx.invoked_subcommand = cmd_name 

1673 super().invoke(ctx) 

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

1675 with sub_ctx: 

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

1677 

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

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

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

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

1682 # but nothing else. 

1683 with ctx: 

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

1685 super().invoke(ctx) 

1686 

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

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

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

1690 contexts = [] 

1691 while args: 

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

1693 assert cmd is not None 

1694 sub_ctx = cmd.make_context( 

1695 cmd_name, 

1696 args, 

1697 parent=ctx, 

1698 allow_extra_args=True, 

1699 allow_interspersed_args=False, 

1700 ) 

1701 contexts.append(sub_ctx) 

1702 args, sub_ctx.args = sub_ctx.args, [] 

1703 

1704 rv = [] 

1705 for sub_ctx in contexts: 

1706 with sub_ctx: 

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

1708 return _process_result(rv) 

1709 

1710 def resolve_command( 

1711 self, ctx: Context, args: t.List[str] 

1712 ) -> t.Tuple[t.Optional[str], t.Optional[Command], t.List[str]]: 

1713 cmd_name = make_str(args[0]) 

1714 original_cmd_name = cmd_name 

1715 

1716 # Get the command 

1717 cmd = self.get_command(ctx, cmd_name) 

1718 

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

1720 # function available, we try with that one. 

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

1722 cmd_name = ctx.token_normalize_func(cmd_name) 

1723 cmd = self.get_command(ctx, cmd_name) 

1724 

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

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

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

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

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

1730 # place. 

1731 if cmd is None and not ctx.resilient_parsing: 

1732 if split_opt(cmd_name)[0]: 

1733 self.parse_args(ctx, ctx.args) 

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

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

1736 

1737 def get_command(self, ctx: Context, cmd_name: str) -> t.Optional[Command]: 

1738 """Given a context and a command name, this returns a 

1739 :class:`Command` object if it exists or returns `None`. 

1740 """ 

1741 raise NotImplementedError 

1742 

1743 def list_commands(self, ctx: Context) -> t.List[str]: 

1744 """Returns a list of subcommand names in the order they should 

1745 appear. 

1746 """ 

1747 return [] 

1748 

1749 def shell_complete(self, ctx: Context, incomplete: str) -> t.List["CompletionItem"]: 

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

1751 at the names of options, subcommands, and chained 

1752 multi-commands. 

1753 

1754 :param ctx: Invocation context for this command. 

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

1756 

1757 .. versionadded:: 8.0 

1758 """ 

1759 from click.shell_completion import CompletionItem 

1760 

1761 results = [ 

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

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

1764 ] 

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

1766 return results 

1767 

1768 

1769class Group(MultiCommand): 

1770 """A group allows a command to have subcommands attached. This is 

1771 the most common way to implement nesting in Click. 

1772 

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

1774 :param commands: A dict mapping names to :class:`Command` objects. 

1775 Can also be a list of :class:`Command`, which will use 

1776 :attr:`Command.name` to create the dict. 

1777 :param attrs: Other command arguments described in 

1778 :class:`MultiCommand`, :class:`Command`, and 

1779 :class:`BaseCommand`. 

1780 

1781 .. versionchanged:: 8.0 

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

1783 """ 

1784 

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

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

1787 #: subcommands use a custom command class. 

1788 #: 

1789 #: .. versionadded:: 8.0 

1790 command_class: t.Optional[t.Type[Command]] = None 

1791 

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

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

1794 #: subgroups use a custom group class. 

1795 #: 

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

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

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

1799 #: custom groups. 

1800 #: 

1801 #: .. versionadded:: 8.0 

1802 group_class: t.Optional[t.Union[t.Type["Group"], t.Type[type]]] = None 

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

1804 

1805 def __init__( 

1806 self, 

1807 name: t.Optional[str] = None, 

1808 commands: t.Optional[ 

1809 t.Union[t.MutableMapping[str, Command], t.Sequence[Command]] 

1810 ] = None, 

1811 **attrs: t.Any, 

1812 ) -> None: 

1813 super().__init__(name, **attrs) 

1814 

1815 if commands is None: 

1816 commands = {} 

1817 elif isinstance(commands, abc.Sequence): 

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

1819 

1820 #: The registered subcommands by their exported names. 

1821 self.commands: t.MutableMapping[str, Command] = commands 

1822 

1823 def add_command(self, cmd: Command, name: t.Optional[str] = None) -> None: 

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

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

1826 """ 

1827 name = name or cmd.name 

1828 if name is None: 

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

1830 _check_multicommand(self, name, cmd, register=True) 

1831 self.commands[name] = cmd 

1832 

1833 @t.overload 

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

1835 ... 

1836 

1837 @t.overload 

1838 def command( 

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

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

1841 ... 

1842 

1843 def command( 

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

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

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

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

1848 immediately registers the created command with this group by 

1849 calling :meth:`add_command`. 

1850 

1851 To customize the command class used, set the 

1852 :attr:`command_class` attribute. 

1853 

1854 .. versionchanged:: 8.1 

1855 This decorator can be applied without parentheses. 

1856 

1857 .. versionchanged:: 8.0 

1858 Added the :attr:`command_class` attribute. 

1859 """ 

1860 from .decorators import command 

1861 

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

1863 kwargs["cls"] = self.command_class 

1864 

1865 func: t.Optional[t.Callable[..., t.Any]] = None 

1866 

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

1868 assert ( 

1869 len(args) == 1 and not kwargs 

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

1871 (func,) = args 

1872 args = () 

1873 

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

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

1876 self.add_command(cmd) 

1877 return cmd 

1878 

1879 if func is not None: 

1880 return decorator(func) 

1881 

1882 return decorator 

1883 

1884 @t.overload 

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

1886 ... 

1887 

1888 @t.overload 

1889 def group( 

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

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

1892 ... 

1893 

1894 def group( 

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

1896 ) -> t.Union[t.Callable[[t.Callable[..., t.Any]], "Group"], "Group"]: 

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

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

1899 immediately registers the created group with this group by 

1900 calling :meth:`add_command`. 

1901 

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

1903 attribute. 

1904 

1905 .. versionchanged:: 8.1 

1906 This decorator can be applied without parentheses. 

1907 

1908 .. versionchanged:: 8.0 

1909 Added the :attr:`group_class` attribute. 

1910 """ 

1911 from .decorators import group 

1912 

1913 func: t.Optional[t.Callable[..., t.Any]] = None 

1914 

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

1916 assert ( 

1917 len(args) == 1 and not kwargs 

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

1919 (func,) = args 

1920 args = () 

1921 

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

1923 if self.group_class is type: 

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

1925 else: 

1926 kwargs["cls"] = self.group_class 

1927 

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

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

1930 self.add_command(cmd) 

1931 return cmd 

1932 

1933 if func is not None: 

1934 return decorator(func) 

1935 

1936 return decorator 

1937 

1938 def get_command(self, ctx: Context, cmd_name: str) -> t.Optional[Command]: 

1939 return self.commands.get(cmd_name) 

1940 

1941 def list_commands(self, ctx: Context) -> t.List[str]: 

1942 return sorted(self.commands) 

1943 

1944 

1945class CommandCollection(MultiCommand): 

1946 """A command collection is a multi command that merges multiple multi 

1947 commands together into one. This is a straightforward implementation 

1948 that accepts a list of different multi commands as sources and 

1949 provides all the commands for each of them. 

1950 

1951 See :class:`MultiCommand` and :class:`Command` for the description of 

1952 ``name`` and ``attrs``. 

1953 """ 

1954 

1955 def __init__( 

1956 self, 

1957 name: t.Optional[str] = None, 

1958 sources: t.Optional[t.List[MultiCommand]] = None, 

1959 **attrs: t.Any, 

1960 ) -> None: 

1961 super().__init__(name, **attrs) 

1962 #: The list of registered multi commands. 

1963 self.sources: t.List[MultiCommand] = sources or [] 

1964 

1965 def add_source(self, multi_cmd: MultiCommand) -> None: 

1966 """Adds a new multi command to the chain dispatcher.""" 

1967 self.sources.append(multi_cmd) 

1968 

1969 def get_command(self, ctx: Context, cmd_name: str) -> t.Optional[Command]: 

1970 for source in self.sources: 

1971 rv = source.get_command(ctx, cmd_name) 

1972 

1973 if rv is not None: 

1974 if self.chain: 

1975 _check_multicommand(self, cmd_name, rv) 

1976 

1977 return rv 

1978 

1979 return None 

1980 

1981 def list_commands(self, ctx: Context) -> t.List[str]: 

1982 rv: t.Set[str] = set() 

1983 

1984 for source in self.sources: 

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

1986 

1987 return sorted(rv) 

1988 

1989 

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

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

1992 error, or return an iterator over the value. 

1993 """ 

1994 if isinstance(value, str): 

1995 raise TypeError 

1996 

1997 return iter(value) 

1998 

1999 

2000class Parameter: 

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

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

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

2004 intentionally not finalized. 

2005 

2006 Some settings are supported by both options and arguments. 

2007 

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

2009 argument. This is a list of flags or argument 

2010 names. 

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

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

2013 automatically if supported. 

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

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

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

2017 without any arguments. 

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

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

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

2021 including prompts. 

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

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

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

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

2026 parameters are collected. 

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

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

2029 to the command callback and stored on the context, 

2030 otherwise it's skipped. 

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

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

2033 order of processing. 

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

2035 that should be checked. 

2036 :param shell_complete: A function that returns custom shell 

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

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

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

2040 strings. 

2041 

2042 .. versionchanged:: 8.0 

2043 ``process_value`` validates required parameters and bounded 

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

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

2046 ``full_process_value`` is removed. 

2047 

2048 .. versionchanged:: 8.0 

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

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

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

2052 new requirements. 

2053 

2054 .. versionchanged:: 8.0 

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

2056 tuples. 

2057 

2058 .. versionchanged:: 8.0 

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

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

2061 default to ``()``. 

2062 

2063 .. versionchanged:: 7.1 

2064 Empty environment variables are ignored rather than taking the 

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

2066 variables if they can't unset them. 

2067 

2068 .. versionchanged:: 2.0 

2069 Changed signature for parameter callback to also be passed the 

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

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

2072 """ 

2073 

2074 param_type_name = "parameter" 

2075 

2076 def __init__( 

2077 self, 

2078 param_decls: t.Optional[t.Sequence[str]] = None, 

2079 type: t.Optional[t.Union[types.ParamType, t.Any]] = None, 

2080 required: bool = False, 

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

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

2083 nargs: t.Optional[int] = None, 

2084 multiple: bool = False, 

2085 metavar: t.Optional[str] = None, 

2086 expose_value: bool = True, 

2087 is_eager: bool = False, 

2088 envvar: t.Optional[t.Union[str, t.Sequence[str]]] = None, 

2089 shell_complete: t.Optional[ 

2090 t.Callable[ 

2091 [Context, "Parameter", str], 

2092 t.Union[t.List["CompletionItem"], t.List[str]], 

2093 ] 

2094 ] = None, 

2095 ) -> None: 

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

2097 param_decls or (), expose_value 

2098 ) 

2099 self.type = types.convert_type(type, default) 

2100 

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

2102 # information available. 

2103 if nargs is None: 

2104 if self.type.is_composite: 

2105 nargs = self.type.arity 

2106 else: 

2107 nargs = 1 

2108 

2109 self.required = required 

2110 self.callback = callback 

2111 self.nargs = nargs 

2112 self.multiple = multiple 

2113 self.expose_value = expose_value 

2114 self.default = default 

2115 self.is_eager = is_eager 

2116 self.metavar = metavar 

2117 self.envvar = envvar 

2118 self._custom_shell_complete = shell_complete 

2119 

2120 if __debug__: 

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

2122 raise ValueError( 

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

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

2125 ) 

2126 

2127 # Skip no default or callable default. 

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

2129 

2130 if check_default is not None: 

2131 if multiple: 

2132 try: 

2133 # Only check the first value against nargs. 

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

2135 except TypeError: 

2136 raise ValueError( 

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

2138 ) from None 

2139 

2140 # Can be None for multiple with empty default. 

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

2142 try: 

2143 _check_iter(check_default) 

2144 except TypeError: 

2145 if multiple: 

2146 message = ( 

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

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

2149 ) 

2150 else: 

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

2152 

2153 raise ValueError(message) from None 

2154 

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

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

2157 raise ValueError( 

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

2159 ) 

2160 

2161 def to_info_dict(self) -> t.Dict[str, t.Any]: 

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

2163 user-facing documentation. 

2164 

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

2166 CLI structure. 

2167 

2168 .. versionadded:: 8.0 

2169 """ 

2170 return { 

2171 "name": self.name, 

2172 "param_type_name": self.param_type_name, 

2173 "opts": self.opts, 

2174 "secondary_opts": self.secondary_opts, 

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

2176 "required": self.required, 

2177 "nargs": self.nargs, 

2178 "multiple": self.multiple, 

2179 "default": self.default, 

2180 "envvar": self.envvar, 

2181 } 

2182 

2183 def __repr__(self) -> str: 

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

2185 

2186 def _parse_decls( 

2187 self, decls: t.Sequence[str], expose_value: bool 

2188 ) -> t.Tuple[t.Optional[str], t.List[str], t.List[str]]: 

2189 raise NotImplementedError() 

2190 

2191 @property 

2192 def human_readable_name(self) -> str: 

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

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

2195 """ 

2196 return self.name # type: ignore 

2197 

2198 def make_metavar(self) -> str: 

2199 if self.metavar is not None: 

2200 return self.metavar 

2201 

2202 metavar = self.type.get_metavar(self) 

2203 

2204 if metavar is None: 

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

2206 

2207 if self.nargs != 1: 

2208 metavar += "..." 

2209 

2210 return metavar 

2211 

2212 @t.overload 

2213 def get_default( 

2214 self, ctx: Context, call: "te.Literal[True]" = True 

2215 ) -> t.Optional[t.Any]: 

2216 ... 

2217 

2218 @t.overload 

2219 def get_default( 

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

2221 ) -> t.Optional[t.Union[t.Any, t.Callable[[], t.Any]]]: 

2222 ... 

2223 

2224 def get_default( 

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

2226 ) -> t.Optional[t.Union[t.Any, t.Callable[[], t.Any]]]: 

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

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

2229 

2230 :param ctx: Current context. 

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

2232 return the callable instead. 

2233 

2234 .. versionchanged:: 8.0.2 

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

2236 

2237 .. versionchanged:: 8.0.1 

2238 Type casting can fail in resilient parsing mode. Invalid 

2239 defaults will not prevent showing help text. 

2240 

2241 .. versionchanged:: 8.0 

2242 Looks at ``ctx.default_map`` first. 

2243 

2244 .. versionchanged:: 8.0 

2245 Added the ``call`` parameter. 

2246 """ 

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

2248 

2249 if value is None: 

2250 value = self.default 

2251 

2252 if call and callable(value): 

2253 value = value() 

2254 

2255 return value 

2256 

2257 def add_to_parser(self, parser: OptionParser, ctx: Context) -> None: 

2258 raise NotImplementedError() 

2259 

2260 def consume_value( 

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

2262 ) -> t.Tuple[t.Any, ParameterSource]: 

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

2264 source = ParameterSource.COMMANDLINE 

2265 

2266 if value is None: 

2267 value = self.value_from_envvar(ctx) 

2268 source = ParameterSource.ENVIRONMENT 

2269 

2270 if value is None: 

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

2272 source = ParameterSource.DEFAULT_MAP 

2273 

2274 if value is None: 

2275 value = self.get_default(ctx) 

2276 source = ParameterSource.DEFAULT 

2277 

2278 return value, source 

2279 

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

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

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

2283 """ 

2284 if value is None: 

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

2286 

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

2288 try: 

2289 return _check_iter(value) 

2290 except TypeError: 

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

2292 # the parser should construct an iterable when parsing 

2293 # the command line. 

2294 raise BadParameter( 

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

2296 ) from None 

2297 

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

2299 convert: t.Callable[[t.Any], t.Any] = partial( 

2300 self.type, param=self, ctx=ctx 

2301 ) 

2302 elif self.nargs == -1: 

2303 

2304 def convert(value: t.Any) -> t.Tuple[t.Any, ...]: 

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

2306 

2307 else: # nargs > 1 

2308 

2309 def convert(value: t.Any) -> t.Tuple[t.Any, ...]: 

2310 value = tuple(check_iter(value)) 

2311 

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

2313 raise BadParameter( 

2314 ngettext( 

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

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

2317 len(value), 

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

2319 ctx=ctx, 

2320 param=self, 

2321 ) 

2322 

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

2324 

2325 if self.multiple: 

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

2327 

2328 return convert(value) 

2329 

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

2331 if value is None: 

2332 return True 

2333 

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

2335 return True 

2336 

2337 return False 

2338 

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

2340 value = self.type_cast_value(ctx, value) 

2341 

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

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

2344 

2345 if self.callback is not None: 

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

2347 

2348 return value 

2349 

2350 def resolve_envvar_value(self, ctx: Context) -> t.Optional[str]: 

2351 if self.envvar is None: 

2352 return None 

2353 

2354 if isinstance(self.envvar, str): 

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

2356 

2357 if rv: 

2358 return rv 

2359 else: 

2360 for envvar in self.envvar: 

2361 rv = os.environ.get(envvar) 

2362 

2363 if rv: 

2364 return rv 

2365 

2366 return None 

2367 

2368 def value_from_envvar(self, ctx: Context) -> t.Optional[t.Any]: 

2369 rv: t.Optional[t.Any] = self.resolve_envvar_value(ctx) 

2370 

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

2372 rv = self.type.split_envvar_value(rv) 

2373 

2374 return rv 

2375 

2376 def handle_parse_result( 

2377 self, ctx: Context, opts: t.Mapping[str, t.Any], args: t.List[str] 

2378 ) -> t.Tuple[t.Any, t.List[str]]: 

2379 with augment_usage_errors(ctx, param=self): 

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

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

2382 

2383 try: 

2384 value = self.process_value(ctx, value) 

2385 except Exception: 

2386 if not ctx.resilient_parsing: 

2387 raise 

2388 

2389 value = None 

2390 

2391 if self.expose_value: 

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

2393 

2394 return value, args 

2395 

2396 def get_help_record(self, ctx: Context) -> t.Optional[t.Tuple[str, str]]: 

2397 pass 

2398 

2399 def get_usage_pieces(self, ctx: Context) -> t.List[str]: 

2400 return [] 

2401 

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

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

2404 indicate which param caused the error. 

2405 """ 

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

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

2408 

2409 def shell_complete(self, ctx: Context, incomplete: str) -> t.List["CompletionItem"]: 

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

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

2412 Otherwise, the :attr:`type` 

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

2414 

2415 :param ctx: Invocation context for this command. 

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

2417 

2418 .. versionadded:: 8.0 

2419 """ 

2420 if self._custom_shell_complete is not None: 

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

2422 

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

2424 from click.shell_completion import CompletionItem 

2425 

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

2427 

2428 return t.cast(t.List["CompletionItem"], results) 

2429 

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

2431 

2432 

2433class Option(Parameter): 

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

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

2436 

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

2438 

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

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

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

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

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

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

2445 its value is ``False``. 

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

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

2448 shown. 

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

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

2451 will be the option name capitalized. 

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

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

2454 ``True`` to customize the message. 

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

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

2457 without a value. 

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

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

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

2461 auto detection. 

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

2463 enabled. This is set to a boolean automatically if 

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

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

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

2467 in how it works but supports arbitrary number of 

2468 arguments. 

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

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

2471 parameter will be pulled from an environment 

2472 variable in case a prefix is defined on the 

2473 context. 

2474 :param help: the help string. 

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

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

2477 

2478 .. versionchanged:: 8.1.0 

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

2480 ``@option`` decorator. 

2481 

2482 .. versionchanged:: 8.1.0 

2483 The ``show_default`` parameter overrides 

2484 ``Context.show_default``. 

2485 

2486 .. versionchanged:: 8.1.0 

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

2488 default value is ``False``. 

2489 

2490 .. versionchanged:: 8.0.1 

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

2492 """ 

2493 

2494 param_type_name = "option" 

2495 

2496 def __init__( 

2497 self, 

2498 param_decls: t.Optional[t.Sequence[str]] = None, 

2499 show_default: t.Union[bool, str, None] = None, 

2500 prompt: t.Union[bool, str] = False, 

2501 confirmation_prompt: t.Union[bool, str] = False, 

2502 prompt_required: bool = True, 

2503 hide_input: bool = False, 

2504 is_flag: t.Optional[bool] = None, 

2505 flag_value: t.Optional[t.Any] = None, 

2506 multiple: bool = False, 

2507 count: bool = False, 

2508 allow_from_autoenv: bool = True, 

2509 type: t.Optional[t.Union[types.ParamType, t.Any]] = None, 

2510 help: t.Optional[str] = None, 

2511 hidden: bool = False, 

2512 show_choices: bool = True, 

2513 show_envvar: bool = False, 

2514 **attrs: t.Any, 

2515 ) -> None: 

2516 if help: 

2517 help = inspect.cleandoc(help) 

2518 

2519 default_is_missing = "default" not in attrs 

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

2521 

2522 if prompt is True: 

2523 if self.name is None: 

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

2525 

2526 prompt_text: t.Optional[str] = self.name.replace("_", " ").capitalize() 

2527 elif prompt is False: 

2528 prompt_text = None 

2529 else: 

2530 prompt_text = prompt 

2531 

2532 self.prompt = prompt_text 

2533 self.confirmation_prompt = confirmation_prompt 

2534 self.prompt_required = prompt_required 

2535 self.hide_input = hide_input 

2536 self.hidden = hidden 

2537 

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

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

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

2541 

2542 if is_flag is None: 

2543 if flag_value is not None: 

2544 # Implicitly a flag because flag_value was set. 

2545 is_flag = True 

2546 elif self._flag_needs_value: 

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

2548 is_flag = False 

2549 else: 

2550 # Implicitly a flag because flag options were given. 

2551 is_flag = bool(self.secondary_opts) 

2552 elif is_flag is False and not self._flag_needs_value: 

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

2554 # flag if flag_value is set. 

2555 self._flag_needs_value = flag_value is not None 

2556 

2557 if is_flag and default_is_missing and not self.required: 

2558 self.default: t.Union[t.Any, t.Callable[[], t.Any]] = False 

2559 

2560 if flag_value is None: 

2561 flag_value = not self.default 

2562 

2563 if is_flag and type is None: 

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

2565 # default. 

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

2567 

2568 self.is_flag: bool = is_flag 

2569 self.is_bool_flag = is_flag and isinstance(self.type, types.BoolParamType) 

2570 self.flag_value: t.Any = flag_value 

2571 

2572 # Counting 

2573 self.count = count 

2574 if count: 

2575 if type is None: 

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

2577 if default_is_missing: 

2578 self.default = 0 

2579 

2580 self.allow_from_autoenv = allow_from_autoenv 

2581 self.help = help 

2582 self.show_default = show_default 

2583 self.show_choices = show_choices 

2584 self.show_envvar = show_envvar 

2585 

2586 if __debug__: 

2587 if self.nargs == -1: 

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

2589 

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

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

2592 

2593 if not self.is_bool_flag and self.secondary_opts: 

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

2595 

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

2597 raise TypeError( 

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

2599 ) 

2600 

2601 if self.count: 

2602 if self.multiple: 

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

2604 

2605 if self.is_flag: 

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

2607 

2608 if self.multiple and self.is_flag: 

2609 raise TypeError("'multiple' is not valid with 'is_flag', use 'count'.") 

2610 

2611 def to_info_dict(self) -> t.Dict[str, t.Any]: 

2612 info_dict = super().to_info_dict() 

2613 info_dict.update( 

2614 help=self.help, 

2615 prompt=self.prompt, 

2616 is_flag=self.is_flag, 

2617 flag_value=self.flag_value, 

2618 count=self.count, 

2619 hidden=self.hidden, 

2620 ) 

2621 return info_dict 

2622 

2623 def _parse_decls( 

2624 self, decls: t.Sequence[str], expose_value: bool 

2625 ) -> t.Tuple[t.Optional[str], t.List[str], t.List[str]]: 

2626 opts = [] 

2627 secondary_opts = [] 

2628 name = None 

2629 possible_names = [] 

2630 

2631 for decl in decls: 

2632 if decl.isidentifier(): 

2633 if name is not None: 

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

2635 name = decl 

2636 else: 

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

2638 if split_char in decl: 

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

2640 first = first.rstrip() 

2641 if first: 

2642 possible_names.append(split_opt(first)) 

2643 opts.append(first) 

2644 second = second.lstrip() 

2645 if second: 

2646 secondary_opts.append(second.lstrip()) 

2647 if first == second: 

2648 raise ValueError( 

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

2650 " same flag for true/false." 

2651 ) 

2652 else: 

2653 possible_names.append(split_opt(decl)) 

2654 opts.append(decl) 

2655 

2656 if name is None and possible_names: 

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

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

2659 if not name.isidentifier(): 

2660 name = None 

2661 

2662 if name is None: 

2663 if not expose_value: 

2664 return None, opts, secondary_opts 

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

2666 

2667 if not opts and not secondary_opts: 

2668 raise TypeError( 

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

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

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

2672 ) 

2673 

2674 return name, opts, secondary_opts 

2675 

2676 def add_to_parser(self, parser: OptionParser, ctx: Context) -> None: 

2677 if self.multiple: 

2678 action = "append" 

2679 elif self.count: 

2680 action = "count" 

2681 else: 

2682 action = "store" 

2683 

2684 if self.is_flag: 

2685 action = f"{action}_const" 

2686 

2687 if self.is_bool_flag and self.secondary_opts: 

2688 parser.add_option( 

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

2690 ) 

2691 parser.add_option( 

2692 obj=self, 

2693 opts=self.secondary_opts, 

2694 dest=self.name, 

2695 action=action, 

2696 const=False, 

2697 ) 

2698 else: 

2699 parser.add_option( 

2700 obj=self, 

2701 opts=self.opts, 

2702 dest=self.name, 

2703 action=action, 

2704 const=self.flag_value, 

2705 ) 

2706 else: 

2707 parser.add_option( 

2708 obj=self, 

2709 opts=self.opts, 

2710 dest=self.name, 

2711 action=action, 

2712 nargs=self.nargs, 

2713 ) 

2714 

2715 def get_help_record(self, ctx: Context) -> t.Optional[t.Tuple[str, str]]: 

2716 if self.hidden: 

2717 return None 

2718 

2719 any_prefix_is_slash = False 

2720 

2721 def _write_opts(opts: t.Sequence[str]) -> str: 

2722 nonlocal any_prefix_is_slash 

2723 

2724 rv, any_slashes = join_options(opts) 

2725 

2726 if any_slashes: 

2727 any_prefix_is_slash = True 

2728 

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

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

2731 

2732 return rv 

2733 

2734 rv = [_write_opts(self.opts)] 

2735 

2736 if self.secondary_opts: 

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

2738 

2739 help = self.help or "" 

2740 extra = [] 

2741 

2742 if self.show_envvar: 

2743 envvar = self.envvar 

2744 

2745 if envvar is None: 

2746 if ( 

2747 self.allow_from_autoenv 

2748 and ctx.auto_envvar_prefix is not None 

2749 and self.name is not None 

2750 ): 

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

2752 

2753 if envvar is not None: 

2754 var_str = ( 

2755 envvar 

2756 if isinstance(envvar, str) 

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

2758 ) 

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

2760 

2761 # Temporarily enable resilient parsing to avoid type casting 

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

2763 # help formatting in general. 

2764 resilient = ctx.resilient_parsing 

2765 ctx.resilient_parsing = True 

2766 

2767 try: 

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

2769 finally: 

2770 ctx.resilient_parsing = resilient 

2771 

2772 show_default = False 

2773 show_default_is_str = False 

2774 

2775 if self.show_default is not None: 

2776 if isinstance(self.show_default, str): 

2777 show_default_is_str = show_default = True 

2778 else: 

2779 show_default = self.show_default 

2780 elif ctx.show_default is not None: 

2781 show_default = ctx.show_default 

2782 

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

2784 if show_default_is_str: 

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

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

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

2788 elif inspect.isfunction(default_value): 

2789 default_string = _("(dynamic)") 

2790 elif self.is_bool_flag and self.secondary_opts: 

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

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

2793 default_string = split_opt( 

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

2795 )[1] 

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

2797 default_string = "" 

2798 else: 

2799 default_string = str(default_value) 

2800 

2801 if default_string: 

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

2803 

2804 if ( 

2805 isinstance(self.type, types._NumberRangeBase) 

2806 # skip count with default range type 

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

2808 ): 

2809 range_str = self.type._describe_range() 

2810 

2811 if range_str: 

2812 extra.append(range_str) 

2813 

2814 if self.required: 

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

2816 

2817 if extra: 

2818 extra_str = "; ".join(extra) 

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

2820 

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

2822 

2823 @t.overload 

2824 def get_default( 

2825 self, ctx: Context, call: "te.Literal[True]" = True 

2826 ) -> t.Optional[t.Any]: 

2827 ... 

2828 

2829 @t.overload 

2830 def get_default( 

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

2832 ) -> t.Optional[t.Union[t.Any, t.Callable[[], t.Any]]]: 

2833 ... 

2834 

2835 def get_default( 

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

2837 ) -> t.Optional[t.Union[t.Any, t.Callable[[], t.Any]]]: 

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

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

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

2841 # value as default. 

2842 if self.is_flag and not self.is_bool_flag: 

2843 for param in ctx.command.params: 

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

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

2846 

2847 return None 

2848 

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

2850 

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

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

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

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

2855 value as result. 

2856 """ 

2857 assert self.prompt is not None 

2858 

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

2860 default = self.get_default(ctx) 

2861 

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

2863 # differently. 

2864 if self.is_bool_flag: 

2865 return confirm(self.prompt, default) 

2866 

2867 return prompt( 

2868 self.prompt, 

2869 default=default, 

2870 type=self.type, 

2871 hide_input=self.hide_input, 

2872 show_choices=self.show_choices, 

2873 confirmation_prompt=self.confirmation_prompt, 

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

2875 ) 

2876 

2877 def resolve_envvar_value(self, ctx: Context) -> t.Optional[str]: 

2878 rv = super().resolve_envvar_value(ctx) 

2879 

2880 if rv is not None: 

2881 return rv 

2882 

2883 if ( 

2884 self.allow_from_autoenv 

2885 and ctx.auto_envvar_prefix is not None 

2886 and self.name is not None 

2887 ): 

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

2889 rv = os.environ.get(envvar) 

2890 

2891 if rv: 

2892 return rv 

2893 

2894 return None 

2895 

2896 def value_from_envvar(self, ctx: Context) -> t.Optional[t.Any]: 

2897 rv: t.Optional[t.Any] = self.resolve_envvar_value(ctx) 

2898 

2899 if rv is None: 

2900 return None 

2901 

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

2903 

2904 if value_depth > 0: 

2905 rv = self.type.split_envvar_value(rv) 

2906 

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

2908 rv = batch(rv, self.nargs) 

2909 

2910 return rv 

2911 

2912 def consume_value( 

2913 self, ctx: Context, opts: t.Mapping[str, "Parameter"] 

2914 ) -> t.Tuple[t.Any, ParameterSource]: 

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

2916 

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

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

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

2920 if value is _flag_needs_value: 

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

2922 value = self.prompt_for_value(ctx) 

2923 source = ParameterSource.PROMPT 

2924 else: 

2925 value = self.flag_value 

2926 source = ParameterSource.COMMANDLINE 

2927 

2928 elif ( 

2929 self.multiple 

2930 and value is not None 

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

2932 ): 

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

2934 source = ParameterSource.COMMANDLINE 

2935 

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

2937 # prompting is enabled. 

2938 elif ( 

2939 source in {None, ParameterSource.DEFAULT} 

2940 and self.prompt is not None 

2941 and (self.required or self.prompt_required) 

2942 and not ctx.resilient_parsing 

2943 ): 

2944 value = self.prompt_for_value(ctx) 

2945 source = ParameterSource.PROMPT 

2946 

2947 return value, source 

2948 

2949 

2950class Argument(Parameter): 

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

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

2953 and are required by default. 

2954 

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

2956 """ 

2957 

2958 param_type_name = "argument" 

2959 

2960 def __init__( 

2961 self, 

2962 param_decls: t.Sequence[str], 

2963 required: t.Optional[bool] = None, 

2964 **attrs: t.Any, 

2965 ) -> None: 

2966 if required is None: 

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

2968 required = False 

2969 else: 

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

2971 

2972 if "multiple" in attrs: 

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

2974 

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

2976 

2977 if __debug__: 

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

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

2980 

2981 @property 

2982 def human_readable_name(self) -> str: 

2983 if self.metavar is not None: 

2984 return self.metavar 

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

2986 

2987 def make_metavar(self) -> str: 

2988 if self.metavar is not None: 

2989 return self.metavar 

2990 var = self.type.get_metavar(self) 

2991 if not var: 

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

2993 if not self.required: 

2994 var = f"[{var}]" 

2995 if self.nargs != 1: 

2996 var += "..." 

2997 return var 

2998 

2999 def _parse_decls( 

3000 self, decls: t.Sequence[str], expose_value: bool 

3001 ) -> t.Tuple[t.Optional[str], t.List[str], t.List[str]]: 

3002 if not decls: 

3003 if not expose_value: 

3004 return None, [], [] 

3005 raise TypeError("Could not determine name for argument") 

3006 if len(decls) == 1: 

3007 name = arg = decls[0] 

3008 name = name.replace("-", "_").lower() 

3009 else: 

3010 raise TypeError( 

3011 "Arguments take exactly one parameter declaration, got" 

3012 f" {len(decls)}." 

3013 ) 

3014 return name, [arg], [] 

3015 

3016 def get_usage_pieces(self, ctx: Context) -> t.List[str]: 

3017 return [self.make_metavar()] 

3018 

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

3020 return f"'{self.make_metavar()}'" 

3021 

3022 def add_to_parser(self, parser: OptionParser, ctx: Context) -> None: 

3023 parser.add_argument(dest=self.name, nargs=self.nargs, obj=self)