Coverage for src/click/core.py: 15%

1151 statements  

« prev     ^ index     » next       coverage.py v7.2.2, created at 2023-05-21 11:49 +0200

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: 40 ↛ 41line 40 didn't jump to line 41, because the condition on line 40 was never true

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.Dict[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.Dict[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: 764 ↛ 765,   764 ↛ 7722 missed branches: 1) line 764 didn't jump to line 765, because the loop on line 764 never started, 2) line 764 didn't jump to line 772, because the loop on line 764 didn't complete

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): 792 ↛ 793,   792 ↛ 7952 missed branches: 1) line 792 didn't jump to line 793, because the condition on line 792 was never true, 2) line 792 didn't jump to line 795, because the condition on line 792 was never false

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.Dict[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.Dict[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 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: 930 ↛ 929,   930 ↛ 9312 missed branches: 1) line 930 didn't jump to line 929, because the condition on line 930 was never false, 2) line 930 didn't jump to line 931, because the condition on line 930 was never true

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 invokable 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: 971 ↛ 981line 971 didn't jump to line 981, because the condition on line 971 was never false

972 ctx = ctx.parent 

973 

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

975 results.extend( 975 ↛ exit,   975 ↛ 9712 missed branches: 1) line 975 didn't jump to the function exit, 2) line 975 didn't jump to line 971

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.Dict[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: 1133 ↛ 1134,   1133 ↛ 11362 missed branches: 1) line 1133 didn't jump to line 1134, because the condition on line 1133 was never true, 2) line 1133 didn't jump to line 1136, because the condition on line 1133 was never false

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.Dict[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( 1227 ↛ exit,   1227 ↛ 12352 missed branches: 1) line 1227 didn't jump to the function exit, 2) line 1227 didn't jump to line 1235

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): 1369 ↛ 1370,   1369 ↛ 13742 missed branches: 1) line 1369 didn't jump to line 1370, because the loop on line 1369 never started, 2) line 1369 didn't jump to line 1374, because the loop on line 1369 didn't complete

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 ( 1439 ↛ 1448,   1439 ↛ 14502 missed branches: 1) line 1439 didn't jump to line 1448, 2) line 1439 didn't jump to line 1450

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 """ 

1484 

1485 allow_extra_args = True 

1486 allow_interspersed_args = False 

1487 

1488 def __init__( 

1489 self, 

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

1491 invoke_without_command: bool = False, 

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

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

1494 chain: bool = False, 

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

1496 **attrs: t.Any, 

1497 ) -> None: 

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

1499 

1500 if no_args_is_help is None: 1500 ↛ 1501,   1500 ↛ 15032 missed branches: 1) line 1500 didn't jump to line 1501, because the condition on line 1500 was never true, 2) line 1500 didn't jump to line 1503, because the condition on line 1500 was never false

1501 no_args_is_help = not invoke_without_command 

1502 

1503 self.no_args_is_help = no_args_is_help 

1504 self.invoke_without_command = invoke_without_command 

1505 

1506 if subcommand_metavar is None: 

1507 if chain: 

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

1509 else: 

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

1511 

1512 self.subcommand_metavar = subcommand_metavar 

1513 self.chain = chain 

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

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

1516 self._result_callback = result_callback 

1517 

1518 if self.chain: 

1519 for param in self.params: 

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

1521 raise RuntimeError( 

1522 "Multi commands in chain mode cannot have" 

1523 " optional arguments." 

1524 ) 

1525 

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

1527 info_dict = super().to_info_dict(ctx) 

1528 commands = {} 

1529 

1530 for name in self.list_commands(ctx): 

1531 command = self.get_command(ctx, name) 

1532 

1533 if command is None: 

1534 continue 

1535 

1536 sub_ctx = ctx._make_sub_context(command) 

1537 

1538 with sub_ctx.scope(cleanup=False): 

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

1540 

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

1542 return info_dict 

1543 

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

1545 rv = super().collect_usage_pieces(ctx) 

1546 rv.append(self.subcommand_metavar) 

1547 return rv 

1548 

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

1550 super().format_options(ctx, formatter) 

1551 self.format_commands(ctx, formatter) 

1552 

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

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

1555 result callback is already registered this will chain them but 

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

1557 callback is invoked with the return value of the subcommand 

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

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

1560 to the main callback. 

1561 

1562 Example:: 

1563 

1564 @click.group() 

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

1566 def cli(input): 

1567 return 42 

1568 

1569 @cli.result_callback() 

1570 def process_result(result, input): 

1571 return result + input 

1572 

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

1574 callback will be removed. 

1575 

1576 .. versionchanged:: 8.0 

1577 Renamed from ``resultcallback``. 

1578 

1579 .. versionadded:: 3.0 

1580 """ 

1581 

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

1583 old_callback = self._result_callback 

1584 

1585 if old_callback is None or replace: 

1586 self._result_callback = f 

1587 return f 

1588 

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

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

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

1592 

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

1594 return rv 

1595 

1596 return decorator 

1597 

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

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

1600 after the options. 

