Coverage for typer / _click / core.py: 100%

432 statements  

« prev     ^ index     » next       coverage.py v7.13.1, created at 2026-11-18 11:12 +0000

1import enum 1adefbghcij

2import inspect 1adefbghcij

3import os 1adefbghcij

4from abc import ABC, abstractmethod 1adefbghcij

5from collections.abc import ( 1adefbghcij

6 Callable, 

7 Generator, 

8 Iterator, 

9 Mapping, 

10 MutableMapping, 

11 Sequence, 

12) 

13from contextlib import AbstractContextManager, ExitStack, contextmanager 1adefbghcij

14from types import TracebackType 1adefbghcij

15from typing import ( 1adefbghcij

16 TYPE_CHECKING, 

17 Any, 

18 ClassVar, 

19 Literal, 

20 NoReturn, 

21 TypeVar, 

22 Union, 

23 cast, 

24 overload, 

25) 

26 

27from ..exceptions import Abort, Exit 1adefbghcij

28from .exceptions import BadParameter, NoArgsIsHelpError, UsageError 1adefbghcij

29from .formatting import HelpFormatter 1adefbghcij

30from .globals import pop_context, push_context 1adefbghcij

31from .parser import _OptionParser 1adefbghcij

32from .termui import style 1adefbghcij

33from .utils import _escape_control_characters, echo, make_default_short_help 1adefbghcij

34 

35if TYPE_CHECKING: 1adefbghcij

36 from ..core import TyperOption, _TyperParameter 

37 from .shell_completion import CompletionItem 

38 

39F = TypeVar("F", bound="Callable[..., Any]") 1adefbghcij

40V = TypeVar("V") 1adefbghcij

41 

42 

43def _complete_visible_commands( 1adefbghcij

44 ctx: "Context", incomplete: str 

45) -> Iterator[tuple[str, "Command"]]: 

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

47 incomplete value and aren't hidden. 

48 """ 

49 # avoid circular imports 

50 from ..core import TyperGroup 1adefbghcij

51 

52 multi = cast(TyperGroup, ctx.command) 1adefbghcij

53 

54 for name in multi.list_commands(ctx): 1adefbghcij

55 if name.startswith(incomplete): 1adefbghcij

56 command = multi.get_command(ctx, name) 1adefbghcij

57 

58 if command is not None and not command.hidden: 1adefbghcij

59 yield name, command 1adefbghcij

60 

61 

62@contextmanager 1adefbghcij

63def augment_usage_errors( 1adefbghcij

64 ctx: "Context", param: Union["_TyperParameter", None] = None 

65) -> Generator[None]: 

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

67 try: 1adefbghcij

68 yield 1adefbghcij

69 except BadParameter as e: 1adefbghcij

70 if e.ctx is None: 1adefbghcij

71 e.ctx = ctx 1adefbghcij

72 if param is not None and e.param is None: 1adefbghcij

73 e.param = param 1adefbghcij

74 raise 1adefbghcij

75 except UsageError as e: # pragma: no cover 1adefbghcij

76 if e.ctx is None: 

77 e.ctx = ctx 

78 raise 

79 

80 

81def iter_params_for_processing( 1adefbghcij

82 invocation_order: Sequence["Parameter"], 

83 declaration_order: Sequence["Parameter"], 

84) -> list["Parameter"]: 

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

86 

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

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

89 

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

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

92 

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

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

95 """ 

96 

97 def sort_key(item: Parameter) -> tuple[bool, float]: 1adefbghcij

98 try: 1adefbghcij

99 idx: float = invocation_order.index(item) 1adefbghcij

100 except ValueError: 1adefbghcij

101 idx = float("inf") 1adefbghcij

102 

103 return not item.is_eager, idx 1adefbghcij

104 

105 return sorted(declaration_order, key=sort_key) 1adefbghcij

106 

107 

108class ParameterSource(enum.Enum): 1adefbghcij

109 """This is an `Enum` that indicates the source of a 

110 parameter's value. 

111 """ 

112 

113 COMMANDLINE = enum.auto() 1adefbghcij

114 """The value was provided by the command line args.""" 1adefbghcij

115 ENVIRONMENT = enum.auto() 1adefbghcij

116 """The value was provided with an environment variable.""" 1adefbghcij

117 DEFAULT = enum.auto() 1adefbghcij

118 """Used the default specified by the parameter.""" 1adefbghcij

119 DEFAULT_MAP = enum.auto() 1adefbghcij

120 """Used a default provided by `Context.default_map`.""" 1adefbghcij

121 PROMPT = enum.auto() 1adefbghcij

122 """Used a prompt to confirm a default or provide a value.""" 1adefbghcij

123 

124 

125class Context: 1adefbghcij

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

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

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

129 

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

131 control special execution features such as reading data from 

