Coverage for typer / core.py: 100%

644 statements  

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

1import errno 1afghbdecij

2import inspect 1afghbdecij

3import os 1afghbdecij

4import sys 1afghbdecij

5from collections.abc import Callable, Mapping, MutableMapping, Sequence 1afghbdecij

6from difflib import get_close_matches 1afghbdecij

7from enum import Enum 1afghbdecij

8from gettext import gettext as _ 1afghbdecij

9from typing import ( 1afghbdecij

10 Any, 

11 TextIO, 

12 Union, 

13 cast, 

14 get_args, 

15 get_origin, 

16) 

17 

18from . import _click 1afghbdecij

19from ._click.parser import _OptionParser 1afghbdecij

20from ._click.shell_completion import CompletionItem 1afghbdecij

21from ._coercion import ( 1afghbdecij

22 RuntimeParam, 

23 TypeDescriptor, 

24 build_runtime_param, 

25) 

26from ._display import describe_number_range 1afghbdecij

27from ._param_types import choice_as_str, normalize_choice_value 1afghbdecij

28from ._typing import Literal 1afghbdecij

29from .exceptions import Abort, Exit 1afghbdecij

30from .utils import parse_boolean_env_var 1afghbdecij

31 

32MarkupMode = Literal["markdown", "rich", None] 1afghbdecij

33MARKUP_MODE_KEY = "TYPER_RICH_MARKUP_MODE" 1afghbdecij

34 

35HAS_RICH = parse_boolean_env_var(os.getenv("TYPER_USE_RICH"), default=True) 1afghbdecij

36 

37if HAS_RICH: 1afghbdecij

38 DEFAULT_MARKUP_MODE: MarkupMode = "rich" 1afghbdecij

39else: 

40 DEFAULT_MARKUP_MODE = None 1afghbdecij

41 

42 

43# Copy from _click.parser._split_opt 

44def _split_opt(opt: str) -> tuple[str, str]: 1afghbdecij

45 first = opt[:1] 1afghbdecij

46 if first.isalnum(): 1afghbdecij

47 return "", opt 1afghbdecij

48 if opt[1:2] == first: 1afghbdecij

49 return opt[:2], opt[2:] 1afghbdecij

50 return first, opt[1:] 1afghbdecij

51 

52 

53def _typer_param_setup_autocompletion_compat( 1afghbdecij

54 self: _click.Parameter, 

55 *, 

56 autocompletion: Callable[ 

57 [_click.Context, list[str], str], list[tuple[str, str] | str] 

58 ] 

59 | None = None, 

60) -> None: 

61 if self._custom_shell_complete is not None: 1afghbdecij

62 import warnings 1afghbdecij

63 

64 warnings.warn( 1afghbdecij

65 "In Typer, only the parameter 'autocompletion' is supported. " 

66 "The support for 'shell_complete' is deprecated and will be removed in upcoming versions. ", 

67 DeprecationWarning, 

68 stacklevel=2, 

69 ) 

70 

71 if autocompletion is not None: 1afghbdecij

72 

73 def compat_autocompletion( 1afghbdecij

74 ctx: _click.Context, param: _click.core.Parameter, incomplete: str 

75 ) -> list[CompletionItem]: 

76 out = [] 1afghbdecij

77 

78 for c in autocompletion(ctx, [], incomplete): 1afghbdecij

79 if isinstance(c, tuple): 1afghbdecij

80 use_completion = CompletionItem(c[0], help=c[1]) 1afghbdecij

81 else: 

82 assert isinstance(c, str) 1afghbdecij

83 use_completion = CompletionItem(c) 1afghbdecij

84 

85 if use_completion.value.startswith(incomplete): 1afghbdecij

86 out.append(use_completion) 1afghbdecij

87 

88 return out 1afghbdecij

89 

90 self._custom_shell_complete = compat_autocompletion 1afghbdecij

91 

92 

93class _TyperParameter(_click.core.Parameter): 1afghbdecij

94 """Typer parameter with runtime coercion.""" 

95 

96 _runtime_param: RuntimeParam | None 1abc

97 type_descriptor: TypeDescriptor 1abc

98 show_choices: bool 1abc

99 

100 def get_runtime_param(self) -> RuntimeParam: 1afghbdecij

101 """lazy definition to avoid up-front costs""" 

102 if self._runtime_param is None: 1afghbdecij

103 self._runtime_param = build_runtime_param(self.type_descriptor) 1afghbdecij

104 return self._runtime_param 1afghbdecij

105 

106 def process_value(self, ctx: _click.Context, value: Any) -> Any: 1afghbdecij

107 # Skip coercion for bool flags that already yield bools 

108 if not (self.type_descriptor.annotation is bool and isinstance(value, bool)): 1afghbdecij

109 value = self.get_runtime_param().coerce(value, param=self, ctx=ctx) 1afghbdecij

110 if self.required and self.value_is_missing(value): 1afghbdecij

111 raise _click.exceptions.MissingParameter(ctx=ctx, param=self) 1afghbdecij

112 if self.callback is not None: 1afghbdecij

113 value = self.callback(ctx, self, value) 1afghbdecij

114 return value 1afghbdecij

115 

116 def value_is_missing(self, value: Any) -> bool: 1afghbdecij

117 if value is None: 1afghbdecij

118 return True 1afghbdecij

119 if (self.nargs != 1 or self.multiple) and value in ((), []): 1afghbdecij

120 return True 1afghbdecij

121 return False 1afghbdecij

122 

123 def get_missing_message(self, ctx: _click.Context | None) -> str | None: 1afghbdecij

124 desc = self.type_descriptor 1afghbdecij

125 if desc.is_choice and desc.choices is not None: 1afghbdecij

126 normalized = [ 1afghbdecij

127 normalize_choice_value(choice, desc.case_sensitive, ctx) 

128 for choice in desc.choices 

129 ] 

130 choices_str = ",\n\t".join(normalized) 1afghbdecij

131 return f"Choose from:\n\t{choices_str}" 1afghbdecij

132 return "" 1afghbdecij

133 

134 def value_from_envvar(self, ctx: _click.Context) -> str | Sequence[str] | None: 1afghbdecij

135 rv: Any | None = self.resolve_envvar_value(ctx) 1afghbdecij

136 if rv is not None and (self.nargs != 1 or self.multiple): 1afghbdecij

137 splitter = self.type_descriptor.envvar_list_splitter 1afghbdecij

138 if splitter is not None: 1afghbdecij

139 rv = (rv or "").split(splitter) 1afghbdecij

140 else: 

141 rv = self.split_envvar_value(rv) 1afghbdecij

142 return rv 1afghbdecij

143 

144 def shell_complete( 1afghbdecij

145 self, ctx: _click.Context, incomplete: str 

146 ) -> list[CompletionItem]: 

147 # custom 

148 if self._custom_shell_complete is not None: 1afghbdecij

149 results = self._custom_shell_complete(ctx, self, incomplete) 1afghbdecij

150 if results and isinstance(results[0], str): 1afghbdecij

151 results = [CompletionItem(c) for c in results] 1afghbdecij

152 return cast(list[CompletionItem], results) 1afghbdecij