1601 """ 

1602 commands = [] 

1603 for subcommand in self.list_commands(ctx): 

1604 cmd = self.get_command(ctx, subcommand) 

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

1606 if cmd is None: 

1607 continue 

1608 if cmd.hidden: 1608 ↛ 1609,   1608 ↛ 16112 missed branches: 1) line 1608 didn't jump to line 1609, because the condition on line 1608 was never true, 2) line 1608 didn't jump to line 1611, because the condition on line 1608 was never false

1609 continue 

1610 

1611 commands.append((subcommand, cmd)) 

1612 

1613 # allow for 3 times the default spacing 

1614 if len(commands): 

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

1616 

1617 rows = [] 

1618 for subcommand, cmd in commands: 

1619 help = cmd.get_short_help_str(limit) 

1620 rows.append((subcommand, help)) 

1621 

1622 if rows: 

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

1624 formatter.write_dl(rows) 

1625 

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

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

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

1629 ctx.exit() 

1630 

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

1632 

1633 if self.chain: 

1634 ctx.protected_args = rest 

1635 ctx.args = [] 

1636 elif rest: 

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

1638 

1639 return ctx.args 

1640 

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

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

1643 if self._result_callback is not None: 

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

1645 return value 

1646 

1647 if not ctx.protected_args: 

1648 if self.invoke_without_command: 

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

1650 # invoked with the group return value for regular 

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

1652 with ctx: 

1653 rv = super().invoke(ctx) 

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

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

1656 

1657 # Fetch args back out 

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

1659 ctx.args = [] 

1660 ctx.protected_args = [] 

1661 

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

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

1664 # name of the command to invoke. 

1665 if not self.chain: 

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

1667 # resources until the result processor has worked. 

1668 with ctx: 

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

1670 assert cmd is not None 

1671 ctx.invoked_subcommand = cmd_name 

1672 super().invoke(ctx) 

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

1674 with sub_ctx: 

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

1676 

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

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

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

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

1681 # but nothing else. 

1682 with ctx: 

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

1684 super().invoke(ctx) 

1685 

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

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

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

1689 contexts = [] 

1690 while args: 

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

1692 assert cmd is not None 

1693 sub_ctx = cmd.make_context( 

1694 cmd_name, 

1695 args, 

1696 parent=ctx, 

1697 allow_extra_args=True, 

1698 allow_interspersed_args=False, 

1699 ) 

1700 contexts.append(sub_ctx) 

1701 args, sub_ctx.args = sub_ctx.args, [] 

1702 

1703 rv = [] 

1704 for sub_ctx in contexts: 

1705 with sub_ctx: 

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

1707 return _process_result(rv) 

1708 

1709 def resolve_command( 

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

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

1712 cmd_name = make_str(args[0]) 

1713 original_cmd_name = cmd_name 

1714 

1715 # Get the command 

1716 cmd = self.get_command(ctx, cmd_name) 

1717 

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

1719 # function available, we try with that one. 

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

1721 cmd_name = ctx.token_normalize_func(cmd_name) 

1722 cmd = self.get_command(ctx, cmd_name) 

1723 

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

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

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

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

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

1729 # place. 

1730 if cmd is None and not ctx.resilient_parsing: 1730 ↛ 1731,   1730 ↛ 17342 missed branches: 1) line 1730 didn't jump to line 1731, because the condition on line 1730 was never true, 2) line 1730 didn't jump to line 1734, because the condition on line 1730 was never false

1731 if split_opt(cmd_name)[0]: 

1732 self.parse_args(ctx, ctx.args) 

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

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

1735 

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

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

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

1739 """ 

1740 raise NotImplementedError 

1741 

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

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

1744 appear. 

1745 """ 

1746 return [] 

1747 

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

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

1750 at the names of options, subcommands, and chained 

1751 multi-commands. 

1752 

1753 :param ctx: Invocation context for this command. 

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

1755 

1756 .. versionadded:: 8.0 

1757 """ 

1758 from click.shell_completion import CompletionItem 

1759 

1760 results = [ 

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

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

1763 ] 

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

1765 return results 

1766 

1767 

1768class Group(MultiCommand): 

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

1770 the most common way to implement nesting in Click. 

1771 

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

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

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

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

1776 :param attrs: Other command arguments described in 

1777 :class:`MultiCommand`, :class:`Command`, and 

1778 :class:`BaseCommand`. 

1779 

1780 .. versionchanged:: 8.0 

1781 The ``commmands`` argument can be a list of command objects. 

1782 """ 

1783 

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

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

1786 #: subcommands use a custom command class. 

1787 #: 

1788 #: .. versionadded:: 8.0 

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

1790 

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

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

1793 #: subgroups use a custom group class. 

1794 #: 

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

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

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

1798 #: custom groups. 

1799 #: 

1800 #: .. versionadded:: 8.0 

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

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

1803 

1804 def __init__( 

1805 self, 

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

1807 commands: t.Optional[t.Union[t.Dict[str, Command], t.Sequence[Command]]] = None, 

1808 **attrs: t.Any, 

1809 ) -> None: 

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

1811 

1812 if commands is None: 1812 ↛ 1814line 1812 didn't jump to line 1814, because the condition on line 1812 was never false

1813 commands = {} 

1814 elif isinstance(commands, abc.Sequence): 

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

1816 

1817 #: The registered subcommands by their exported names. 

1818 self.commands: t.Dict[str, Command] = commands 

1819 

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

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

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

1823 """ 

