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

144 statements  

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

1import io 1adefbghcij

2from collections.abc import Callable, Iterable 1adefbghcij

3from contextlib import AbstractContextManager 1adefbghcij

4from typing import IO, TYPE_CHECKING, Any, AnyStr, TextIO, TypeVar, overload 1adefbghcij

5 

6from ..exceptions import Abort 1adefbghcij

7from .exceptions import UsageError 1adefbghcij

8from .globals import resolve_color_default 1adefbghcij

9from .utils import LazyFile, echo 1adefbghcij

10 

11if TYPE_CHECKING: 1adefbghcij

12 from ._termui_impl import ProgressBar 

13 

14V = TypeVar("V") 1adefbghcij

15 

16# The prompt functions to use. The doc tools currently override these 

17# functions to customize how they work. 

18visible_prompt_func: Callable[[str], str] = input 1adefbghcij

19 

20_ansi_colors = { 1adefbghcij

21 "black": 30, 

22 "red": 31, 

23 "green": 32, 

24 "yellow": 33, 

25 "blue": 34, 

26 "magenta": 35, 

27 "cyan": 36, 

28 "white": 37, 

29 "reset": 39, 

30 "bright_black": 90, 

31 "bright_red": 91, 

32 "bright_green": 92, 

33 "bright_yellow": 93, 

34 "bright_blue": 94, 

35 "bright_magenta": 95, 

36 "bright_cyan": 96, 

37 "bright_white": 97, 

38} 

39_ansi_reset_all = "\033[0m" 1adefbghcij

40 

41 

42def hidden_prompt_func(prompt: str) -> str: 1adefbghcij

43 import getpass 1adefbghcij

44 

45 return getpass.getpass(prompt) 1adefbghcij

46 

47 

48def _build_prompt( 1adefbghcij

49 text: str, 

50 suffix: str, 

51 show_default: bool = False, 

52 default: Any | None = None, 

53 show_choices: bool = True, 

54 annotation: Any | None = None, 

55) -> str: 

56 # prevent circular imports 

57 from .._param_types import choice_as_str, choice_coercion_annotation 1adefbghcij

58 from ..models import OptionInfo 1adefbghcij

59 

60 prompt = text 1adefbghcij

61 if show_choices and annotation is not None: 1adefbghcij

62 choice = choice_coercion_annotation(annotation, OptionInfo()) 1adefbghcij

63 if choice is not None: 1adefbghcij

64 choices, _ = choice 1adefbghcij

65 prompt += f" ({', '.join(map(choice_as_str, choices))})" 1adefbghcij

66 if default is not None and show_default: 1adefbghcij

67 prompt = f"{prompt} [{_format_default(default)}]" 1adefbghcij

68 return f"{prompt}{suffix}" 1adefbghcij

69 

70 

71def _format_default(default: Any) -> Any: 1adefbghcij

72 if isinstance(default, (io.IOBase, LazyFile)) and hasattr(default, "name"): 1adefbghcij

73 return default.name 1adefbghcij

74 

75 return default 1adefbghcij

76 

77 

78def prompt( 1adefbghcij

79 text: str, 

80 default: Any | None = None, 

81 hide_input: bool = False, 

82 confirmation_prompt: bool | str = False, 

83 type: Any | None = None, 

84 value_proc: Callable[[str], Any] | None = None, 

85 prompt_suffix: str = ": ", 

86 show_default: bool = True, 

87 err: bool = False, 

88 show_choices: bool = True, 

89) -> Any: 

90 """Prompts a user for input. This is a convenience function that can 

91 be used to prompt a user for input later. 

92 

93 If the user aborts the input by sending an interrupt signal, this 

94 function will catch it and raise an `Abort` exception. 

95 """ 

96 

97 def prompt_func(text: str) -> str: 1adefbghcij

98 f = hidden_prompt_func if hide_input else visible_prompt_func 1adefbghcij

99 try: 1adefbghcij

100 # Write the prompt separately so that we get nice 

101 # coloring through colorama on Windows 

102 echo(text[:-1], nl=False, err=err) 1adefbghcij

103 # Echo the last character to stdout to work around an issue where 

104 # readline causes backspace to clear the whole line. 

105 return f(text[-1:]) 1adefbghcij

106 except (KeyboardInterrupt, EOFError): # pragma: no cover 

107 # getpass doesn't print a newline if the user aborts input with ^C. 

108 # Allegedly this behavior is inherited from getpass(3). 

109 # A doc bug has been filed at https://bugs.python.org/issue24711 

110 if hide_input: 

111 echo(None, err=err) 