132 environment variables. 

133 

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

135 `close` on teardown. 

136 """ 

137 

138 formatter_class: type[HelpFormatter] = HelpFormatter 1adefbghcij

139 

140 def __init__( 1adefbghcij

141 self, 

142 command: "Command", 

143 parent: Union["Context", None] = None, 

144 info_name: str | None = None, 

145 obj: Any | None = None, 

146 auto_envvar_prefix: str | None = None, 

147 default_map: MutableMapping[str, Any] | None = None, 

148 terminal_width: int | None = None, 

149 max_content_width: int | None = None, 

150 resilient_parsing: bool = False, 

151 allow_extra_args: bool | None = None, 

152 allow_interspersed_args: bool | None = None, 

153 ignore_unknown_options: bool | None = None, 

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

155 token_normalize_func: Callable[[str], str] | None = None, 

156 color: bool | None = None, 

157 show_default: bool | None = None, 

158 ) -> None: 

159 self.parent = parent 1adefbghcij

160 self.command = command 1adefbghcij

161 self.info_name = info_name 1adefbghcij

162 # Map of parameter names to their parsed values. 

163 self.params: dict[str, Any] = {} 1adefbghcij

164 # the leftover arguments. 

165 self.args: list[str] = [] 1adefbghcij

166 # protected arguments. used to implement nested parsing. 

167 self._protected_args: list[str] = [] 1adefbghcij

168 # the collected prefixes of the command's options. 

169 self._opt_prefixes: set[str] = set(parent._opt_prefixes) if parent else set() 1adefbghcij

170 

171 if obj is None and parent is not None: 1adefbghcij

172 obj = parent.obj 1adefbghcij

173 

174 self.obj: Any = obj 1adefbghcij

175 self._meta: dict[str, Any] = getattr(parent, "meta", {}) 1adefbghcij

176 

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

178 if ( 

179 default_map is None 

180 and info_name is not None 

181 and parent is not None 

182 and parent.default_map is not None 

183 ): 

184 default_map = parent.default_map.get(info_name) 1adefbghcij

185 

186 self.default_map: MutableMapping[str, Any] | None = default_map 1adefbghcij

187 

188 # This flag indicates if a subcommand is going to be executed. 

189 self.invoked_subcommand: str | None = None 1adefbghcij

190 

191 if terminal_width is None and parent is not None: 1adefbghcij

192 terminal_width = parent.terminal_width 1adefbghcij

193 

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

195 self.terminal_width: int | None = terminal_width 1adefbghcij

196 

197 if max_content_width is None and parent is not None: 1adefbghcij

198 max_content_width = parent.max_content_width 1adefbghcij

199 

200 self.max_content_width: int | None = max_content_width 1adefbghcij

201 

202 if allow_extra_args is None: 1adefbghcij

203 allow_extra_args = command.allow_extra_args 1adefbghcij

204 

205 self.allow_extra_args = allow_extra_args 1adefbghcij

206 

207 if allow_interspersed_args is None: 1adefbghcij

208 allow_interspersed_args = command.allow_interspersed_args 1adefbghcij

209 

210 self.allow_interspersed_args: bool = allow_interspersed_args 1adefbghcij

211 

212 if ignore_unknown_options is None: 1adefbghcij

213 ignore_unknown_options = command.ignore_unknown_options 1adefbghcij

214 

215 self.ignore_unknown_options: bool = ignore_unknown_options 1adefbghcij

216 

217 if help_option_names is None: 1adefbghcij

218 if parent is not None: 1adefbghcij

219 help_option_names = parent.help_option_names 1adefbghcij

220 else: 

221 help_option_names = ["--help"] 1adefbghcij

222 

223 self.help_option_names: list[str] = help_option_names 1adefbghcij

224 

225 if token_normalize_func is None and parent is not None: 1adefbghcij

226 token_normalize_func = parent.token_normalize_func 1adefbghcij

227 

228 # An optional normalization function for tokens. (options, choices, commands etc.) 

229 self.token_normalize_func: Callable[[str], str] | None = token_normalize_func 1adefbghcij

230 

231 # Indicates if resilient parsing is enabled. 

232 self.resilient_parsing: bool = resilient_parsing 1adefbghcij

233 

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

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

236 # prefix automatically. 

237 if auto_envvar_prefix is None: 1adefbghcij

238 if ( 

239 parent is not None 

240 and parent.auto_envvar_prefix is not None 

241 and self.info_name is not None 

242 ): 

243 auto_envvar_prefix = ( 1adefbghcij

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

245 ) 

246 else: 

247 auto_envvar_prefix = auto_envvar_prefix.upper() 1adefbghcij

248 

249 if auto_envvar_prefix is not None: 1adefbghcij

250 auto_envvar_prefix = auto_envvar_prefix.replace("-", "_") 1adefbghcij

251 

252 self.auto_envvar_prefix: str | None = auto_envvar_prefix 1adefbghcij

253 

254 if color is None and parent is not None: 1adefbghcij

255 color = parent.color 1adefbghcij

256 

257 # Controls if styling output is wanted or not. 

258 self.color: bool | None = color 1adefbghcij

259 

260 if show_default is None and parent is not None: 1adefbghcij

261 show_default = parent.show_default 1adefbghcij

262 

263 # Show option default values when formatting help text. 

264 self.show_default: bool | None = show_default 1adefbghcij

265 

266 self._close_callbacks: list[Callable[[], Any]] = [] 1adefbghcij

267 self._depth = 0 1adefbghcij

268 self._parameter_source: dict[str, ParameterSource] = {} 1adefbghcij

269 self._exit_stack = ExitStack() 1adefbghcij

270 

271 def __enter__(self) -> "Context": 1adefbghcij

272 self._depth += 1 1adefbghcij

273 push_context(self) 1adefbghcij

274 return self 1adefbghcij

275 

276 def __exit__( 1adefbghcij

277 self, 

278 exc_type: type[BaseException] | None, 

279 exc_value: BaseException | None, 

280 tb: TracebackType | None, 

281 ) -> bool | None: 

282 self._depth -= 1 1adefbghcij

283 exit_result: bool | None = None 1adefbghcij

284 if self._depth == 0: 1adefbghcij

285 exit_result = self._close_with_exception_info(exc_type, exc_value, tb) 1adefbghcij

286 pop_context() 1adefbghcij

287 

288 return exit_result 1adefbghcij

289 

290 @contextmanager 1adefbghcij

291 def scope(self, cleanup: bool = True) -> Generator["Context"]: 1adefbghcij

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

293 it to the current thread local (see `get_current_context`). 

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

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

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

297 

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

299 used as a context manager. 

300 """ 