1824 name = name or cmd.name 

1825 if name is None: 

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

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

1828 self.commands[name] = cmd 

1829 

1830 @t.overload 

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

1832 ... 

1833 

1834 @t.overload 

1835 def command( 

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

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

1838 ... 

1839 

1840 def command( 

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

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

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

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

1845 immediately registers the created command with this group by 

1846 calling :meth:`add_command`. 

1847 

1848 To customize the command class used, set the 

1849 :attr:`command_class` attribute. 

1850 

1851 .. versionchanged:: 8.1 

1852 This decorator can be applied without parentheses. 

1853 

1854 .. versionchanged:: 8.0 

1855 Added the :attr:`command_class` attribute. 

1856 """ 

1857 from .decorators import command 

1858 

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

1860 kwargs["cls"] = self.command_class 

1861 

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

1863 

1864 if args and callable(args[0]): 1864 ↛ 1871line 1864 didn't jump to line 1871, because the condition on line 1864 was never false

1865 assert ( 

1866 len(args) == 1 and not kwargs 

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

1868 (func,) = args 

1869 args = () 

1870 

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

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

1873 self.add_command(cmd) 

1874 return cmd 

1875 

1876 if func is not None: 

1877 return decorator(func) 

1878 

1879 return decorator 

1880 

1881 @t.overload 

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

1883 ... 

1884 

1885 @t.overload 

1886 def group( 

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

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

1889 ... 

1890 

1891 def group( 

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

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

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

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

1896 immediately registers the created group with this group by 

1897 calling :meth:`add_command`. 

1898 

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

1900 attribute. 

1901 

1902 .. versionchanged:: 8.1 

1903 This decorator can be applied without parentheses. 

1904 

1905 .. versionchanged:: 8.0 

1906 Added the :attr:`group_class` attribute. 

1907 """ 

1908 from .decorators import group 

1909 

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

1911 

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

1913 assert ( 

1914 len(args) == 1 and not kwargs 

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

1916 (func,) = args 

1917 args = () 

1918 

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

1920 if self.group_class is type: 1920 ↛ 1921,   1920 ↛ 19232 missed branches: 1) line 1920 didn't jump to line 1921, because the condition on line 1920 was never true, 2) line 1920 didn't jump to line 1923, because the condition on line 1920 was never false

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

1922 else: 

1923 kwargs["cls"] = self.group_class 

1924 

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

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

1927 self.add_command(cmd) 

1928 return cmd 

1929 

1930 if func is not None: 

1931 return decorator(func) 

1932 

1933 return decorator 

1934 

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

1936 return self.commands.get(cmd_name) 

1937 

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

1939 return sorted(self.commands) 

1940 

1941 

1942class CommandCollection(MultiCommand): 

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

1944 commands together into one. This is a straightforward implementation 

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

1946 provides all the commands for each of them. 

1947 """ 

1948 

1949 def __init__( 

1950 self, 

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

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

1953 **attrs: t.Any, 

1954 ) -> None: 

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

1956 #: The list of registered multi commands. 

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

1958 

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

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

1961 self.sources.append(multi_cmd) 

1962 

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

1964 for source in self.sources: 

1965 rv = source.get_command(ctx, cmd_name) 

1966 

1967 if rv is not None: 

1968 if self.chain: 

1969 _check_multicommand(self, cmd_name, rv) 

1970 

1971 return rv 

1972 

1973 return None 

1974 

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

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

1977 

1978 for source in self.sources: 

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

1980 

1981 return sorted(rv) 

1982 

1983 

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

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

1986 error, or return an iterator over the value. 

1987 """ 

1988 if isinstance(value, str): 

1989 raise TypeError 

1990 

1991 return iter(value) 

1992 

1993 

1994class Parameter: 

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

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

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

1998 intentionally not finalized. 

1999 

2000 Some settings are supported by both options and arguments. 

2001 

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

2003 argument. This is a list of flags or argument 

2004 names. 

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

2006 or a Python type. The later is converted into the former 

2007 automatically if supported. 

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

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

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

2011 without any arguments. 

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

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

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

2015 including prompts. 

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

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

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

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

2020 parameters are collected. 

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

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

2023 to the command callback and stored on the context, 

2024 otherwise it's skipped. 

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

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

2027 order of processing. 

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

2029 that should be checked. 

2030 :param shell_complete: A function that returns custom shell 

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

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

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

2034 strings. 

2035 

2036 .. versionchanged:: 8.0 

2037 ``process_value`` validates required parameters and bounded 

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

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

2040 ``full_process_value`` is removed. 

2041 

2042 .. versionchanged:: 8.0 

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

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

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

2046 new requirements. 

2047 

2048 .. versionchanged:: 8.0 

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

2050 tuples. 

2051 

2052 .. versionchanged:: 8.0 

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

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

2055 default to ``()``. 

2056 

2057 .. versionchanged:: 7.1 

2058 Empty environment variables are ignored rather than taking the 

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

2060 variables if they can't unset them. 

2061 

2062 .. versionchanged:: 2.0 

2063 Changed signature for parameter callback to also be passed the 

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

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

2066 """ 

2067 

2068 param_type_name = "parameter" 

2069 

2070 def __init__( 

2071 self, 

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

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

2074 required: bool = False, 

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

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

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

2078 multiple: bool = False, 

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

2080 expose_value: bool = True, 

2081 is_eager: bool = False, 

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

2083 shell_complete: t.Optional[ 

2084 t.Callable[ 

2085 [Context, "Parameter", str], 

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

2087 ] 

2088 ] = None, 

2089 ) -> None: 

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

2091 param_decls or (), expose_value 

2092 ) 

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

2094 

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

2096 # information available. 

2097 if nargs is None: 2097 ↛ 2098,   2097 ↛ 21032 missed branches: 1) line 2097 didn't jump to line 2098, because the condition on line 2097 was never true, 2) line 2097 didn't jump to line 2103, because the condition on line 2097 was never false

2098 if self.type.is_composite: 

2099 nargs = self.type.arity 

2100 else: 

2101 nargs = 1 

2102 

2103 self.required = required 

2104 self.callback = callback 

2105 self.nargs = nargs 

2106 self.multiple = multiple 

2107 self.expose_value = expose_value 

2108 self.default = default 

2109 self.is_eager = is_eager 

2110 self.metavar = metavar 

2111 self.envvar = envvar 

2112 self._custom_shell_complete = shell_complete 

2113 

2114 if __debug__: 

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

2116 raise ValueError( 

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

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

2119 ) 

2120 

2121 # Skip no default or callable default. 

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

2123 

2124 if check_default is not None: 

2125 if multiple: 

2126 try: 

2127 # Only check the first value against nargs. 

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

2129 except TypeError: 

2130 raise ValueError( 

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

2132 ) from None 

2133 

2134 # Can be None for multiple with empty default. 

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

2136 try: 

2137 _check_iter(check_default) 

2138 except TypeError: 

2139 if multiple: 

2140 message = ( 

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

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

2143 ) 

2144 else: 

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

2146 

2147 raise ValueError(message) from None 

2148 

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

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

2151 raise ValueError( 

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

2153 ) 

2154 

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

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

2157 user-facing documentation. 

2158 

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

2160 CLI structure. 

2161 

2162 .. versionadded:: 8.0 

2163 """ 

2164 return { 

2165 "name": self.name, 

2166 "param_type_name": self.param_type_name, 

2167 "opts": self.opts, 

2168 "secondary_opts": self.secondary_opts, 

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

2170 "required": self.required, 

2171 "nargs": self.nargs, 

2172 "multiple": self.multiple, 

2173 "default": self.default, 

2174 "envvar": self.envvar, 

2175 } 

2176 

2177 def __repr__(self) -> str: 

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

2179 

2180 def _parse_decls( 

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

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

2183 raise NotImplementedError() 

2184 

2185 @property 

2186 def human_readable_name(self) -> str: 

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

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

2189 """ 

2190 return self.name # type: ignore 

2191 

2192 def make_metavar(self) -> str: 

2193 if self.metavar is not None: 

2194 return self.metavar 

2195 

2196 metavar = self.type.get_metavar(self) 

2197 

2198 if metavar is None: 

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

2200 

2201 if self.nargs != 1: 2201 ↛ 2204line 2201 didn't jump to line 2204, because the condition on line 2201 was never false

2202 metavar += "..." 

2203 

2204 return metavar 

2205 

2206 @t.overload 

2207 def get_default( 

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

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

2210 ... 

2211 

2212 @t.overload 

2213 def get_default( 

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

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

2216 ... 

2217 

2218 def get_default( 

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

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

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

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

2223 

2224 :param ctx: Current context. 

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

2226 return the callable instead. 

2227 

2228 .. versionchanged:: 8.0.2 

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

2230 

2231 .. versionchanged:: 8.0.1 

2232 Type casting can fail in resilient parsing mode. Invalid 

2233 defaults will not prevent showing help text. 

2234 

2235 .. versionchanged:: 8.0 

2236 Looks at ``ctx.default_map`` first. 

2237 

2238 .. versionchanged:: 8.0 

2239 Added the ``call`` parameter. 

2240 """ 

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

2242 

2243 if value is None: 

2244 value = self.default 

2245 

2246 if call and callable(value): 

2247 value = value() 

2248 

2249 return value 

2250 

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

2252 raise NotImplementedError() 

2253 

2254 def consume_value( 

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

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

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

2258 source = ParameterSource.COMMANDLINE 

2259 

2260 if value is None: 

2261 value = self.value_from_envvar(ctx) 

2262 source = ParameterSource.ENVIRONMENT 

2263 

2264 if value is None: 

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

2266 source = ParameterSource.DEFAULT_MAP 

2267 

2268 if value is None: 

2269 value = self.get_default(ctx) 

2270 source = ParameterSource.DEFAULT 

2271 

2272 return value, source 

2273 

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

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

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

2277 """ 

2278 if value is None: 

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

2280 

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

2282 try: 

2283 return _check_iter(value) 

2284 except TypeError: 

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

2286 # the parser should construct an iterable when parsing 

2287 # the command line. 

2288 raise BadParameter( 

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

2290 ) from None 

2291 

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

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

2294 self.type, param=self, ctx=ctx 

2295 ) 

2296 elif self.nargs == -1: 

2297 

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

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

2300 

2301 else: # nargs > 1 

2302 

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

2304 value = tuple(check_iter(value)) 

2305 

2306 if len(value) != self.nargs: 2306 ↛ 2317line 2306 didn't jump to line 2317, because the condition on line 2306 was never false

2307 raise BadParameter( 

2308 ngettext( 

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

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

2311 len(value), 

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

2313 ctx=ctx, 

2314 param=self, 

2315 ) 

2316 

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

2318 

2319 if self.multiple: 

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

2321 

2322 return convert(value) 

2323 

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

2325 if value is None: 

2326 return True 

2327 

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

2329 return True 

2330 

2331 return False 

2332 

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

2334 value = self.type_cast_value(ctx, value) 

2335 

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

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

2338 

2339 if self.callback is not None: 

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

2341 

2342 return value 

2343 

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

2345 if self.envvar is None: 

2346 return None 

2347 

2348 if isinstance(self.envvar, str): 

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

2350 

2351 if rv: 

2352 return rv 

2353 else: 

2354 for envvar in self.envvar: 2354 ↛ 2355,   2354 ↛ 23602 missed branches: 1) line 2354 didn't jump to line 2355, because the loop on line 2354 never started, 2) line 2354 didn't jump to line 2360, because the loop on line 2354 didn't complete

2355 rv = os.environ.get(envvar) 

2356 

2357 if rv: 

2358 return rv 

2359 

2360 return None 

2361 

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

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

2364 

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

2366 rv = self.type.split_envvar_value(rv) 

2367 

2368 return rv 

2369 

2370 def handle_parse_result( 

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

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

2373 with augment_usage_errors(ctx, param=self): 

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

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

2376 

2377 try: 

2378 value = self.process_value(ctx, value) 

2379 except Exception: 

2380 if not ctx.resilient_parsing: 

2381 raise 

2382 

2383 value = None 

2384 

2385 if self.expose_value: 2385 ↛ 2386,   2385 ↛ 23882 missed branches: 1) line 2385 didn't jump to line 2386, because the condition on line 2385 was never true, 2) line 2385 didn't jump to line 2388, because the condition on line 2385 was never false

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

2387 

2388 return value, args 

2389 

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

2391 pass 

2392 

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

2394 return [] 

2395 

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

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

2398 indicate which param caused the error. 

2399 """ 

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

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

2402 

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

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

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

2406 Otherwise, the :attr:`type` 

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

2408 

2409 :param ctx: Invocation context for this command. 

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

2411 

2412 .. versionadded:: 8.0 

2413 """ 

2414 if self._custom_shell_complete is not None: 

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

2416 

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

2418 from click.shell_completion import CompletionItem 

2419 

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

2421 

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

2423 

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

2425 

2426 

2427class Option(Parameter): 

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

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

2430 

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

2432 

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

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

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

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

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

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

2439 its value is ``False``. 

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

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

2442 shown. 

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

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

2445 will be the option name capitalized. 

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

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

2448 ``True`` to customize the message. 

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

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

2451 without a value. 

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

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

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

2455 auto detection. 

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

2457 enabled. This is set to a boolean automatically if 

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

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

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

2461 in how it works but supports arbitrary number of 

2462 arguments. 

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

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

2465 parameter will be pulled from an environment 

2466 variable in case a prefix is defined on the 

2467 context. 

2468 :param help: the help string. 

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

2470 

2471 .. versionchanged:: 8.1.0 

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

2473 ``@option`` decorator. 

2474 

2475 .. versionchanged:: 8.1.0 

2476 The ``show_default`` parameter overrides 

2477 ``Context.show_default``. 

2478 

2479 .. versionchanged:: 8.1.0 

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

2481 default value is ``False``. 

2482 

2483 .. versionchanged:: 8.0.1 

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

2485 """ 

2486 

2487 param_type_name = "option" 

2488 

2489 def __init__( 

2490 self, 

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

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

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

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

2495 prompt_required: bool = True, 

2496 hide_input: bool = False, 

2497 is_flag: t.Optional[bool] = None, 

2498 flag_value: t.Optional[t.Any] = None, 

2499 multiple: bool = False, 

2500 count: bool = False, 

2501 allow_from_autoenv: bool = True, 

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

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

2504 hidden: bool = False, 

2505 show_choices: bool = True, 

2506 show_envvar: bool = False, 

2507 **attrs: t.Any, 

2508 ) -> None: 

2509 if help: 2509 ↛ 2512line 2509 didn't jump to line 2512, because the condition on line 2509 was never false

2510 help = inspect.cleandoc(help) 

2511 

2512 default_is_missing = "default" not in attrs 

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

2514 

2515 if prompt is True: 2515 ↛ 2516,   2515 ↛ 25202 missed branches: 1) line 2515 didn't jump to line 2516, because the condition on line 2515 was never true, 2) line 2515 didn't jump to line 2520, because the condition on line 2515 was never false

2516 if self.name is None: 

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

2518 

2519 prompt_text: t.Optional[str] = self.name.replace("_", " ").capitalize() 

2520 elif prompt is False: 2520 ↛ 2521,   2520 ↛ 25232 missed branches: 1) line 2520 didn't jump to line 2521, because the condition on line 2520 was never true, 2) line 2520 didn't jump to line 2523, because the condition on line 2520 was never false

2521 prompt_text = None 

2522 else: 

2523 prompt_text = prompt 

2524 

2525 self.prompt = prompt_text 

2526 self.confirmation_prompt = confirmation_prompt 

2527 self.prompt_required = prompt_required 

2528 self.hide_input = hide_input 

2529 self.hidden = hidden 

2530 

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

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

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

2534 

2535 if is_flag is None: 2535 ↛ 2545line 2535 didn't jump to line 2545, because the condition on line 2535 was never false

2536 if flag_value is not None: 2536 ↛ 2539line 2536 didn't jump to line 2539, because the condition on line 2536 was never false

2537 # Implicitly a flag because flag_value was set. 

2538 is_flag = True 

2539 elif self._flag_needs_value: 

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

2541 is_flag = False 

2542 else: 

2543 # Implicitly a flag because flag options were given. 

2544 is_flag = bool(self.secondary_opts) 

2545 elif is_flag is False and not self._flag_needs_value: 2545 ↛ 2550line 2545 didn't jump to line 2550, because the condition on line 2545 was never false

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

2547 # flag if flag_value is set. 

2548 self._flag_needs_value = flag_value is not None 

2549 

2550 if is_flag and default_is_missing and not self.required: 

2551 self.default: t.Union[t.Any, t.Callable[[], t.Any]] = False 

2552 

2553 if flag_value is None: 

2554 flag_value = not self.default 

2555 

2556 if is_flag and type is None: 2556 ↛ 2559,   2556 ↛ 25612 missed branches: 1) line 2556 didn't jump to line 2559, because the condition on line 2556 was never true, 2) line 2556 didn't jump to line 2561, because the condition on line 2556 was never false

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

2558 # default. 

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

2560 

2561 self.is_flag: bool = is_flag 

2562 self.is_bool_flag = is_flag and isinstance(self.type, types.BoolParamType) 

2563 self.flag_value: t.Any = flag_value 

2564 

2565 # Counting 

2566 self.count = count 

2567 if count: 

2568 if type is None: 2568 ↛ 2569,   2568 ↛ 25702 missed branches: 1) line 2568 didn't jump to line 2569, because the condition on line 2568 was never true, 2) line 2568 didn't jump to line 2570, because the condition on line 2568 was never false

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