112 raise Abort() from None 

113 

114 from .._param_types import annotation_from_prompt 1adefbghcij

115 

116 annotation = annotation_from_prompt(type, default) 1adefbghcij

117 if value_proc is None: 1adefbghcij

118 from .._coercion import prompt_value_proc 1adefbghcij

119 

120 value_proc = prompt_value_proc(type, default) 1adefbghcij

121 

122 prompt = _build_prompt( 1adefbghcij

123 text, prompt_suffix, show_default, default, show_choices, annotation 

124 ) 

125 

126 if confirmation_prompt: 1adefbghcij

127 if confirmation_prompt is True: 1adefbghcij

128 confirmation_prompt = "Repeat for confirmation" 1adefbghcij

129 

130 confirmation_prompt = _build_prompt( 1adefbghcij

131 confirmation_prompt, prompt_suffix, annotation=annotation 

132 ) 

133 

134 while True: 1adefbghcij

135 while True: 1adefbghcij

136 value = prompt_func(prompt) 1adefbghcij

137 if value: 1adefbghcij

138 break 1adefbghcij

139 elif default is not None: 1adefbghcij

140 value = default 1adefbghcij

141 break 1adefbghcij

142 try: 1adefbghcij

143 result = value_proc(value) 1adefbghcij

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

145 if hide_input: 1adefbghcij

146 echo("Error: The value you entered was invalid.", err=err) 

147 else: 

148 echo(f"Error: {e.message}", err=err) 1adefbghcij

149 continue 1adefbghcij

150 if not confirmation_prompt: 1adefbghcij

151 return result 1adefbghcij

152 while True: 1adefbghcij

153 value2 = prompt_func(confirmation_prompt) 1adefbghcij

154 is_empty = not value and not value2 1adefbghcij

155 if value2 or is_empty: 1adefbghcij

156 break 1adefbghcij

157 if value == value2: 1adefbghcij

158 return result 1adefbghcij

159 echo("Error: The two entered values do not match.", err=err) 1adefbghcij

160 

161 

162def confirm( 1adefbghcij

163 text: str, 

164 default: bool | None = False, 

165 abort: bool = False, 

166 prompt_suffix: str = ": ", 

167 show_default: bool = True, 

168 err: bool = False, 

169) -> bool: 

170 """Prompts for confirmation (yes/no question). 

171 

172 If the user aborts the input by sending a interrupt signal this 

173 function will catch it and raise an `Abort` exception. 

174 """ 

175 prompt = _build_prompt( 1adefbghcij

176 text, 

177 prompt_suffix, 

178 show_default, 

179 "y/n" if default is None else ("Y/n" if default else "y/N"), 

180 ) 

181 

182 while True: 1adefbghcij

183 try: 1adefbghcij

184 # Write the prompt separately so that we get nice 

185 # coloring through colorama on Windows 

186 echo(prompt[:-1], nl=False, err=err) 1adefbghcij

187 # Echo the last character to stdout to work around an issue where 

188 # readline causes backspace to clear the whole line. 

189 value = visible_prompt_func(prompt[-1:]).lower().strip() 1adefbghcij

190 except (KeyboardInterrupt, EOFError): # pragma: no cover 

191 raise Abort() from None 

192 if value in ("y", "yes"): 1adefbghcij

193 rv = True 1adefbghcij

194 elif value in ("n", "no"): 1adefbghcij

195 rv = False 1adefbghcij

196 elif default is not None and value == "": 1adefbghcij

197 rv = default 1adefbghcij

198 else: # pragma: no cover 

199 echo("Error: invalid input", err=err) 

200 continue 

201 break 1adefbghcij

202 if abort and not rv: 1adefbghcij

203 raise Abort() 1adefbghcij

204 return rv 1adefbghcij

205 

206 

207@overload 1adefbghcij

208def progressbar( 1adefbghcij

209 *, 

210 length: int, 1abc

211 label: str | None = None, 1adefbghcij

212 hidden: bool = False, 1adefbghcij

213 show_eta: bool = True, 1adefbghcij

214 show_percent: bool | None = None, 1adefbghcij

215 show_pos: bool = False, 1adefbghcij

216 fill_char: str = "#", 1adefbghcij

217 empty_char: str = "-", 1adefbghcij

218 bar_template: str = "%(label)s [%(bar)s] %(info)s", 1adefbghcij

219 info_sep: str = " ", 1adefbghcij

220 width: int = 36, 1adefbghcij

221 file: TextIO | None = None, 1adefbghcij

222 color: bool | None = None, 1adefbghcij

223 update_min_steps: int = 1, 1adefbghcij

224) -> "ProgressBar[int]": ... 1abc