301 if not cleanup: 1adefbghcij

302 self._depth += 1 1adefbghcij

303 try: 1adefbghcij

304 with self as rv: 1adefbghcij

305 yield rv 1adefbghcij

306 finally: 

307 if not cleanup: 1adefbghcij

308 self._depth -= 1 1adefbghcij

309 

310 @property 1adefbghcij

311 def meta(self) -> dict[str, Any]: 1adefbghcij

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

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

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

315 that code to manage this dictionary well. 

316 

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

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

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

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

321 the system. 

322 """ 

323 return self._meta 1adefbghcij

324 

325 def make_formatter(self) -> HelpFormatter: 1adefbghcij

326 """Creates the HelpFormatter for the help and 

327 usage output. 

328 """ 

329 return self.formatter_class( 1adefbghcij

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

331 ) 

332 

333 def with_resource(self, context_manager: AbstractContextManager[V]) -> V: 1adefbghcij

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

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

336 popped. 

337 

338 Uses `contextlib.ExitStack.enter_context`. It calls the 

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

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

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

342 

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

344 context manager, use `call_on_close`. Or use something 

345 from `contextlib` to turn it into a context manager first. 

346 """ 

347 return self._exit_stack.enter_context(context_manager) 1adefbghcij

348 

349 def call_on_close(self, f: Callable[..., Any]) -> Callable[..., Any]: 1adefbghcij

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

351 

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

353 execution. Resources that support Python's context manager 

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

355 registered with `with_resource` instead. 

356 """ 

357 return self._exit_stack.callback(f) 1adefbghcij

358 

359 def close(self) -> None: 1adefbghcij

360 """Invoke all close callbacks registered with `call_on_close`, 

361 and exit all context managers entered with `with_resource`. 

362 """ 

363 self._close_with_exception_info(None, None, None) 1adefbghcij

364 

365 def _close_with_exception_info( 1adefbghcij

366 self, 

367 exc_type: type[BaseException] | None, 

368 exc_value: BaseException | None, 

369 tb: TracebackType | None, 

370 ) -> bool | None: 

371 """Unwind the exit stack by calling its `__exit__` providing the exception 

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

373 using `with_resource` 

374 """ 

375 exit_result = self._exit_stack.__exit__(exc_type, exc_value, tb) 1adefbghcij

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

377 self._exit_stack = ExitStack() 1adefbghcij

378 

379 return exit_result 1adefbghcij

380 

381 @property 1adefbghcij

382 def command_path(self) -> str: 1adefbghcij

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

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

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

386 """ 

387 rv = "" 1adefbghcij

388 if self.info_name is not None: 1adefbghcij

389 rv = self.info_name 1adefbghcij

390 if self.parent is not None: 1adefbghcij

391 parent_command_path = [self.parent.command_path] 1adefbghcij

392 

393 if isinstance(self.parent.command, Command): 1adefbghcij