153 # choice 

154 desc = self.type_descriptor 1afghbdecij

155 if desc.is_choice and desc.choices is not None: 1afghbdecij

156 str_choices = map(choice_as_str, desc.choices) 1afghbdecij

157 if desc.case_sensitive: 1afghbdecij

158 matched = (c for c in str_choices if c.startswith(incomplete)) 1afghbdecij

159 else: 

160 incomplete = incomplete.lower() 1afghbdecij

161 matched = (c for c in str_choices if c.lower().startswith(incomplete)) 1afghbdecij

162 return [CompletionItem(c) for c in matched] 1afghbdecij

163 # file 

164 if desc.is_file: 1afghbdecij

165 return [CompletionItem(incomplete, type="file")] 1afghbdecij

166 # fall-back, specifically also required for path's 

167 return [] 1afghbdecij

168 

169 @property 1afghbdecij

170 def display_name_raw(self) -> str: 1afghbdecij

171 if self.metavar is not None: 1afghbdecij

172 return self.metavar 1afghbdecij

173 return self.name 1afghbdecij

174 

175 def get_error_hint(self) -> str: 1afghbdecij

176 return f"'{self.display_name_raw}'" 1afghbdecij

177 

178 def display_type(self, ctx: _click.Context) -> str: 1afghbdecij

179 """Formatted type string for help, e.g. ``<int>``""" 

180 desc = self.type_descriptor 1afghbdecij

181 if desc.is_choice: 1afghbdecij

182 if not self.show_choices: 1afghbdecij

183 type_names = [self._bare_type(type(c)) for c in desc.choices or ()] 1afghbdecij

184 label = "|".join([*dict.fromkeys(type_names)]) 1afghbdecij

185 else: 

186 normalized_mapping = { 1afghbdecij

187 c: normalize_choice_value(c, desc.case_sensitive, ctx) 

188 for c in desc.choices or () 

189 } 

190 label = "|".join(normalized_mapping.values()) 1afghbdecij

191 if desc.is_list: 1afghbdecij

192 label = f"list[{label}]" 1afghbdecij

193 elif desc.is_list: 1afghbdecij

194 label = self.bare_type() 1afghbdecij

195 elif desc.is_tuple: 1afghbdecij

196 labels = [self._bare_type(arg) for arg in get_args(desc.annotation)] 1afghbdecij

197 label = ",".join(labels) 1afghbdecij

198 elif desc.is_datetime: 1afghbdecij

199 formats = desc.parameter_info.formats 1afghbdecij

200 if formats is not None: 1afghbdecij

201 label = "|".join(tuple(formats)) 1afghbdecij

202 else: 

203 label = "datetime" 1afghbdecij

204 elif desc.is_ranged: 1afghbdecij

205 label = f"{desc.ranged_type_name} range" 1afghbdecij

206 elif desc.is_path: 1afghbdecij

207 label = desc.path_type 1afghbdecij

208 else: 

209 label = self.bare_type() 1afghbdecij

210 return f"<{label}>" 1afghbdecij

211 

212 def display_type_rich(self, ctx: _click.Context) -> str | None: 1afghbdecij

213 return self.display_type(ctx) 1afghbdecij

214 

215 def bare_type(self) -> str: 1afghbdecij

216 annotation = self.type_descriptor.annotation 1afghbdecij

217 return self._bare_type(annotation) 1afghbdecij

218 

219 def _bare_type(self, annotation: type) -> str: 1afghbdecij

220 display_type = str(annotation) 1afghbdecij

221 origin = get_origin(annotation) 1afghbdecij

222 if origin is list: 1afghbdecij

223 args = get_args(annotation) 1afghbdecij

224 assert len(args) == 1 1afghbdecij

225 element_label = self._bare_type(args[0]) 1afghbdecij

226 display_type = f"list[{element_label}]" 1afghbdecij

227 elif isinstance(annotation, type): 1afghbdecij

228 display_type = annotation.__name__ 1afghbdecij

229 return display_type 1afghbdecij

230 

231 

232def _get_default_string( 1afghbdecij

233 obj: Union["TyperArgument", "TyperOption"], 

234 *, 

235 ctx: _click.Context, 

236 show_default_is_str: bool, 

237 default_value: list[Any] | tuple[Any, ...] | str | Callable[..., Any] | Any, 

238) -> str: 

239 # Extracted from _click.core.Option.get_help_record() to be reused by 

240 # rich_utils avoiding RegEx hacks 

241 if show_default_is_str: 1afghbdecij

242 default_string = f"({obj.show_default})" 1afghbdecij

243 elif isinstance(default_value, (list, tuple)): 1afghbdecij

244 parts = [ 1afghbdecij

245 _get_default_string( 

246 obj, ctx=ctx, show_default_is_str=show_default_is_str, default_value=d 

247 ) 

248 for d in default_value 

249 ] 

250 if all(not part for part in parts): 1afghbdecij

251 default_string = "" 1afghbdecij

252 else: 

253 default_string = ", ".join(parts) 1afghbdecij

254 elif isinstance(default_value, Enum): 1afghbdecij

255 default_string = str(default_value.value) 1afghbdecij

256 elif inspect.isfunction(default_value): 1afghbdecij

257 default_string = _("(dynamic)") 1afghbdecij

258 elif isinstance(obj, TyperOption) and obj.is_bool_flag and obj.secondary_opts: 1afghbdecij

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

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

261 # Typer override, original commented 

262 # default_string = _click.parser.split_opt( 

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

264 # )[1] 

265 if obj.default: 1afghbdecij

266 if obj.opts: 1afghbdecij

267 default_string = _split_opt(obj.opts[0])[1] 1afghbdecij

268 else: 

269 default_string = str(default_value) 1afghbdecij

270 else: 

271 default_string = _split_opt(obj.secondary_opts[0])[1] 1afghbdecij

272 # Typer override end 

273 elif ( 1a

274 isinstance(obj, TyperOption) 

275 and obj.is_bool_flag 

276 and not obj.secondary_opts 

277 and not default_value 

278 ): 

279 default_string = "" 1afghbdecij

280 else: 

281 default_string = str(default_value) 1afghbdecij

282 return default_string 1afghbdecij

283 

284 