225 

226 

227@overload 1adefbghcij

228def progressbar( 1adefbghcij

229 iterable: Iterable[V] | None = None, 1abc

230 length: int | None = None, 1abc

231 label: str | None = None, 1abc

232 hidden: bool = False, 1abc

233 show_eta: bool = True, 1abc

234 show_percent: bool | None = None, 1abc

235 show_pos: bool = False, 1abc

236 item_show_func: Callable[[V | None], str | None] | None = None, 1abc

237 fill_char: str = "#", 1abc

238 empty_char: str = "-", 1abc

239 bar_template: str = "%(label)s [%(bar)s] %(info)s", 1abc

240 info_sep: str = " ", 1abc

241 width: int = 36, 1abc

242 file: TextIO | None = None, 1abc

243 color: bool | None = None, 1abc

244 update_min_steps: int = 1, 1abc

245) -> "ProgressBar[V]": ... 1abc

246 

247 

248def progressbar( 1adefbghcij

249 iterable: Iterable[V] | None = None, 

250 length: int | None = None, 

251 label: str | None = None, 

252 hidden: bool = False, 

253 show_eta: bool = True, 

254 show_percent: bool | None = None, 

255 show_pos: bool = False, 

256 item_show_func: Callable[[V | None], str | None] | None = None, 

257 fill_char: str = "#", 

258 empty_char: str = "-", 

259 bar_template: str = "%(label)s [%(bar)s] %(info)s", 

260 info_sep: str = " ", 

261 width: int = 36, 

262 file: TextIO | None = None, 

263 color: bool | None = None, 

264 update_min_steps: int = 1, 

265) -> "ProgressBar[V]": 

266 """This function creates an iterable context manager that can be used 

267 to iterate over something while showing a progress bar. It will 

268 either iterate over the `iterable` or `length` items (that are counted 

269 up). While iteration happens, this function will print a rendered 

270 progress bar to the given `file` (defaults to stdout) and will attempt 

271 to calculate remaining time and more. By default, this progress bar 

272 will not be rendered if the file is not a terminal. 

273 

274 The context manager creates the progress bar. When the context 

275 manager is entered the progress bar is already created. With every 

276 iteration over the progress bar, the iterable passed to the bar is 

277 advanced and the bar is updated. When the context manager exits, 

278 a newline is printed and the progress bar is finalized on screen. 

279 

280 Note: The progress bar is currently designed for use cases where the 

281 total progress can be expected to take at least several seconds. 

282 Because of this, the ProgressBar class object won't display 

283 progress that is considered too fast, and progress where the time 

284 between steps is less than a second. 

285 

286 No printing must happen or the progress bar will be unintentionally 

287 destroyed. 

288 """ 

289 from ._termui_impl import ProgressBar 1adefbghcij

290 

291 color = resolve_color_default(color) 1adefbghcij

292 return ProgressBar( 1adefbghcij

293 iterable=iterable, 

294 length=length, 

295 hidden=hidden, 

296 show_eta=show_eta, 

297 show_percent=show_percent, 

298 show_pos=show_pos, 

299 item_show_func=item_show_func, 

300 fill_char=fill_char, 

301 empty_char=empty_char, 

302 bar_template=bar_template, 

303 info_sep=info_sep, 

304 file=file, 

305 label=label, 

306 width=width, 

307 color=color, 

308 update_min_steps=update_min_steps, 

309 ) 

310 

311 

312def _interpret_color(color: int | tuple[int, int, int] | str, offset: int = 0) -> str: 1adefbghcij

313 if isinstance(color, int): 1adefbghcij

314 return f"{38 + offset};5;{color:d}" 1adefbghcij

315 

316 if isinstance(color, (tuple, list)): 1adefbghcij

317 r, g, b = color 1adefbghcij

318 return f"{38 + offset};2;{r:d};{g:d};{b:d}" 1adefbghcij

319 

320 return str(_ansi_colors[color] + offset) 1adefbghcij

321 

322 

323def style( 1adefbghcij

324 text: Any, 

325 fg: int | tuple[int, int, int] | str | None = None, 

326 bg: int | tuple[int, int, int] | str | None = None, 

327 bold: bool | None = None, 

328 dim: bool | None = None, 

329 underline: bool | None = None, 

330 overline: bool | None = None, 

331 italic: bool | None = None, 

332 blink: bool | None = None, 

333 reverse: bool | None = None, 

334 strikethrough: bool | None = None, 

335 reset: bool = True, 

336) -> str: 