394 for param in self.parent.command.get_params(self): 1adefbghcij

395 parent_command_path.extend(param.get_usage_pieces(self)) 1adefbghcij

396 

397 rv = f"{' '.join(parent_command_path)} {rv}" 1adefbghcij

398 return rv.lstrip() 1adefbghcij

399 

400 def find_root(self) -> "Context": 1adefbghcij

401 """Finds the outermost context.""" 

402 node = self 1adefbghcij

403 while node.parent is not None: 1adefbghcij

404 node = node.parent 1adefbghcij

405 return node 1adefbghcij

406 

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

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

409 node: Context | None = self 1adefbghcij

410 

411 while node is not None: 1adefbghcij

412 if isinstance(node.obj, object_type): 1adefbghcij

413 return node.obj 1adefbghcij

414 

415 node = node.parent 1adefbghcij

416 

417 return None 1adefbghcij

418 

419 def ensure_object(self, object_type: type[V]) -> V: 1adefbghcij

420 """Like `find_object` but sets the innermost object to a 

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

422 """ 

423 rv = self.find_object(object_type) 1adefbghcij

424 if rv is None: 1adefbghcij

425 self.obj = rv = object_type() 1adefbghcij

426 return rv 1adefbghcij

427 

428 @overload 1adefbghcij

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

430 

431 @overload 1adefbghcij

432 def lookup_default( 1adefbghcij

433 self, name: str, call: Literal[False] = ... 1abc

434 ) -> Any | Callable[[], Any] | None: ... 1abc

435 

436 def lookup_default(self, name: str, call: bool = True) -> Any | None: 1adefbghcij

437 """Get the default for a parameter from `default_map`.""" 

438 if self.default_map is not None: 1adefbghcij

439 value = self.default_map.get(name) 1adefbghcij

440 

441 if call and callable(value): 1adefbghcij

442 return value() 1adefbghcij

443 

444 return value 1adefbghcij

445 

446 return None 1adefbghcij

447 

448 def fail(self, message: str) -> NoReturn: 1adefbghcij

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

450 message. 

451 """ 

452 raise UsageError(message, self) 1adefbghcij

453 

454 def abort(self) -> NoReturn: 1adefbghcij

455 """Aborts the script.""" 

456 raise Abort() 1adefbghcij

457 

458 def exit(self, code: int = 0) -> NoReturn: 1adefbghcij

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

460 self.close() 1adefbghcij

461 raise Exit(code) 1adefbghcij

462 

463 def get_usage(self) -> str: 1adefbghcij

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

465 context and command. 

466 """ 

467 return self.command.get_usage(self) 1adefbghcij

468 

469 def get_help(self) -> str: 1adefbghcij

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

471 context and command. 

472 """ 

473 return self.command.get_help(self) 1adefbghcij

474 

475 def invoke(self, callback: Callable[..., V], /, *args: Any, **kwargs: Any) -> V: 1adefbghcij

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

477 are two ways to invoke this method: 

478 

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

480 keyword arguments are forwarded directly to the function. 

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

482 arguments are forwarded as well but proper click parameters 

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

484 will fill in defaults. 

485 """ 

486 ctx = self 1adefbghcij

487 

488 with augment_usage_errors(self): 1adefbghcij

489 with ctx: 1adefbghcij

490 return callback(*args, **kwargs) 1adefbghcij

491 

492 def set_parameter_source(self, name: str, source: ParameterSource) -> None: 1adefbghcij

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

494 from which the value of the parameter was obtained. 

495 """ 

496 self._parameter_source[name] = source 1adefbghcij

497 

498 def get_parameter_source(self, name: str) -> ParameterSource | None: 1adefbghcij

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

500 from which the value of the parameter was obtained. 

501 

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

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

504 will be `ParameterSource.DEFAULT` only if the 

505 value was actually taken from the default. 

506 """ 

507 return self._parameter_source.get(name) 1adefbghcij

508 

509 

510class Command(ABC): 1adefbghcij

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

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

513 more parsing to commands nested below it. 