2570 if default_is_missing: 

2571 self.default = 0 

2572 

2573 self.allow_from_autoenv = allow_from_autoenv 

2574 self.help = help 

2575 self.show_default = show_default 

2576 self.show_choices = show_choices 

2577 self.show_envvar = show_envvar 

2578 

2579 if __debug__: 

2580 if self.nargs == -1: 

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

2582 

2583 if self.prompt and self.is_flag and not self.is_bool_flag: 2583 ↛ 2584,   2583 ↛ 25862 missed branches: 1) line 2583 didn't jump to line 2584, because the condition on line 2583 was never true, 2) line 2583 didn't jump to line 2586, because the condition on line 2583 was never false

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

2585 

2586 if not self.is_bool_flag and self.secondary_opts: 2586 ↛ 2587,   2586 ↛ 25892 missed branches: 1) line 2586 didn't jump to line 2587, because the condition on line 2586 was never true, 2) line 2586 didn't jump to line 2589, because the condition on line 2586 was never false

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

2588 

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

2590 raise TypeError( 

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

2592 ) 

2593 

2594 if self.count: 

2595 if self.multiple: 

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

2597 

2598 if self.is_flag: 

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

2600 

2601 if self.multiple and self.is_flag: 2601 ↛ exitline 2601 didn't return from function '__init__', because the condition on line 2601 was never false