285def _extract_default_help_str( 1afghbdecij

286 obj: Union["TyperArgument", "TyperOption"], *, ctx: _click.Context 

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

288 # Extracted from _click.core.Option.get_help_record() to be reused by 

289 # rich_utils avoiding RegEx hacks 

290 # Temporarily enable resilient parsing to avoid type casting 

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

292 # help formatting in general. 

293 resilient = ctx.resilient_parsing 1afghbdecij

294 ctx.resilient_parsing = True 1afghbdecij

295 

296 try: 1afghbdecij

297 default_value = obj.get_default(ctx, call=False) 1afghbdecij

298 finally: 

299 ctx.resilient_parsing = resilient 1afghbdecij

300 return default_value 1afghbdecij

301 

302 

303def _main( 1afghbdecij

304 self: _click.Command, 

305 *, 

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

307 prog_name: str | None = None, 

308 complete_var: str | None = None, 

309 standalone_mode: bool = True, 

310 windows_expand_args: bool = True, 

311 rich_markup_mode: MarkupMode = DEFAULT_MARKUP_MODE, 

312 **extra: Any, 

313) -> Any: 

314 # Originally copied from _click.main(), adopted to handle custom rich exceptions etc 

315 if args is None: 1afghbdecij

316 args = sys.argv[1:] 1afghbdecij

317 

318 if os.name == "nt" and windows_expand_args: # pragma: no cover 1afghbdecij

319 args = _click.utils._expand_args(args) 1bde

320 else: 

321 args = list(args) 1afghbdecij

322 

323 if prog_name is None: 1afghbdecij

324 prog_name = _click.utils._detect_program_name() 1afghbdecij

325 

326 # Process shell completion requests and exit early. 

327 self._main_shell_completion(extra, prog_name, complete_var) 1afghbdecij

328 

329 try: 1afghbdecij

330 try: 1afghbdecij

331 with self.make_context(prog_name, args, **extra) as ctx: 1afghbdecij

332 rv = self.invoke(ctx) 1afghbdecij

333 if not standalone_mode: 1afghbdecij

334 return rv 1afghbdecij

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

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

337 # has obvious effects 

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

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

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

341 # by its truthiness/falsiness 

342 ctx.exit() 1afghbdecij

343 except EOFError as e: 1afghbdecij

344 _click.echo(file=sys.stderr) 1afghbdecij

345 raise Abort() from e 1afghbdecij

346 except KeyboardInterrupt as e: 1afghbdecij

347 raise Exit(130) from e 1afghbdecij

348 except _click.exceptions.ClickException as e: 1afghbdecij

349 if not standalone_mode: 1afghbdecij

350 raise 1afghbdecij

351 if HAS_RICH and rich_markup_mode is not None: 1afghbdecij

352 from . import rich_utils 1afghbdecij

353 

354 rich_utils.rich_format_error(e) 1afghbdecij

355 else: 

356 e.show() 1afghbdecij

357 sys.exit(e.exit_code) 1afghbdecij

358 except OSError as e: 1afghbdecij

359 if e.errno == errno.EPIPE: 1afghbdecij

360 sys.stdout = cast(TextIO, _click.utils.PacifyFlushWrapper(sys.stdout)) 1afghbdecij

361 sys.stderr = cast(TextIO, _click.utils.PacifyFlushWrapper(sys.stderr)) 1afghbdecij

362 sys.exit(1) 1afghbdecij

363 else: 

364 raise 1afghbdecij

365 except Exit as e: 1afghbdecij

366 if standalone_mode: 1afghbdecij

367 sys.exit(e.exit_code) 1afghbdecij

368 else: 

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

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

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

372 # would return its result 

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

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

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

376 # tell the difference between the two 

377 return e.exit_code 1afghbdecij

378 except Abort: 1afghbdecij

379 if not standalone_mode: 1afghbdecij

380 raise 1afghbdecij

381 if HAS_RICH and rich_markup_mode is not None: 1afghbdecij

382 from . import rich_utils 1afghbdecij

383 

384 rich_utils.rich_abort_error() 1afghbdecij

385 else: 

386 _click.echo(_("Aborted!"), file=sys.stderr) 1afghbdecij

387 sys.exit(1) 1afghbdecij

388 

389 

390class TyperArgument(_TyperParameter): 1afghbdecij

391 param_type_name = "argument" 1afghbdecij

392 

393 def __init__( 1afghbdecij

394 self, 

395 *, 

396 # Parameter 

397 param_decls: list[str], 

398 type_descriptor: TypeDescriptor, 

399 required: bool = False, 

400 default: Any | None = None, 

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

402 nargs: int | None = None, 

403 metavar: str | None = None, 

404 expose_value: bool = True, 

405 is_eager: bool = False, 

406 envvar: str | list[str] | None = None, 

407 # Note that shell_complete is not fully supported and will be removed in future versions 

408 # TODO: Remove shell_complete in a future version (after 0.16.0) 

409 shell_complete: Callable[ 

410 [_click.Context, _click.Parameter, str], 

411 list[CompletionItem] | list[str], 

412 ] 

413 | None = None, 

414 autocompletion: Callable[..., Any] | None = None, 

415 # TyperArgument 

416 show_default: bool | str = True, 

417 show_choices: bool = True, 

418 show_envvar: bool = True, 

419 help: str | None = None, 

420 hidden: bool = False, 

421 # Numbers 

422 min: int | float | None = None, 

423 max: int | float | None = None, 

424 # Rich settings 

425 rich_help_panel: str | None = None, 

426 ): 

427 self.help = help 1afghbdecij

428 self.show_default = show_default 1afghbdecij

429 self.show_choices = show_choices 1afghbdecij

430 self.show_envvar = show_envvar 1afghbdecij

431 self.hidden = hidden 1afghbdecij

432 self.min = min 1afghbdecij

433 self.max = max 1afghbdecij

434 self.rich_help_panel = rich_help_panel 1afghbdecij

435 self.type_descriptor = type_descriptor 1afghbdecij

436 self._runtime_param = None 1afghbdecij

437 

438 super().__init__( 1afghbdecij

439 param_decls=param_decls, 

440 required=required, 

441 default=default, 

442 callback=callback, 

443 nargs=nargs, 

444 metavar=metavar, 

445 expose_value=expose_value, 

446 is_eager=is_eager, 

447 envvar=envvar, 

448 shell_complete=shell_complete, 

449 ) 

450 _typer_param_setup_autocompletion_compat(self, autocompletion=autocompletion) 1afghbdecij

451 

452 def _get_default_string( 1afghbdecij

453 self, 

454 *, 

455 ctx: _click.Context, 

456 show_default_is_str: bool, 

457 default_value: list[Any] | tuple[Any, ...] | str | Callable[..., Any] | Any, 

458 ) -> str: 

459 return _get_default_string( 1afghbdecij

460 self, 

461 ctx=ctx, 

462 show_default_is_str=show_default_is_str, 

463 default_value=default_value, 

464 ) 

465 

466 def _rich_display_name(self) -> str: 1afghbdecij

467 """Argument display name for the Rich help name column.""" 

468 name = self.display_name_raw 1afghbdecij

469 if self.metavar is None and self.nargs != 1: 1afghbdecij

470 name += "..." 1afghbdecij

471 return name 1afghbdecij

472 

473 def _usage_display_name(self) -> str: 1afghbdecij

474 """Argument name for the usage line only.""" 

475 name = self.display_name_raw 1afghbdecij

476 if self.required: 1afghbdecij

477 name = f"{{{name}}}" 1afghbdecij

478 else: 

479 name = f"[{name}]" 1afghbdecij

480 if self.nargs != 1: 1afghbdecij

481 name += "..." 1afghbdecij

482 return name 1afghbdecij

483 

484 def _extract_default_help_str( 1afghbdecij

485 self, *, ctx: _click.Context 

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

487 return _extract_default_help_str(self, ctx=ctx) 1afghbdecij

488 

489 def get_help_record(self, ctx: _click.Context) -> tuple[str, str] | None: 1afghbdecij

490 if self.hidden: 1afghbdecij

491 return None 1afghbdecij

492 name = self._rich_display_name() 1afghbdecij

493 type_str = self.display_type_rich(ctx=ctx) 1afghbdecij

494 if type_str: 1afghbdecij

495 name = f"{name} {type_str}" 1afghbdecij

496 help = self.help or "" 1afghbdecij

497 extra = [] 1afghbdecij

498 if self.show_envvar: 1afghbdecij

499 envvar = self.envvar 1afghbdecij

500 # allow_from_autoenv is currently not supported in Typer for CLI Arguments 

501 if envvar is not None: 1afghbdecij

502 var_str = ( 1afghbdecij

503 ", ".join(str(d) for d in envvar) 

504 if isinstance(envvar, (list, tuple)) 

505 else envvar 

506 ) 

507 extra.append(f"env var: {var_str}") 1afghbdecij

508 

509 # Typer override: 

510 # Extracted to _extract_default_help_str() to allow re-using it in rich_utils 

511 default_value = self._extract_default_help_str(ctx=ctx) 1afghbdecij

512 # Typer override end 

513 

514 show_default_is_str = isinstance(self.show_default, str) 1afghbdecij

515 

516 if show_default_is_str or ( 1afghbdecij

517 default_value is not None and (self.show_default or ctx.show_default) 

518 ): 

519 # Typer override: 

520 # Extracted to _get_default_string() to allow re-using it in rich_utils 

521 default_string = self._get_default_string( 1afghbdecij

522 ctx=ctx, 

523 show_default_is_str=show_default_is_str, 

524 default_value=default_value, 

525 ) 

526 # Typer override end 

527 if default_string: 1afghbdecij

528 extra.append(_("default: {default}").format(default=default_string)) 1afghbdecij

529 range_str = self._get_number_range_help_str() 1afghbdecij

530 if range_str: 1afghbdecij

531 extra.append(range_str) 1afghbdecij

532 if self.required: 1afghbdecij

533 extra.append(_("required")) 1afghbdecij

534 if extra: 1afghbdecij

535 extra_str = "; ".join(extra) 1afghbdecij

536 extra_str = f"[{extra_str}]" 1afghbdecij

537 rich_markup_mode = None 1afghbdecij

538 if hasattr(ctx, "obj") and isinstance(ctx.obj, dict): 1afghbdecij

539 rich_markup_mode = ctx.obj.get(MARKUP_MODE_KEY, None) 1afghbdecij

540 if HAS_RICH and rich_markup_mode == "rich": 1afghbdecij

541 # This is needed for when we want to export to HTML 

542 from . import rich_utils 1afghbdecij

543 

544 extra_str = rich_utils.escape_before_html_export(extra_str) 1afghbdecij

545 

546 help = f"{help} {extra_str}" if help else f"{extra_str}" 1afghbdecij

547 return name, help 1afghbdecij

548 

549 def _parse_decls( 1afghbdecij

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

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

552 assert decls 1afghbdecij

553 assert len(decls) == 1 1afghbdecij

554 name = arg = decls[0] 1afghbdecij

555 name = name.replace("-", "_") 1afghbdecij

556 return name, [arg], [] 1afghbdecij

557 

558 def get_usage_pieces(self, ctx: _click.Context) -> list[str]: 1afghbdecij

559 return [self._usage_display_name()] 1afghbdecij

560 

561 def add_to_parser(self, parser: _OptionParser, ctx: _click.Context) -> None: 1afghbdecij

562 parser.add_argument(dest=self.name, nargs=self.nargs, obj=self) 1afghbdecij

563 

564 def _get_number_range_help_str(self) -> str | None: 1afghbdecij

565 return describe_number_range(self.min, self.max) 1afghbdecij

566 

567 

568class TyperOption(_TyperParameter): 1afghbdecij

569 param_type_name = "option" 1afghbdecij

570 

571 _depr_flag_value: bool | None 1abc

572 

573 def __init__( 1afghbdecij

574 self, 

575 *, 

576 # Parameter 

577 param_decls: list[str], 

578 type_descriptor: TypeDescriptor, 

579 required: bool = False, 

580 default: Any | None = None, 

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

582 nargs: int | None = None, 

583 metavar: str | None = None, 

584 expose_value: bool = True, 

585 is_eager: bool = False, 

586 envvar: str | list[str] | None = None, 

587 # Note that shell_complete is not fully supported and will be removed in future versions 

588 # TODO: Remove shell_complete in a future version (after 0.16.0) 

589 shell_complete: Callable[ 

590 [_click.Context, _click.Parameter, str], 

591 list[CompletionItem] | list[str], 

592 ] 

593 | None = None, 

594 autocompletion: Callable[..., Any] | None = None, 

595 # Option 

596 show_default: bool | str = False, 

597 prompt: bool | str = False, 

598 confirmation_prompt: bool | str = False, 

599 prompt_required: bool = True, 

600 hide_input: bool = False, 

601 is_flag: bool | None = None, 

602 multiple: bool = False, 

603 count: bool = False, 

604 allow_from_autoenv: bool = True, 

605 help: str | None = None, 

606 hidden: bool = False, 

607 show_choices: bool = True, 

608 show_envvar: bool = False, 

609 # Numbers 

610 min: int | float | None = None, 

611 max: int | float | None = None, 

612 # Rich settings 

613 rich_help_panel: str | None = None, 

614 ): 

615 if help: 1afghbdecij

616 help = inspect.cleandoc(help) 1afghbdecij

617 

618 self.min = min 1afghbdecij

619 self.max = max 1afghbdecij

620 self.type_descriptor = type_descriptor 1afghbdecij

621 self._runtime_param = None 1afghbdecij

622 

623 super().__init__( 1afghbdecij

624 param_decls, 

625 multiple=multiple, 

626 required=required, 

627 default=default, 

628 callback=callback, 

629 nargs=nargs, 

630 metavar=metavar, 

631 expose_value=expose_value, 

632 is_eager=is_eager, 

633 envvar=envvar, 

634 shell_complete=shell_complete, 

635 ) 

636 

637 if prompt is True: 1afghbdecij

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

639 elif prompt is False: 1afghbdecij

640 prompt_text = None 1afghbdecij

641 else: 

642 prompt_text = prompt 1afghbdecij

643 

644 self.prompt = prompt_text 1afghbdecij

645 self.confirmation_prompt = confirmation_prompt 1afghbdecij

646 self.prompt_required = prompt_required 1afghbdecij

647 self.hide_input = hide_input 1afghbdecij

648 self.hidden = hidden 1afghbdecij

649 

650 # TODO: revisit all of this flag stuff 

651 self.is_flag: bool = bool(is_flag) 1afghbdecij

652 self.is_bool_flag: bool = bool(is_flag and not count) 1afghbdecij

653 

654 if self.is_flag: 1afghbdecij

655 self._depr_flag_value = True 1afghbdecij

656 else: 

657 self._depr_flag_value = None 1afghbdecij

658 

659 # Counting 

660 self.count = count 1afghbdecij

661 if count and self.min is None: 1afghbdecij

662 self.min = 0 1afghbdecij

663 

664 self.allow_from_autoenv = allow_from_autoenv 1afghbdecij

665 self.help = help 1afghbdecij

666 self.show_default = show_default 1afghbdecij

667 self.show_choices = show_choices 1afghbdecij

668 self.show_envvar = show_envvar 1afghbdecij

669 

670 _typer_param_setup_autocompletion_compat(self, autocompletion=autocompletion) 1afghbdecij

671 self.rich_help_panel = rich_help_panel 1afghbdecij

672 

673 def get_error_hint(self) -> str: 1afghbdecij

674 hint_list = self.opts or [self.display_name_raw] 1afghbdecij

675 result = " / ".join(f"'{x}'" for x in hint_list) 1afghbdecij

676 if self.show_envvar and self.envvar is not None: 1afghbdecij

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

678 return result 1afghbdecij

679 

680 def _parse_decls( 1afghbdecij

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

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

683 opts = [] 1afghbdecij

684 secondary_opts = [] 1afghbdecij

685 name = None 1afghbdecij

686 possible_names = [] 1afghbdecij

687 

688 for decl in decls: 1afghbdecij

689 if decl.isidentifier(): 1afghbdecij

690 if name: 1afghbdecij

691 raise TypeError(f"Name '{name}' defined twice") 1afghbdecij

692 name = decl 1afghbdecij

693 else: 

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

695 if split_char in decl: 1afghbdecij

696 first, second = decl.split(split_char, 1) 1afghbdecij

697 first = first.rstrip() 1afghbdecij

698 if first: 1afghbdecij

699 possible_names.append(_split_opt(first)) 1afghbdecij

700 opts.append(first) 1afghbdecij

701 second = second.lstrip() 1afghbdecij

702 if second: 1afghbdecij

703 secondary_opts.append(second.lstrip()) 1afghbdecij

704 if first == second: 1afghbdecij

705 raise ValueError( 1afghbdecij

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

707 " same flag for true/false." 

708 ) 

709 else: 

710 possible_names.append(_split_opt(decl)) 1afghbdecij

711 opts.append(decl) 1afghbdecij

712 

713 if not name and possible_names: 1afghbdecij

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

715 name = possible_names[0][1].replace("-", "_") 1afghbdecij

716 assert name.isidentifier() 1afghbdecij

717 

718 assert name is not None 1afghbdecij

719 

720 return name, opts, secondary_opts 1afghbdecij

721 

722 def add_to_parser(self, parser: _OptionParser, ctx: _click.Context) -> None: 1afghbdecij

723 if self.multiple: 1afghbdecij

724 action = "append" 1afghbdecij

725 elif self.count: 1afghbdecij

726 action = "count" 1afghbdecij

727 else: 

728 action = "store" 1afghbdecij

729 

730 if self.is_flag: 1afghbdecij

731 action = f"{action}_const" 1afghbdecij

732 

733 if self.is_bool_flag and self.secondary_opts: 1afghbdecij

734 parser.add_option( 1afghbdecij

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

736 ) 

737 parser.add_option( 1afghbdecij

738 obj=self, 

739 opts=self.secondary_opts, 

740 dest=self.name, 

741 action=action, 

742 const=False, 

743 ) 

744 else: 

745 parser.add_option( 1afghbdecij

746 obj=self, 

747 opts=self.opts, 

748 dest=self.name, 

749 action=action, 

750 const=self._depr_flag_value, 

751 ) 

752 else: 

753 parser.add_option( 1afghbdecij

754 obj=self, 

755 opts=self.opts, 

756 dest=self.name, 

757 action=action, 

758 nargs=self.nargs, 

759 ) 

760 

761 def prompt_for_value(self, ctx: _click.Context) -> Any: 1afghbdecij

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

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

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

765 value as result. 

766 """ 

767 assert self.prompt is not None 1afghbdecij

768 

769 # Calculate the default before prompting anything to lock in the value before 

770 # attempting any user interaction. 

771 default = self.get_default(ctx) 1afghbdecij

772 

773 # A boolean flag can use a simplified [y/n] confirmation prompt. 

774 if self.is_bool_flag: 1afghbdecij

775 # Nothing prevent you to declare an option that is simultaneously: 

776 # 1) auto-detected as a boolean flag, 

777 # 2) allowed to prompt, and 

778 # 3) still declare a non-boolean default. 

779 # This forced casting into a boolean is necessary to align any non-boolean 

780 # default to the prompt, which is going to be a [y/n]-style confirmation 

781 # because the option is still a boolean flag. That way, instead of [y/n], 

782 # we get [Y/n] or [y/N] depending on the truthy value of the default. 

783 # Refs: https://github.com/pallets/click/pull/3030#discussion_r2289180249 

784 if default is not None: 1afghbdecij

785 default = bool(default) 1afghbdecij

786 return _click.termui.confirm(self.prompt, default) 1afghbdecij

787 

788 # If show_default is set to True/False, provide this to `prompt` as well. For 

789 # non-bool values of `show_default`, we use `prompt`'s default behavior 

790 prompt_kwargs: Any = {} 1afghbdecij

791 if isinstance(self.show_default, bool): 1afghbdecij

792 prompt_kwargs["show_default"] = self.show_default 1afghbdecij

793 

794 return _click.termui.prompt( 1afghbdecij

795 self.prompt, 

796 # Use ``None`` to inform the prompt() function to reiterate until a valid 

797 # value is provided by the user if we have no default. 

798 default=default, 

799 type=self.type_descriptor.annotation, 

800 hide_input=self.hide_input, 

801 show_choices=self.show_choices, 

802 confirmation_prompt=self.confirmation_prompt, 

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

804 **prompt_kwargs, 

805 ) 

806 

807 def resolve_envvar_value(self, ctx: _click.Context) -> str | None: 1afghbdecij

808 rv = super().resolve_envvar_value(ctx) 1afghbdecij

809 

810 if rv is not None: 1afghbdecij

811 return rv 1afghbdecij

812 

813 if ( 1a

814 self.allow_from_autoenv 

815 and ctx.auto_envvar_prefix is not None 

816 and self.name is not None 

817 ): 

818 envvar = f"{ctx.auto_envvar_prefix}_{self.name.upper()}" 1afghbdecij

819 rv = os.environ.get(envvar) 1afghbdecij

820 

821 if rv: 1afghbdecij

822 return rv 1afghbdecij

823 

824 return None 1afghbdecij

825 

826 def consume_value( 1afghbdecij

827 self, ctx: _click.Context, opts: Mapping[str, _click.Parameter] 

828 ) -> tuple[Any, _click.core.ParameterSource]: 

829 """For `Option`, the value can be collected from an interactive prompt 

830 if the option is a flag that needs a value (and the `prompt` property is 

831 set). 

832 

833 Additionally, this method handles flag option that are activated without a 

834 value, in which case the `flag_value` is returned. 

835 """ 

836 value, source = super().consume_value(ctx, opts) 1afghbdecij

837 

838 # The value wasn't set, or used the param's default, prompt for one to the user 

839 # if prompting is enabled. 

840 if ( 

841 source in {None, _click.core.ParameterSource.DEFAULT} 

842 and self.prompt is not None 

843 and (self.required or self.prompt_required) 

844 and not ctx.resilient_parsing 

845 ): 

846 value = self.prompt_for_value(ctx) 1afghbdecij

847 source = _click.core.ParameterSource.PROMPT 1afghbdecij

848 

849 return value, source 1afghbdecij

850 

851 def _get_default_string( 1afghbdecij

852 self, 

853 *, 

854 ctx: _click.Context, 

855 show_default_is_str: bool, 

856 default_value: list[Any] | tuple[Any, ...] | str | Callable[..., Any] | Any, 

857 ) -> str: 

858 return _get_default_string( 1afghbdecij

859 self, 

860 ctx=ctx, 

861 show_default_is_str=show_default_is_str, 

862 default_value=default_value, 

863 ) 

864 

865 def _extract_default_help_str( 1afghbdecij

866 self, *, ctx: _click.Context 

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

868 return _extract_default_help_str(self, ctx=ctx) 1afghbdecij

869 

870 def get_help_record(self, ctx: _click.Context) -> tuple[str, str] | None: 1afghbdecij

871 if self.hidden: 1afghbdecij

872 return None 1afghbdecij

873 

874 any_prefix_is_slash = False 1afghbdecij

875 

876 def _write_opts(opts: Sequence[str]) -> str: 1afghbdecij

877 nonlocal any_prefix_is_slash 

878 

879 rv, any_slashes = _click.formatting.join_options(opts) 1afghbdecij

880 

881 if any_slashes: 1afghbdecij

882 any_prefix_is_slash = True 1afghbdecij

883 

884 if not self.is_flag and not self.count: 1afghbdecij

885 rv += f" {self.display_type_rich(ctx=ctx)}" 1afghbdecij

886 

887 return rv 1afghbdecij

888 

889 rv = [_write_opts(self.opts)] 1afghbdecij

890 

891 if self.secondary_opts: 1afghbdecij

892 rv.append(_write_opts(self.secondary_opts)) 1afghbdecij

893 

894 help = self.help or "" 1afghbdecij

895 extra = [] 1afghbdecij

896 

897 if self.show_envvar: 1afghbdecij

898 envvar = self.envvar 1afghbdecij

899 

900 if envvar is None: 1afghbdecij

901 if ( 1a

902 self.allow_from_autoenv 

903 and ctx.auto_envvar_prefix is not None 

904 and self.name 

905 ): 

906 envvar = f"{ctx.auto_envvar_prefix}_{self.name.upper()}" 1afghbdecij

907 

908 if envvar is not None: 1afghbdecij

909 var_str = ( 1afghbdecij

910 envvar 

911 if isinstance(envvar, str) 

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

913 ) 

914 extra.append(_("env var: {var}").format(var=var_str)) 1afghbdecij

915 

916 default_value = self._extract_default_help_str(ctx=ctx) 1afghbdecij

917 

918 show_default_is_str = isinstance(self.show_default, str) 1afghbdecij

919 

920 if show_default_is_str or ( 1afghbdecij

921 default_value is not None and (self.show_default or ctx.show_default) 

922 ): 

923 default_string = self._get_default_string( 1afghbdecij

924 ctx=ctx, 

925 show_default_is_str=show_default_is_str, 

926 default_value=default_value, 

927 ) 

928 if default_string: 1afghbdecij

929 extra.append(_("default: {default}").format(default=default_string)) 1afghbdecij

930 

931 range_str = self._get_number_range_help_str() 1afghbdecij

932 if range_str: 1afghbdecij

933 extra.append(range_str) 1afghbdecij

934 

935 if self.required: 1afghbdecij

936 extra.append(_("required")) 1afghbdecij

937 

938 if extra: 1afghbdecij

939 extra_str = "; ".join(extra) 1afghbdecij

940 extra_str = f"[{extra_str}]" 1afghbdecij

941 rich_markup_mode = None 1afghbdecij

942 if hasattr(ctx, "obj") and isinstance(ctx.obj, dict): 1afghbdecij

943 rich_markup_mode = ctx.obj.get(MARKUP_MODE_KEY, None) 1afghbdecij

944 if HAS_RICH and rich_markup_mode == "rich": 1afghbdecij

945 # This is needed for when we want to export to HTML 

946 from . import rich_utils 1afghbdecij

947 

948 extra_str = rich_utils.escape_before_html_export(extra_str) 1afghbdecij

949 

950 help = f"{help} {extra_str}" if help else f"{extra_str}" 1afghbdecij

951 

952 return ("; " if any_prefix_is_slash else " / ").join(rv), help 1afghbdecij

953 

954 def display_type_rich(self, ctx: _click.Context) -> str | None: 1afghbdecij

955 if self.metavar is not None: 1afghbdecij

956 return self.metavar 1afghbdecij

957 

958 value_display = self.display_type(ctx) 1afghbdecij

959 if self.nargs != 1 and value_display is not None: 1afghbdecij

960 return str(value_display) + "..." 1afghbdecij

961 return value_display 1afghbdecij

962 

963 def _get_number_range_help_str(self) -> str | None: 1afghbdecij

964 if self.count and self.min == 0 and self.max is None: 1afghbdecij

965 return None 1afghbdecij

966 return describe_number_range(self.min, self.max) 1afghbdecij

967 

968 

969def _typer_format_options( 1afghbdecij

970 self: _click.core.Command, *, ctx: _click.Context, formatter: _click.HelpFormatter 

971) -> None: 

972 args = [] 1afghbdecij

973 opts = [] 1afghbdecij

974 for param in self.get_params(ctx): 1afghbdecij

975 rv = param.get_help_record(ctx) 1afghbdecij

976 if rv is not None: 1afghbdecij

977 if param.param_type_name == "argument": 1afghbdecij

978 args.append(rv) 1afghbdecij

979 elif param.param_type_name == "option": 1afghbdecij

980 opts.append(rv) 1afghbdecij

981 

982 if args: 1afghbdecij

983 with formatter.section(_("Arguments")): 1afghbdecij

984 formatter.write_dl(args) 1afghbdecij

985 if opts: 1afghbdecij

986 with formatter.section(_("Options")): 1afghbdecij

987 formatter.write_dl(opts) 1afghbdecij

988 

989 

990def _typer_main_shell_completion( 1afghbdecij

991 self: _click.core.Command, 

992 *, 

993 ctx_args: MutableMapping[str, Any], 

994 prog_name: str, 

995 complete_var: str | None = None, 

996) -> None: 

997 if complete_var is None: 1afghbdecij

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

999 

1000 instruction = os.environ.get(complete_var) 1afghbdecij

1001 

1002 if not instruction: 1afghbdecij

1003 return 1afghbdecij

1004 

1005 from .completion import shell_complete 1afghbdecij

1006 

1007 rv = shell_complete(self, ctx_args, prog_name, complete_var, instruction) 1afghbdecij

1008 sys.exit(rv) 1afghbdecij

1009 

1010 

1011class TyperCommand(_click.core.Command): 1afghbdecij

1012 def __init__( 1afghbdecij

1013 self, 

1014 name: str | None, 

1015 *, 

1016 context_settings: dict[str, Any] | None = None, 

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

1018 params: list[_click.Parameter] | None = None, 

1019 help: str | None = None, 

1020 epilog: str | None = None, 

1021 short_help: str | None = None, 

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

1023 add_help_option: bool = True, 

1024 no_args_is_help: bool = False, 

1025 hidden: bool = False, 

1026 deprecated: bool = False, 

1027 # Rich settings 

1028 rich_markup_mode: MarkupMode = DEFAULT_MARKUP_MODE, 

1029 rich_help_panel: str | None = None, 

1030 ) -> None: 

1031 super().__init__( 1afghbdecij

1032 name=name, 

1033 context_settings=context_settings, 

1034 callback=callback, 

1035 params=params, 

1036 help=help, 

1037 epilog=epilog, 

1038 short_help=short_help, 

1039 options_metavar=options_metavar, 

1040 add_help_option=add_help_option, 

1041 no_args_is_help=no_args_is_help, 

1042 hidden=hidden, 

1043 deprecated=deprecated, 

1044 ) 

1045 self.rich_markup_mode: MarkupMode = rich_markup_mode 1afghbdecij

1046 self.rich_help_panel = rich_help_panel 1afghbdecij

1047 

1048 def format_options( 1afghbdecij

1049 self, ctx: _click.Context, formatter: _click.HelpFormatter 

1050 ) -> None: 

1051 _typer_format_options(self, ctx=ctx, formatter=formatter) 1afghbdecij

1052 

1053 def _main_shell_completion( 1afghbdecij

1054 self, 

1055 ctx_args: MutableMapping[str, Any], 

1056 prog_name: str, 

1057 complete_var: str | None = None, 

1058 ) -> None: 

1059 _typer_main_shell_completion( 1afghbdecij

1060 self, ctx_args=ctx_args, prog_name=prog_name, complete_var=complete_var 

1061 ) 

1062 

1063 def main( 1afghbdecij

1064 self, 

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

1066 prog_name: str | None = None, 

1067 complete_var: str | None = None, 

1068 standalone_mode: bool = True, 

1069 windows_expand_args: bool = True, 

1070 **extra: Any, 

1071 ) -> Any: 

1072 return _main( 1afghbdecij

1073 self, 

1074 args=args, 

1075 prog_name=prog_name, 

1076 complete_var=complete_var, 

1077 standalone_mode=standalone_mode, 

1078 windows_expand_args=windows_expand_args, 

1079 rich_markup_mode=self.rich_markup_mode, 

1080 **extra, 

1081 ) 

1082 

1083 def format_help(self, ctx: _click.Context, formatter: _click.HelpFormatter) -> None: 1afghbdecij

1084 if not HAS_RICH or self.rich_markup_mode is None: 1afghbdecij

1085 if not hasattr(ctx, "obj") or ctx.obj is None: 1afghbdecij

1086 ctx.ensure_object(dict) 1afghbdecij

1087 if isinstance(ctx.obj, dict): 1afghbdecij

1088 ctx.obj[MARKUP_MODE_KEY] = self.rich_markup_mode 1afghbdecij

1089 return super().format_help(ctx, formatter) 1afghbdecij

1090 from . import rich_utils 1afghbdecij

1091 

1092 return rich_utils.rich_format_help( 1afghbdecij

1093 obj=self, 

1094 ctx=ctx, 

1095 markup_mode=self.rich_markup_mode, 

1096 ) 

1097 

1098 

1099class TyperGroup(_click.Command): 1afghbdecij

1100 allow_extra_args = True 1afghbdecij

1101 allow_interspersed_args = False 1afghbdecij

1102 command_class: type[_click.Command] | None = None 1afghbdecij

1103 group_class: type["TyperGroup"] | type[type] | None = None 1afghbdecij

1104 

1105 def __init__( 1afghbdecij

1106 self, 

1107 *, 

1108 name: str | None = None, 

1109 commands: dict[str, _click.Command] | Sequence[_click.Command] | None = None, 

1110 # Rich settings 

1111 rich_markup_mode: MarkupMode = DEFAULT_MARKUP_MODE, 

1112 rich_help_panel: str | None = None, 

1113 suggest_commands: bool = True, 

1114 # Click settings 

1115 invoke_without_command: bool = False, 

1116 no_args_is_help: bool = False, 

1117 subcommand_metavar: str | None = None, 

1118 result_callback: Callable[..., Any] | None = None, 

1119 **attrs: Any, 

1120 ) -> None: 

1121 super().__init__(name=name, **attrs) 1afghbdecij

1122 self.rich_markup_mode: MarkupMode = rich_markup_mode 1afghbdecij

1123 self.rich_help_panel = rich_help_panel 1afghbdecij

1124 self.suggest_commands = suggest_commands 1afghbdecij

1125 

1126 # copied from Click's init 

1127 if commands is None: 1afghbdecij

1128 commands = {} 1afghbdecij

1129 elif isinstance(commands, Sequence): 1afghbdecij

1130 commands = { 1afghbdecij

1131 c.name: c 

1132 for c in commands 

1133 if isinstance(c, _click.Command) and c.name is not None 

1134 } 

1135 

1136 self.commands = cast(MutableMapping[str, _click.Command], commands) 1afghbdecij

1137 self.no_args_is_help = no_args_is_help 1afghbdecij

1138 self.invoke_without_command = invoke_without_command 1afghbdecij

1139 

1140 if subcommand_metavar is None: 1afghbdecij

1141 subcommand_metavar = "COMMAND [ARGS]..." 1afghbdecij

1142 

1143 self.subcommand_metavar = subcommand_metavar 1afghbdecij

1144 self._result_callback = result_callback 1afghbdecij

1145 

1146 def add_command(self, cmd: _click.Command, name: str | None = None) -> None: 1afghbdecij

1147 name = name or cmd.name 1afghbdecij

1148 if name is None: 1afghbdecij

1149 raise TypeError("Command has no name.") 1afghbdecij

1150 self.commands[name] = cmd 1afghbdecij

1151 

1152 def get_command(self, ctx: _click.Context, cmd_name: str) -> _click.Command | None: 1afghbdecij

1153 return self.commands.get(cmd_name) 1afghbdecij

1154 

1155 def collect_usage_pieces(self, ctx: _click.Context) -> list[str]: 1afghbdecij

1156 rv = super().collect_usage_pieces(ctx) 1afghbdecij

1157 rv.append(self.subcommand_metavar) 1afghbdecij

1158 return rv 1afghbdecij

1159 

1160 def format_commands( 1afghbdecij

1161 self, ctx: _click.Context, formatter: _click.HelpFormatter 

1162 ) -> None: 

1163 commands = [] 1afghbdecij

1164 for subcommand in self.list_commands(ctx): 1afghbdecij

1165 cmd = self.get_command(ctx, subcommand) 1afghbdecij

1166 if cmd is None or cmd.hidden: 1afghbdecij

1167 continue 1afghbdecij

1168 

1169 commands.append((subcommand, cmd)) 1afghbdecij

1170 

1171 # allow for 3 times the default spacing 

1172 if len(commands): 1afghbdecij

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

1174 

1175 rows = [] 1afghbdecij

1176 for subcommand, cmd in commands: 1afghbdecij

1177 assert cmd is not None 1afghbdecij

1178 help = cmd.get_short_help_str(limit) 1afghbdecij

1179 rows.append((subcommand, help)) 1afghbdecij

1180 

1181 if rows: 1afghbdecij

1182 with formatter.section(_("Commands")): 1afghbdecij

1183 formatter.write_dl(rows) 1afghbdecij

1184 

1185 def parse_args(self, ctx: _click.Context, args: list[str]) -> list[str]: 1afghbdecij

1186 if not args and self.no_args_is_help and not ctx.resilient_parsing: 1afghbdecij

1187 raise _click.exceptions.NoArgsIsHelpError(ctx) 1afghbdecij

1188 

1189 rest = super().parse_args(ctx, args) 1afghbdecij

1190 

1191 if rest: 1afghbdecij

1192 ctx._protected_args, ctx.args = rest[:1], rest[1:] 1afghbdecij

1193 

1194 return ctx.args 1afghbdecij

1195 

1196 def invoke(self, ctx: _click.Context) -> Any: 1afghbdecij

1197 def _process_result(value: Any) -> Any: 1afghbdecij

1198 if self._result_callback is not None: 1afghbdecij

1199 value = ctx.invoke(self._result_callback, value, **ctx.params) 1afghbdecij

1200 return value 1afghbdecij

1201 

1202 if not ctx._protected_args: 1afghbdecij

1203 if self.invoke_without_command: 1afghbdecij

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

1205 # invoked with the group return value for regular 

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

1207 with ctx: 1afghbdecij

1208 rv = super().invoke(ctx) 1afghbdecij

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

1210 return _process_result(rv) 1afghbdecij

1211 ctx.fail(_("Missing command.")) 1afghbdecij

1212 

1213 # Fetch args back out 

1214 args = [*ctx._protected_args, *ctx.args] 1afghbdecij

1215 ctx.args = [] 1afghbdecij

1216 ctx._protected_args = [] 1afghbdecij

1217 

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

1219 # resources until the result processor has worked. 

1220 with ctx: 1afghbdecij

1221 cmd_name, cmd, args = self.resolve_command(ctx, args) 1afghbdecij

1222 assert cmd is not None 1afghbdecij

1223 ctx.invoked_subcommand = cmd_name 1afghbdecij

1224 super().invoke(ctx) 1afghbdecij

1225 sub_ctx = cmd.make_context(cmd_name, args, parent=ctx) 1afghbdecij

1226 with sub_ctx: 1afghbdecij

1227 return _process_result(sub_ctx.command.invoke(sub_ctx)) 1afghbdecij

1228 

1229 def shell_complete( 1afghbdecij

1230 self, ctx: _click.Context, incomplete: str 

1231 ) -> list[CompletionItem]: 

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

1233 at the names of options, subcommands, and chained 

1234 multi-commands. 

1235 """ 

1236 

1237 results = [ 1afghbdecij

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

1239 for name, command in _click.core._complete_visible_commands(ctx, incomplete) 

1240 ] 

1241 results.extend(super().shell_complete(ctx, incomplete)) 1afghbdecij

1242 return results 1afghbdecij

1243 

1244 def format_options( 1afghbdecij

1245 self, ctx: _click.Context, formatter: _click.HelpFormatter 

1246 ) -> None: 

1247 _typer_format_options(self, ctx=ctx, formatter=formatter) 1afghbdecij

1248 self.format_commands(ctx, formatter) 1afghbdecij

1249 

1250 def _main_shell_completion( 1afghbdecij

1251 self, 

1252 ctx_args: MutableMapping[str, Any], 

1253 prog_name: str, 

1254 complete_var: str | None = None, 

1255 ) -> None: 

1256 _typer_main_shell_completion( 1afghbdecij

1257 self, ctx_args=ctx_args, prog_name=prog_name, complete_var=complete_var 

1258 ) 

1259 

1260 def _click_resolve_command( 1afghbdecij

1261 self, ctx: _click.Context, args: list[str] 

1262 ) -> tuple[str | None, _click.Command | None, list[str]]: 

1263 cmd_name = args[0] 1afghbdecij

1264 original_cmd_name = cmd_name 1afghbdecij

1265 

1266 # Get the command 

1267 cmd = self.get_command(ctx, cmd_name) 1afghbdecij

1268 

1269 if cmd is None and ctx.token_normalize_func is not None: 1afghbdecij

1270 cmd_name = ctx.token_normalize_func(cmd_name) 1afghbdecij

1271 cmd = self.get_command(ctx, cmd_name) 1afghbdecij

1272 

1273 if cmd is None and not ctx.resilient_parsing: 1afghbdecij

1274 if _split_opt(cmd_name)[0]: 1afghbdecij

1275 self.parse_args(ctx, args) 1afghbdecij

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

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

1278 

1279 def resolve_command( 1afghbdecij

1280 self, ctx: _click.Context, args: list[str] 

1281 ) -> tuple[str | None, _click.Command | None, list[str]]: 

1282 try: 1afghbdecij

1283 return self._click_resolve_command(ctx, args) 1afghbdecij

1284 except _click.exceptions.UsageError as e: 1afghbdecij

1285 if self.suggest_commands: 1afghbdecij

1286 available_commands = list(self.commands.keys()) 1afghbdecij

1287 if available_commands and args: 1afghbdecij

1288 typo = args[0] 1afghbdecij

1289 matches = get_close_matches(typo, available_commands) 1afghbdecij

1290 if matches: 1afghbdecij

1291 suggestions = ", ".join(f"{m!r}" for m in matches) 1afghbdecij

1292 message = e.message.rstrip(".") 1afghbdecij

1293 e.message = f"{message}. Did you mean {suggestions}?" 1afghbdecij

1294 raise 1afghbdecij

1295 

1296 def main( 1afghbdecij

1297 self, 

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

1299 prog_name: str | None = None, 

1300 complete_var: str | None = None, 

1301 standalone_mode: bool = True, 

1302 windows_expand_args: bool = True, 

1303 **extra: Any, 

1304 ) -> Any: 

1305 return _main( 1afghbdecij

1306 self, 

1307 args=args, 

1308 prog_name=prog_name, 

1309 complete_var=complete_var, 

1310 standalone_mode=standalone_mode, 

1311 windows_expand_args=windows_expand_args, 

1312 rich_markup_mode=self.rich_markup_mode, 

1313 **extra, 

1314 ) 

1315 

1316 def format_help(self, ctx: _click.Context, formatter: _click.HelpFormatter) -> None: 1afghbdecij

1317 if not HAS_RICH or self.rich_markup_mode is None: 1afghbdecij

1318 return super().format_help(ctx, formatter) 1afghbdecij

1319 from . import rich_utils 1afghbdecij

1320 

1321 return rich_utils.rich_format_help( 1afghbdecij

1322 obj=self, 

1323 ctx=ctx, 

1324 markup_mode=self.rich_markup_mode, 

1325 ) 

1326 

1327 def list_commands(self, ctx: _click.Context) -> list[str]: 1afghbdecij

1328 """Returns a list of subcommand names, maintaining the original order of creation (cf Issue #933)""" 

1329 return [n for n, c in self.commands.items()] 1afghbdecij