514 """ 

515 

516 context_class: type[Context] = Context 1adefbghcij

517 allow_extra_args = False 1adefbghcij

518 allow_interspersed_args = True 1adefbghcij

519 ignore_unknown_options = False 1adefbghcij

520 

521 def __init__( 1adefbghcij

522 self, 

523 name: str | None, 

524 context_settings: MutableMapping[str, Any] | None = None, 

525 callback: Callable[..., Any] | None = None, 

526 params: list["Parameter"] | None = None, 

527 help: str | None = None, 

528 epilog: str | None = None, 

529 short_help: str | None = None, 

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

531 add_help_option: bool = True, 

532 no_args_is_help: bool = False, 

533 hidden: bool = False, 

534 deprecated: bool | str = False, 

535 ) -> None: 

536 self.name = name 1adefbghcij

537 

538 if context_settings is None: 1adefbghcij

539 context_settings = {} 1adefbghcij

540 

541 self.context_settings: MutableMapping[str, Any] = context_settings 1adefbghcij

542 

543 self.callback = callback 1adefbghcij

544 self.params: list[Parameter] = params or [] 1adefbghcij

545 self.help = help 1adefbghcij

546 self.epilog = epilog 1adefbghcij

547 self.options_metavar = options_metavar 1adefbghcij

548 self.short_help = short_help 1adefbghcij

549 self.add_help_option = add_help_option 1adefbghcij

550 self._help_option: TyperOption | None = None 1adefbghcij

551 self.no_args_is_help = no_args_is_help 1adefbghcij

552 self.hidden = hidden 1adefbghcij

553 self.deprecated = deprecated 1adefbghcij

554 

555 def __repr__(self) -> str: 1adefbghcij

556 return f"<{self.__class__.__name__} {self.name}>" 1adefbghcij

557 

558 def get_usage(self, ctx: Context) -> str: 1adefbghcij

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

560 formatter = ctx.make_formatter() 1adefbghcij

561 self.format_usage(ctx, formatter) 1adefbghcij

562 return formatter.getvalue().rstrip("\n") 1adefbghcij

563 

564 def get_params(self, ctx: Context) -> list["Parameter"]: 1adefbghcij

565 params = self.params 1adefbghcij

566 help_option = self.get_help_option(ctx) 1adefbghcij

567 

568 if help_option is not None: 1adefbghcij

569 params = [*params, help_option] 1adefbghcij

570 

571 return params 1adefbghcij

572 

573 def format_usage(self, ctx: Context, formatter: HelpFormatter) -> None: 1adefbghcij

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

575 pieces = self.collect_usage_pieces(ctx) 1adefbghcij

576 formatter.write_usage(ctx.command_path, " ".join(pieces)) 1adefbghcij

577 

578 def collect_usage_pieces(self, ctx: Context) -> list[str]: 1adefbghcij

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

580 it as a list of strings. 

581 """ 

582 rv = [self.options_metavar] if self.options_metavar else [] 1adefbghcij

583 

584 for param in self.get_params(ctx): 1adefbghcij

585 rv.extend(param.get_usage_pieces(ctx)) 1adefbghcij

586 

587 return rv 1adefbghcij

588 

589 def get_help_option_names(self, ctx: Context) -> list[str]: 1adefbghcij

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

591 all_names = set(ctx.help_option_names) 1adefbghcij

592 for param in self.params: 1adefbghcij

593 all_names.difference_update(param.opts) 1adefbghcij

594 all_names.difference_update(param.secondary_opts) 1adefbghcij

595 return list(all_names) 1adefbghcij

596 

597 def get_help_option(self, ctx: Context) -> Union["TyperOption", None]: 1adefbghcij

598 """Returns the help option object.""" 

599 help_option_names = self.get_help_option_names(ctx) 1adefbghcij

600 

601 if not help_option_names or not self.add_help_option: 1adefbghcij

602 return None 1adefbghcij

603 

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

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

606 # callback ordering by iter_params_for_processing(), which relies on 

607 # object comparison. 

608 if self._help_option is None: 1adefbghcij

609 # Avoid circular import. 

610 from .decorators import help_option 1adefbghcij

611 

612 # Apply help_option decorator and pop resulting option 

613 help_option(help_option_names)(self) 1adefbghcij

614 self._help_option = cast("TyperOption", self.params.pop()) 1adefbghcij

615 

616 return self._help_option 1adefbghcij

617 

618 def make_parser(self, ctx: Context) -> _OptionParser: 1adefbghcij

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

620 parser = _OptionParser(ctx) 1adefbghcij

621 for param in self.get_params(ctx): 1adefbghcij

622 param.add_to_parser(parser, ctx) 1adefbghcij

623 return parser 1adefbghcij

624 

625 def get_help(self, ctx: Context) -> str: 1adefbghcij

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

627 formatter = ctx.make_formatter() 1adefbghcij

628 self.format_help(ctx, formatter) 1adefbghcij

629 return formatter.getvalue().rstrip("\n") 1adefbghcij

630 

631 def get_short_help_str(self, limit: int = 45) -> str: 1adefbghcij

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

633 long help string. 