2602 raise TypeError("'multiple' is not valid with 'is_flag', use 'count'.") 

2603 

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

2605 info_dict = super().to_info_dict() 

2606 info_dict.update( 

2607 help=self.help, 

2608 prompt=self.prompt, 

2609 is_flag=self.is_flag, 

2610 flag_value=self.flag_value, 

2611 count=self.count, 

2612 hidden=self.hidden, 

2613 ) 

2614 return info_dict 

2615 

2616 def _parse_decls( 

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

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

2619 opts = [] 

2620 secondary_opts = [] 

2621 name = None 

2622 possible_names = [] 

2623 

2624 for decl in decls: 

2625 if decl.isidentifier(): 

2626 if name is not None: 

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

2628 name = decl 

2629 else: 

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

2631 if split_char in decl: 2631 ↛ 2646line 2631 didn't jump to line 2646, because the condition on line 2631 was never false

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

2633 first = first.rstrip() 

2634 if first: 2634 ↛ 2635line 2634 didn't jump to line 2635, because the condition on line 2634 was never true

2635 possible_names.append(split_opt(first)) 

2636 opts.append(first) 

2637 second = second.lstrip() 

2638 if second: 

2639 secondary_opts.append(second.lstrip()) 

2640 if first == second: 

2641 raise ValueError( 

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

2643 " same flag for true/false." 

2644 ) 

2645 else: 

2646 possible_names.append(split_opt(decl)) 

2647 opts.append(decl) 

2648 

2649 if name is None and possible_names: 2649 ↛ 2650,   2649 ↛ 26552 missed branches: 1) line 2649 didn't jump to line 2650, because the condition on line 2649 was never true, 2) line 2649 didn't jump to line 2655, because the condition on line 2649 was never false

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

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