337 """Styles a text with ANSI styles and returns the new string. By 

338 default the styling is self contained which means that at the end 

339 of the string a reset code is issued. This can be prevented by 

340 passing ``reset=False``. 

341 """ 

342 if not isinstance(text, str): 1adefbghcij

343 text = str(text) 1adefbghcij

344 

345 bits = [] 1adefbghcij

346 

347 if fg: 1adefbghcij

348 try: 1adefbghcij

349 bits.append(f"\033[{_interpret_color(fg)}m") 1adefbghcij

350 except KeyError: 1adefbghcij

351 raise TypeError(f"Unknown color {fg!r}") from None 1adefbghcij

352 

353 if bg: 1adefbghcij

354 try: 1adefbghcij

355 bits.append(f"\033[{_interpret_color(bg, 10)}m") 1adefbghcij

356 except KeyError: 1adefbghcij

357 raise TypeError(f"Unknown color {bg!r}") from None 1adefbghcij

358 

359 if bold is not None: 1adefbghcij

360 bits.append(f"\033[{1 if bold else 22}m") 1adefbghcij

361 if dim is not None: 1adefbghcij

362 bits.append(f"\033[{2 if dim else 22}m") 1adefbghcij

363 if underline is not None: 1adefbghcij

364 bits.append(f"\033[{4 if underline else 24}m") 1adefbghcij

365 if overline is not None: 1adefbghcij

366 bits.append(f"\033[{53 if overline else 55}m") 1adefbghcij

367 if italic is not None: 1adefbghcij

368 bits.append(f"\033[{3 if italic else 23}m") 1adefbghcij

369 if blink is not None: 1adefbghcij

370 bits.append(f"\033[{5 if blink else 25}m") 1adefbghcij

371 if reverse is not None: 1adefbghcij

372 bits.append(f"\033[{7 if reverse else 27}m") 1adefbghcij

373 if strikethrough is not None: 1adefbghcij

374 bits.append(f"\033[{9 if strikethrough else 29}m") 1adefbghcij

375 bits.append(text) 1adefbghcij

376 if reset: 1adefbghcij

377 bits.append(_ansi_reset_all) 1adefbghcij

378 return "".join(bits) 1adefbghcij

379 

380 

381def secho( 1adefbghcij

382 message: Any | None = None, 

383 file: IO[AnyStr] | None = None, 

384 nl: bool = True, 

385 err: bool = False, 

386 color: bool | None = None, 

387 **styles: Any, 

388) -> None: 

389 """This function combines `echo` and `style` into one call.""" 

390 if message is not None and not isinstance(message, (bytes, bytearray)): 1adefbghcij

391 message = style(message, **styles) 1adefbghcij

392 

393 return echo(message, file=file, nl=nl, err=err, color=color) 1adefbghcij

394 

395 

396def launch(url: str, wait: bool = False, locate: bool = False) -> int: 1adefbghcij

397 """This function launches the given URL (or filename) in the default 

398 viewer application for this file type. If this is an executable, it 

399 might launch the executable in a new session. The return value is 

400 the exit code of the launched application. Usually, ``0`` indicates 

401 success. 

402 """ 

403 from ._termui_impl import open_url 1adefbghcij

404 

405 return open_url(url, wait=wait, locate=locate) 1adefbghcij

406 

407 

408# If this is provided, getchar() calls into this instead. This is used 

409# for unittesting purposes. 

410_getchar: Callable[[bool], str] | None = None 1adefbghcij

411 

412 

413def getchar(echo: bool = False) -> str: 1adefbghcij

414 """Fetches a single character from the terminal and returns it. This 

415 will always return a unicode character and under certain rare 

416 circumstances this might return more than one character. The 

417 situations which more than one character is returned is when for 

418 whatever reason multiple characters end up in the terminal buffer or 

419 standard input was not actually a terminal. 

420 

421 Note that this will always read from the terminal, even if something 

422 is piped into the standard input. 

423 

424 Note for Windows: in rare cases when typing non-ASCII characters, this 

425 function might wait for a second character and then return both at once. 

426 This is because certain Unicode characters look like special-key markers. 

427 """ 

428 global _getchar 

429 

430 if _getchar is None: 1adefbghcij

431 from ._termui_impl import getchar as f 1adefbghcij

432 

433 _getchar = f 1adefbghcij

434 

435 return _getchar(echo) 1adefbghcij

436 

437 

438def raw_terminal() -> AbstractContextManager[int]: 1adefbghcij

439 from ._termui_impl import raw_terminal as f 1adefbghcij

440 

441 return f() 1adefbghcij