634 """ 

635 if self.short_help: 1adefbghcij

636 text = inspect.cleandoc(self.short_help) 1adefbghcij

637 elif self.help: 1adefbghcij

638 text = make_default_short_help(self.help, limit) 1adefbghcij

639 else: 

640 text = "" 1adefbghcij

641 

642 if self.deprecated: 1adefbghcij

643 deprecated_message = ( 1adefbghcij

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

645 if isinstance(self.deprecated, str) 

646 else "(DEPRECATED)" 

647 ) 

648 text = f"{text} {deprecated_message}" 1adefbghcij

649 

650 return text.strip() 1adefbghcij

651 

652 def format_help(self, ctx: Context, formatter: HelpFormatter) -> None: 1adefbghcij

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

654 self.format_usage(ctx, formatter) 1adefbghcij

655 self.format_help_text(ctx, formatter) 1adefbghcij

656 self.format_options(ctx, formatter) 1adefbghcij

657 self.format_epilog(ctx, formatter) 1adefbghcij

658 

659 def format_help_text(self, ctx: Context, formatter: HelpFormatter) -> None: 1adefbghcij

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

661 if self.help is not None: 1adefbghcij

662 # truncate the help text to the first form feed 

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

664 else: 

665 text = "" 1adefbghcij

666 

667 if self.deprecated: 1adefbghcij

668 deprecated_message = ( 1adefbghcij

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

670 if isinstance(self.deprecated, str) 

671 else "(DEPRECATED)" 

672 ) 

673 text = f"{text} {deprecated_message}" 1adefbghcij

674 

675 if text: 1adefbghcij

676 formatter.write_paragraph() 1adefbghcij

677 

678 with formatter.indentation(): 1adefbghcij

679 formatter.write_text(text) 1adefbghcij

680 

681 @abstractmethod 1adefbghcij

682 def format_options(self, ctx: Context, formatter: HelpFormatter) -> None: 1adefbghcij

683 pass # pragma: no cover 

684 

685 def format_epilog(self, ctx: Context, formatter: HelpFormatter) -> None: 1adefbghcij

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

687 if self.epilog: 1adefbghcij

688 epilog = inspect.cleandoc(self.epilog) 1adefbghcij

689 formatter.write_paragraph() 1adefbghcij

690 

691 with formatter.indentation(): 1adefbghcij

692 formatter.write_text(epilog) 1adefbghcij

693 

694 def make_context( 1adefbghcij

695 self, 

696 info_name: str | None, 

697 args: list[str], 

698 parent: Context | None = None, 

699 **extra: Any, 

700 ) -> Context: 

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

702 off the parsing and create a new `Context`. It does not 

703 invoke the actual command callback though. 

704 

705 To quickly customize the context class used without overriding 

706 this method, set the `context_class` attribute. 

707 """ 

708 for key, value in self.context_settings.items(): 1adefbghcij

709 if key not in extra: 1adefbghcij

710 extra[key] = value 1adefbghcij

711 

712 ctx = self.context_class(self, info_name=info_name, parent=parent, **extra) 1adefbghcij

713 

714 with ctx.scope(cleanup=False): 1adefbghcij

715 self.parse_args(ctx, args) 1adefbghcij

716 return ctx 1adefbghcij

717 

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

719 if not args and self.no_args_is_help and not ctx.resilient_parsing: 1adefbghcij

720 raise NoArgsIsHelpError(ctx) # pragma: no cover 

721 

722 parser = self.make_parser(ctx) 1adefbghcij

723 opts, args, param_order = parser.parse_args(args=args) 1adefbghcij

724 

725 for param in iter_params_for_processing(param_order, self.get_params(ctx)): 1adefbghcij

726 _, args = param.handle_parse_result(ctx, opts, args) 1adefbghcij

727 

728 if args and not ctx.allow_extra_args and not ctx.resilient_parsing: 1adefbghcij

729 extra_args = " ".join(_escape_control_characters(str(arg)) for arg in args) 1adefbghcij

730 ctx.fail(f"Got unexpected extra argument(s) ({extra_args})") 1adefbghcij

731 

732 ctx.args = args 1adefbghcij

733 ctx._opt_prefixes.update(parser._opt_prefixes) 1adefbghcij

734 return args 1adefbghcij

735 

736 def invoke(self, ctx: Context) -> Any: 1adefbghcij

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

738 in the right way. 

739 """ 

740 if self.deprecated: 1adefbghcij

741 extra_message = ( 1adefbghcij

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

743 ) 

744 message = f"DeprecationWarning: The command {self.name!r} is deprecated.{extra_message}" 1adefbghcij

745 echo(style(message, fg="red"), err=True) 1adefbghcij

746 

747 if self.callback is not None: 1adefbghcij

748 return ctx.invoke(self.callback, **ctx.params) 1adefbghcij

749 

750 def shell_complete(self, ctx: Context, incomplete: str) -> list["CompletionItem"]: 1adefbghcij

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

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

753 

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

755 commands are valid at any point during command completion. 

756 """ 

757 # avoid circular imports 

758 from .shell_completion import CompletionItem 1adefbghcij

759 

760 results: list[CompletionItem] = [] 1adefbghcij

761 