2652 if not name.isidentifier(): 

2653 name = None 

2654 

2655 if name is None: 

2656 if not expose_value: 

2657 return None, opts, secondary_opts 

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

2659 

2660 if not opts and not secondary_opts: 

2661 raise TypeError( 

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

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

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

2665 ) 

2666 

2667 return name, opts, secondary_opts 

2668 

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

2670 if self.multiple: 

2671 action = "append" 

2672 elif self.count: 

2673 action = "count" 

2674 else: 

2675 action = "store" 

2676 

2677 if self.is_flag: 

2678 action = f"{action}_const" 

2679 

2680 if self.is_bool_flag and self.secondary_opts: 

2681 parser.add_option( 

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

2683 ) 

2684 parser.add_option( 

2685 obj=self, 

2686 opts=self.secondary_opts, 

2687 dest=self.name, 

2688 action=action, 

2689 const=False, 

2690 ) 

2691 else: 

2692 parser.add_option( 

2693 obj=self, 

2694 opts=self.opts, 

2695 dest=self.name, 

2696 action=action, 

2697 const=self.flag_value, 

2698 ) 

2699 else: 

2700 parser.add_option( 

2701 obj=self, 

2702 opts=self.opts, 

2703 dest=self.name, 

2704 action=action, 

2705 nargs=self.nargs, 

2706 ) 

2707 

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

2709 if self.hidden: 

2710 return None 

2711 

2712 any_prefix_is_slash = False 

2713 

2714 def _write_opts(opts: t.Sequence[str]) -> str: 

2715 nonlocal any_prefix_is_slash 

2716 

2717 rv, any_slashes = join_options(opts) 

2718 

2719 if any_slashes: 

2720 any_prefix_is_slash = True 

2721 

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

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

2724 

2725 return rv 

2726 

2727 rv = [_write_opts(self.opts)] 

2728 

2729 if self.secondary_opts: 

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

2731 

2732 help = self.help or "" 

2733 extra = [] 

2734 

2735 if self.show_envvar: 

2736 envvar = self.envvar 

2737 

2738 if envvar is None: 

2739 if ( 

2740 self.allow_from_autoenv 

2741 and ctx.auto_envvar_prefix is not None 

2742 and self.name is not None 

2743 ): 

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

2745 

2746 if envvar is not None: 

2747 var_str = ( 

2748 envvar 

2749 if isinstance(envvar, str) 

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

2751 ) 

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

2753 

2754 # Temporarily enable resilient parsing to avoid type casting 

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

2756 # help formatting in general. 

2757 resilient = ctx.resilient_parsing 

2758 ctx.resilient_parsing = True 

2759 

2760 try: 

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

2762 finally: 

2763 ctx.resilient_parsing = resilient 

2764 

2765 show_default = False 

2766 show_default_is_str = False 

2767 

2768 if self.show_default is not None: 

2769 if isinstance(self.show_default, str): 

2770 show_default_is_str = show_default = True 

2771 else: 

2772 show_default = self.show_default 

2773 elif ctx.show_default is not None: 

2774 show_default = ctx.show_default 

2775 

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

2777 if show_default_is_str: 

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

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

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

2781 elif inspect.isfunction(default_value): 

2782 default_string = _("(dynamic)") 

2783 elif self.is_bool_flag and self.secondary_opts: 

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

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

2786 default_string = split_opt( 

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

2788 )[1] 

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

2790 default_string = "" 

2791 else: 

2792 default_string = str(default_value) 

2793 

2794 if default_string: 

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

2796 

2797 if ( 2797 ↛ 2802,   2797 ↛ 28072 missed branches: 1) line 2797 didn't jump to line 2802, 2) line 2797 didn't jump to line 2807

2798 isinstance(self.type, types._NumberRangeBase) 

2799 # skip count with default range type 

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

2801 ): 

2802 range_str = self.type._describe_range() 

2803 

2804 if range_str: 2804 ↛ 2805,   2804 ↛ 28072 missed branches: 1) line 2804 didn't jump to line 2805, because the condition on line 2804 was never true, 2) line 2804 didn't jump to line 2807, because the condition on line 2804 was never false

2805 extra.append(range_str) 

2806 

2807 if self.required: 2807 ↛ 2808,   2807 ↛ 28102 missed branches: 1) line 2807 didn't jump to line 2808, because the condition on line 2807 was never true, 2) line 2807 didn't jump to line 2810, because the condition on line 2807 was never false

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

2809 

2810 if extra: 

2811 extra_str = "; ".join(extra) 

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

2813 

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

2815 

2816 @t.overload 