762 if incomplete and not incomplete[0].isalnum(): 1adefbghcij

763 # avoid circular imports 

764 from ..core import TyperOption 1adefbghcij

765 

766 for param in self.get_params(ctx): 1adefbghcij

767 if ( 1a

768 not isinstance(param, TyperOption) 

769 or param.hidden 

770 or ( 

771 not param.multiple 

772 and ctx.get_parameter_source(param.name) 

773 is ParameterSource.COMMANDLINE 

774 ) 

775 ): 

776 continue 1adefbghcij

777 

778 results.extend( 1adefbghcij

779 CompletionItem(name, help=param.help) 

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

781 if name.startswith(incomplete) 

782 ) 

783 

784 return results 1adefbghcij

785 

786 @abstractmethod 1adefbghcij

787 def main( 1adefbghcij

788 self, 

789 args: Sequence[str] | None = None, 

790 prog_name: str | None = None, 

791 complete_var: str | None = None, 

792 standalone_mode: bool = True, 

793 windows_expand_args: bool = True, 

794 **extra: Any, 

795 ) -> Any: 

796 pass # pragma: no cover 

797 

798 @abstractmethod 1adefbghcij

799 def _main_shell_completion( 1adefbghcij

800 self, 

801 ctx_args: MutableMapping[str, Any], 

802 prog_name: str, 

803 complete_var: str | None = None, 

804 ) -> None: 

805 pass # pragma: no cover 

806 

807 def __call__(self, *args: Any, **kwargs: Any) -> Any: 1adefbghcij

808 """Alias for self.main""" 

809 return self.main(*args, **kwargs) 1adefbghcij

810 

811 

812class Parameter(ABC): 1adefbghcij

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

814 `Option`\s or `Argument`\s. 

815 

816 Some settings are supported by both options and arguments. 

817 """ 

818 

819 param_type_name = "parameter" 1adefbghcij

820 

821 def __init__( 1adefbghcij

822 self, 

823 param_decls: Sequence[str] | None = None, 

824 required: bool = False, 

825 default: Any | Callable[[], Any] | None = None, 

826 callback: Callable[[Context, "Parameter", Any], Any] | None = None, 

827 nargs: int | None = None, 

828 multiple: bool = False, 

829 metavar: str | None = None, 

830 expose_value: bool = True, 

831 is_eager: bool = False, 

832 envvar: str | Sequence[str] | None = None, 

833 shell_complete: Callable[ 

834 [Context, "Parameter", str], list["CompletionItem"] | list[str] 

835 ] 

836 | None = None, 

837 ) -> None: 

838 self.name: str 1adefbghcij

839 self.opts: list[str] 1adefbghcij

840 self.secondary_opts: list[str] 1adefbghcij

841 self.name, self.opts, self.secondary_opts = self._parse_decls( 1adefbghcij

842 param_decls or (), expose_value 

843 ) 

844 

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

846 # information available. 

847 if nargs is None: 1adefbghcij

848 nargs = 1 1adefbghcij

849 

850 self.required = required 1adefbghcij

851 self.callback = callback 1adefbghcij

852 self.nargs = nargs 1adefbghcij

853 self.multiple = multiple 1adefbghcij

854 self.expose_value = expose_value 1adefbghcij

855 self.default: Any | Callable[[], Any] | None = default 1adefbghcij

856 self.is_eager = is_eager 1adefbghcij

857 self.metavar = metavar 1adefbghcij

858 self.envvar = envvar 1adefbghcij

859 self._custom_shell_complete = shell_complete 1adefbghcij

860 

861 def __repr__(self) -> str: 1adefbghcij

862 return f"<{self.__class__.__name__} {self.name}>" 1adefbghcij

863 

864 @abstractmethod 1adefbghcij

865 def _parse_decls( 1adefbghcij

866 self, decls: Sequence[str], expose_value: bool 

867 ) -> tuple[str, list[str], list[str]]: 

868 pass # pragma: no cover 

869 

870 @overload 1adefbghcij

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

872 

873 @overload 1adefbghcij

874 def get_default( 1adefbghcij

875 self, ctx: Context, call: bool = ... 1abc

876 ) -> Any | Callable[[], Any] | None: ... 1abc

877 

878 def get_default( 1adefbghcij

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

880 ) -> Any | Callable[[], Any] | None: 

881 """Get the default for the parameter""" 

882 value = ctx.lookup_default(self.name, call=False) 1adefbghcij

883 

884 if value is None: 1adefbghcij

885 value = self.default 1adefbghcij

886 

887 if call and callable(value): 1adefbghcij

888 value = value() 1adefbghcij

889 

890 return value 1adefbghcij

891 

892 @abstractmethod 1adefbghcij

893 def add_to_parser(self, parser: _OptionParser, ctx: Context) -> None: 1adefbghcij

894 pass # pragma: no cover 

895 

896 def consume_value( 1adefbghcij

897 self, ctx: Context, opts: Mapping[str, Any] 

898 ) -> tuple[Any, ParameterSource]: 

899 value = opts.get(self.name) 1adefbghcij

900 source = ParameterSource.COMMANDLINE 1adefbghcij

901 

902 if value is None: 1adefbghcij

903 value = self.value_from_envvar(ctx) 1adefbghcij

904 source = ParameterSource.ENVIRONMENT 1adefbghcij

905 

906 if value is None: 1adefbghcij

907 value = ctx.lookup_default(self.name) 1adefbghcij

908 source = ParameterSource.DEFAULT_MAP 1adefbghcij

909 

910 if value is None: 1adefbghcij

911 value = self.get_default(ctx) 1adefbghcij

912 source = ParameterSource.DEFAULT 1adefbghcij

913 

914 return value, source 1adefbghcij

915 

916 @abstractmethod 1adefbghcij

917 def value_is_missing(self, value: Any) -> bool: 1adefbghcij

918 pass # pragma: no cover 

919 

920 @abstractmethod 1adefbghcij

921 def process_value(self, ctx: Context, value: Any) -> Any: 1adefbghcij

922 """Process the value of this parameter.""" 

923 pass # pragma: no cover 

924 

925 def resolve_envvar_value(self, ctx: Context) -> str | None: 1adefbghcij

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

927 parameter. 

928 

929 Environment variables values are `always returned as strings 

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

931 

932 This method returns ``None`` if: 

933 

934 - the `envvar` property is not set on `Parameter`, 

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

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

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

938 

939 If `envvar` is setup with multiple environment variables, 

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

941 """ 

942 if self.envvar is None: 1adefbghcij

943 return None 1adefbghcij

944 

945 if isinstance(self.envvar, str): 1adefbghcij

946 rv = os.environ.get(self.envvar) 1adefbghcij

947 

948 if rv: 1adefbghcij

949 return rv 1adefbghcij

950 else: 

951 for envvar in self.envvar: 1adefbghcij

952 rv = os.environ.get(envvar) 1adefbghcij

953 

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

955 if rv: 1adefbghcij

956 return rv 1adefbghcij

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

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

959 

960 return None 1adefbghcij

961 

962 envvar_list_splitter: ClassVar[str | None] = None 1adefbghcij

963 

964 def split_envvar_value(self, rv: str) -> Sequence[str]: 1adefbghcij

965 """Given a value from an environment variable this splits it up 

966 into small chunks depending on the defined envvar list splitter. 

967 

968 If the splitter is set to `None`, which means that whitespace splits, 

969 then leading and trailing whitespace is ignored. Otherwise, leading 

970 and trailing splitters usually lead to empty items being included. 

971 """ 

972 return (rv or "").split(self.envvar_list_splitter) 1adefbghcij

973 

974 @abstractmethod 1adefbghcij

975 def value_from_envvar(self, ctx: Context) -> str | Sequence[str] | None: 1adefbghcij

976 """Process the value from the environment variable.""" 

977 pass # pragma: no cover 

978 

979 def handle_parse_result( 1adefbghcij

980 self, ctx: Context, opts: Mapping[str, Any], args: list[str] 

981 ) -> tuple[Any, list[str]]: 

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

983 

984 Always process the value through the Parameter's `type`, wherever it 

985 comes from. 

986 

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

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

989 a default). 

990 """ 

991 from ..core import _TyperParameter 1adefbghcij

992 

993 with augment_usage_errors(ctx, param=cast(_TyperParameter, self)): 1adefbghcij

994 value, source = self.consume_value(ctx, opts) 1adefbghcij

995 

996 ctx.set_parameter_source(self.name, source) 1adefbghcij

997 

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

999 try: 1adefbghcij

1000 value = self.process_value(ctx, value) 1adefbghcij

1001 except Exception: 1adefbghcij

1002 if not ctx.resilient_parsing: 1adefbghcij

1003 raise 1adefbghcij

1004 value = None 1adefbghcij

1005 

1006 if self.expose_value: 1adefbghcij

1007 ctx.params[self.name] = value 1adefbghcij

1008 

1009 return value, args 1adefbghcij

1010 

1011 @abstractmethod 1adefbghcij

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

1013 pass # pragma: no cover 

1014 

1015 def get_usage_pieces(self, ctx: Context) -> list[str]: 1adefbghcij

1016 return [] 1adefbghcij

1017 

1018 @abstractmethod 1adefbghcij

1019 def shell_complete(self, ctx: Context, incomplete: str) -> list["CompletionItem"]: 1adefbghcij

1020 """Return a list of completions for the incomplete value.""" 

1021 pass # pragma: no cover