2817 def get_default( 

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

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

2820 ... 

2821 

2822 @t.overload 

2823 def get_default( 

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

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

2826 ... 

2827 

2828 def get_default( 

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

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

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

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

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

2834 # value as default. 

2835 if self.is_flag and not self.is_bool_flag: 

2836 for param in ctx.command.params: 

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

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

2839 

2840 return None 

2841 

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

2843 

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

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

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

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

2848 value as result. 

2849 """ 

2850 assert self.prompt is not None 

2851 

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

2853 default = self.get_default(ctx) 

2854 

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

2856 # differently. 

2857 if self.is_bool_flag: 

2858 return confirm(self.prompt, default) 

2859 

2860 return prompt( 

2861 self.prompt, 

2862 default=default, 

2863 type=self.type, 

2864 hide_input=self.hide_input, 

2865 show_choices=self.show_choices, 

2866 confirmation_prompt=self.confirmation_prompt, 

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

2868 ) 

2869 

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

2871 rv = super().resolve_envvar_value(ctx) 

2872 

2873 if rv is not None: 

2874 return rv 

2875 

2876 if ( 

2877 self.allow_from_autoenv 

2878 and ctx.auto_envvar_prefix is not None 

2879 and self.name is not None 

2880 ): 

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

2882 rv = os.environ.get(envvar) 

2883 

2884 if rv: 

2885 return rv 

2886 

2887 return None 

2888 

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

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

2891 

2892 if rv is None: 

2893 return None 

2894 

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

2896 

2897 if value_depth > 0: 

2898 rv = self.type.split_envvar_value(rv) 

2899 

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

2901 rv = batch(rv, self.nargs) 

2902 

2903 return rv 

2904 

2905 def consume_value( 

2906 self, ctx: Context, opts: t.Mapping[str, "Parameter"] 

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

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

2909 

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

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

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

2913 if value is _flag_needs_value: 

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

2915 value = self.prompt_for_value(ctx) 

2916 source = ParameterSource.PROMPT 

2917 else: 

2918 value = self.flag_value 

2919 source = ParameterSource.COMMANDLINE 

2920 

2921 elif ( 2921 ↛ exit,   2921 ↛ 29262 missed branches: 1) line 2921 didn't jump to the function exit, 2) line 2921 didn't jump to line 2926

2922 self.multiple 

2923 and value is not None 

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

2925 ): 

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

2927 source = ParameterSource.COMMANDLINE 

2928 

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

2930 # prompting is enabled. 

2931 elif ( 2931 ↛ 2937,   2931 ↛ 29402 missed branches: 1) line 2931 didn't jump to line 2937, 2) line 2931 didn't jump to line 2940

2932 source in {None, ParameterSource.DEFAULT} 

2933 and self.prompt is not None 

2934 and (self.required or self.prompt_required) 

2935 and not ctx.resilient_parsing 

2936 ): 

2937 value = self.prompt_for_value(ctx) 

2938 source = ParameterSource.PROMPT 

2939 

2940 return value, source 

2941 

2942 

2943class Argument(Parameter): 

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

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

2946 and are required by default. 

2947 

2948 All parameters are passed onwards to the parameter constructor. 

2949 """ 

2950 

2951 param_type_name = "argument" 

2952 

2953 def __init__( 

2954 self, 

2955 param_decls: t.Sequence[str], 

2956 required: t.Optional[bool] = None, 

2957 **attrs: t.Any, 

2958 ) -> None: 

2959 if required is None: 

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

2961 required = False 

2962 else: 

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

2964 

2965 if "multiple" in attrs: 

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

2967 

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

2969 

2970 if __debug__: 

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

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

2973 

2974 @property 

2975 def human_readable_name(self) -> str: 

2976 if self.metavar is not None: 2976 ↛ 2977,   2976 ↛ 29782 missed branches: 1) line 2976 didn't jump to line 2977, because the condition on line 2976 was never true, 2) line 2976 didn't jump to line 2978, because the condition on line 2976 was never false

2977 return self.metavar 

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

2979 

2980 def make_metavar(self) -> str: 

2981 if self.metavar is not None: 2981 ↛ 2983line 2981 didn't jump to line 2983, because the condition on line 2981 was never false

2982 return self.metavar 

2983 var = self.type.get_metavar(self) 

2984 if not var: 

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

2986 if not self.required: 

2987 var = f"[{var}]" 

2988 if self.nargs != 1: 

2989 var += "..." 

2990 return var 

2991 

2992 def _parse_decls( 

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

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

2995 if not decls: 

2996 if not expose_value: 

2997 return None, [], [] 

2998 raise TypeError("Could not determine name for argument") 

2999 if len(decls) == 1: 

3000 name = arg = decls[0] 

3001 name = name.replace("-", "_").lower() 

3002 else: 

3003 raise TypeError( 

3004 "Arguments take exactly one parameter declaration, got" 

3005 f" {len(decls)}." 

3006 ) 

3007 return name, [arg], [] 

3008 

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

3010 return [self.make_metavar()] 

3011 

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

3013 return f"'{self.make_metavar()}'" 

3014 

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

3016 parser.add_argument(dest=self.name, nargs=self.nargs, obj=self)