termui.py 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014
  1. from __future__ import annotations
  2. import collections.abc as cabc
  3. import inspect
  4. import io
  5. import itertools
  6. import os
  7. import re
  8. import sys
  9. import typing as t
  10. from contextlib import AbstractContextManager
  11. from contextlib import redirect_stdout
  12. from gettext import gettext as _
  13. from . import _compat
  14. from ._compat import isatty
  15. from ._compat import strip_ansi
  16. from .exceptions import Abort
  17. from .exceptions import UsageError
  18. from .globals import resolve_color_default
  19. from .types import Choice
  20. from .types import convert_type
  21. from .types import ParamType
  22. from .utils import _LazyFile
  23. from .utils import echo
  24. if t.TYPE_CHECKING:
  25. from ._termui_impl import ProgressBar
  26. V = t.TypeVar("V")
  27. # The prompt functions to use. The doc tools currently override these
  28. # functions to customize how they work.
  29. visible_prompt_func: t.Callable[[str], str] = input
  30. _ansi_colors = {
  31. "black": 30,
  32. "red": 31,
  33. "green": 32,
  34. "yellow": 33,
  35. "blue": 34,
  36. "magenta": 35,
  37. "cyan": 36,
  38. "white": 37,
  39. "reset": 39,
  40. "bright_black": 90,
  41. "bright_red": 91,
  42. "bright_green": 92,
  43. "bright_yellow": 93,
  44. "bright_blue": 94,
  45. "bright_magenta": 95,
  46. "bright_cyan": 96,
  47. "bright_white": 97,
  48. }
  49. _ansi_reset_all = "\033[0m"
  50. _HIDDEN_INPUT_MASK = "'***'"
  51. def _mask_hidden_input(message: str, value: str) -> str:
  52. """Replace occurrences of ``value`` in ``message`` with a fixed mask.
  53. Both ``repr(value)`` (the form built-in :class:`ParamType` errors use
  54. via ``{value!r}``) and the raw value are masked. The raw-value pass
  55. uses word-boundary lookarounds so a substring like ``"1"`` does not
  56. match inside ``"10"``, and ``"ent"`` does not match inside
  57. ``"Authentication"``. The empty string is skipped to avoid matching
  58. at every boundary.
  59. """
  60. message = message.replace(repr(value), _HIDDEN_INPUT_MASK)
  61. if value:
  62. message = re.sub(
  63. rf"(?<!\w){re.escape(value)}(?!\w)", _HIDDEN_INPUT_MASK, message
  64. )
  65. return message
  66. def hidden_prompt_func(prompt: str) -> str:
  67. import getpass
  68. return getpass.getpass(prompt)
  69. def _readline_prompt(func: t.Callable[[str], str], text: str, err: bool) -> str:
  70. """Call a prompt function, passing the full prompt so readline can
  71. handle line editing and cursor positioning correctly.
  72. The prompt is handed to *func* (such as :func:`input`) rather than
  73. written through :func:`echo`, so it has to strip ANSI color and style
  74. codes itself when the destination stream does not support them. Without
  75. this the prompt would keep codes that :func:`echo` removes from the
  76. rest of the output.
  77. """
  78. stream = sys.stderr if err else sys.stdout
  79. # Look up ``should_strip_ansi`` on the module so that ``CliRunner``,
  80. # which patches it there during test isolation, is honored.
  81. if _compat.should_strip_ansi(stream, resolve_color_default()):
  82. text = strip_ansi(text)
  83. if err:
  84. with redirect_stdout(sys.stderr):
  85. return func(text)
  86. return func(text)
  87. def _build_prompt(
  88. text: str,
  89. suffix: str,
  90. show_default: bool | str = False,
  91. default: object | None = None,
  92. show_choices: bool = True,
  93. type: object | None = None,
  94. ) -> str:
  95. prompt = text
  96. if type is not None and show_choices and isinstance(type, Choice):
  97. prompt += f" ({', '.join(map(str, type.choices))})"
  98. default_preview = ""
  99. if show_default:
  100. if isinstance(show_default, str):
  101. default_preview = f" [({show_default})]"
  102. elif default is not None:
  103. default_preview = f" [{_format_default(default)}]"
  104. return f"{prompt}{default_preview}{suffix}"
  105. def _format_default(default: V) -> V | str:
  106. if isinstance(default, (io.IOBase, _LazyFile)):
  107. name = getattr(default, "name", None)
  108. if name is not None:
  109. return str(name)
  110. return default
  111. @t.overload
  112. def prompt(
  113. text: str,
  114. default: str | None = None,
  115. hide_input: bool = False,
  116. confirmation_prompt: bool | str = False,
  117. type: None = None,
  118. value_proc: None = None,
  119. prompt_suffix: str = ": ",
  120. show_default: bool | str = True,
  121. err: bool = False,
  122. show_choices: bool = True,
  123. ) -> str: ...
  124. @t.overload
  125. def prompt(
  126. text: str,
  127. default: V | str | None = None,
  128. hide_input: bool = False,
  129. confirmation_prompt: bool | str = False,
  130. type: ParamType[V, str] | type[V] | None = None,
  131. value_proc: t.Callable[[str], V] | None = None,
  132. prompt_suffix: str = ": ",
  133. show_default: bool | str = True,
  134. err: bool = False,
  135. show_choices: bool = True,
  136. ) -> V: ...
  137. def prompt(
  138. text: str,
  139. default: V | str | None = None,
  140. hide_input: bool = False,
  141. confirmation_prompt: bool | str = False,
  142. type: ParamType[V, str] | type[V] | None = None,
  143. value_proc: t.Callable[[str], V] | None = None,
  144. prompt_suffix: str = ": ",
  145. show_default: bool | str = True,
  146. err: bool = False,
  147. show_choices: bool = True,
  148. ) -> V:
  149. """Prompts a user for input. This is a convenience function that can
  150. be used to prompt a user for input later.
  151. If the user aborts the input by sending an interrupt signal, this
  152. function will catch it and raise a :exc:`Abort` exception.
  153. :param text: the text to show for the prompt.
  154. :param default: the default value to use if no input happens. If this
  155. is not given it will prompt until it's aborted.
  156. :param hide_input: if this is set to true then the input value will
  157. be hidden.
  158. :param confirmation_prompt: Prompt a second time to confirm the
  159. value. Can be set to a string instead of ``True`` to customize
  160. the message.
  161. :param type: the type to use to check the value against.
  162. :param value_proc: if this parameter is provided it's a function that
  163. is invoked instead of the type conversion to
  164. convert a value.
  165. :param prompt_suffix: a suffix that should be added to the prompt.
  166. :param show_default: shows or hides the default value in the prompt.
  167. If this value is a string, it shows that string
  168. in parentheses instead of the actual value.
  169. :param err: if set to true the file defaults to ``stderr`` instead of
  170. ``stdout``, the same as with echo.
  171. :param show_choices: Show or hide choices if the passed type is a Choice.
  172. For example if type is a Choice of either day or week,
  173. show_choices is true and text is "Group by" then the
  174. prompt will be "Group by (day, week): ".
  175. .. versionchanged:: 8.5.0
  176. Generically typed: the return type is narrowed by ``type``,
  177. ``value_proc``, or ``default`` instead of being ``Any``. Runtime
  178. behavior is unchanged.
  179. .. versionchanged:: 8.3.3
  180. ``show_default`` can be a string to show a custom value instead
  181. of the actual default, matching the help text behavior.
  182. .. versionchanged:: 8.3.1
  183. A space is no longer appended to the prompt.
  184. .. versionadded:: 8.0
  185. ``confirmation_prompt`` can be a custom string.
  186. .. versionadded:: 7.0
  187. Added the ``show_choices`` parameter.
  188. .. versionadded:: 6.0
  189. Added unicode support for cmd.exe on Windows.
  190. .. versionadded:: 4.0
  191. Added the `err` parameter.
  192. """
  193. def prompt_func(text: str) -> str:
  194. f = hidden_prompt_func if hide_input else visible_prompt_func
  195. try:
  196. return _readline_prompt(f, text, err)
  197. except (KeyboardInterrupt, EOFError):
  198. # getpass doesn't print a newline if the user aborts input with ^C.
  199. # Allegedly this behavior is inherited from getpass(3).
  200. # A doc bug has been filed at https://bugs.python.org/issue24711
  201. if hide_input:
  202. echo(None, err=err)
  203. raise Abort() from None
  204. if value_proc is None:
  205. value_proc = convert_type(type, default)
  206. prompt = _build_prompt(
  207. text, prompt_suffix, show_default, default, show_choices, type
  208. )
  209. if confirmation_prompt:
  210. if confirmation_prompt is True:
  211. confirmation_prompt = _("Repeat for confirmation")
  212. confirmation_prompt = _build_prompt(confirmation_prompt, prompt_suffix)
  213. while True:
  214. while True:
  215. value = prompt_func(prompt)
  216. if value:
  217. break
  218. elif default is not None:
  219. # Defaults of any type are accepted and round trip through
  220. # value_proc like typed input, so the annotation is only
  221. # accurate for typed input.
  222. value = t.cast("str", default)
  223. break
  224. try:
  225. result = value_proc(value)
  226. except UsageError as e:
  227. message = _mask_hidden_input(e.message, value) if hide_input else e.message
  228. echo(_("Error: {message}").format(message=message), err=err)
  229. continue
  230. if not confirmation_prompt:
  231. return result
  232. while True:
  233. value2 = prompt_func(confirmation_prompt)
  234. is_empty = not value and not value2
  235. if value2 or is_empty:
  236. break
  237. if value == value2:
  238. return result
  239. echo(_("Error: The two entered values do not match."), err=err)
  240. def confirm(
  241. text: str,
  242. default: bool | None = False,
  243. abort: bool = False,
  244. prompt_suffix: str = ": ",
  245. show_default: bool = True,
  246. err: bool = False,
  247. ) -> bool:
  248. """Prompts for confirmation (yes/no question).
  249. If the user aborts the input by sending a interrupt signal this
  250. function will catch it and raise a :exc:`Abort` exception.
  251. :param text: the question to ask.
  252. :param default: The default value to use when no input is given. If
  253. ``None``, repeat until input is given.
  254. :param abort: if this is set to `True` a negative answer aborts the
  255. exception by raising :exc:`Abort`.
  256. :param prompt_suffix: a suffix that should be added to the prompt.
  257. :param show_default: shows or hides the default value in the prompt.
  258. :param err: if set to true the file defaults to ``stderr`` instead of
  259. ``stdout``, the same as with echo.
  260. .. versionchanged:: 8.3.1
  261. A space is no longer appended to the prompt.
  262. .. versionchanged:: 8.0
  263. Repeat until input is given if ``default`` is ``None``.
  264. .. versionadded:: 4.0
  265. Added the ``err`` parameter.
  266. """
  267. prompt = _build_prompt(
  268. text,
  269. prompt_suffix,
  270. show_default,
  271. "y/n" if default is None else ("Y/n" if default else "y/N"),
  272. )
  273. while True:
  274. try:
  275. value = _readline_prompt(visible_prompt_func, prompt, err).lower().strip()
  276. except (KeyboardInterrupt, EOFError):
  277. raise Abort() from None
  278. if value in ("y", "yes"):
  279. rv = True
  280. elif value in ("n", "no"):
  281. rv = False
  282. elif default is not None and value == "":
  283. rv = default
  284. else:
  285. echo(_("Error: invalid input"), err=err)
  286. continue
  287. break
  288. if abort and not rv:
  289. raise Abort()
  290. return rv
  291. def get_pager_file(
  292. color: bool | None = None,
  293. ) -> t.ContextManager[t.TextIO]:
  294. """Context manager.
  295. Yields a writable file-like object which can be used as an output pager.
  296. .. versionadded:: 8.4.0
  297. :param color: controls if the pager supports ANSI colors or not. The
  298. default is autodetection.
  299. """
  300. from ._termui_impl import get_pager_file
  301. color = resolve_color_default(color)
  302. return get_pager_file(color=color)
  303. def echo_via_pager(
  304. text_or_generator: cabc.Iterable[str] | t.Callable[[], cabc.Iterable[str]] | str,
  305. color: bool | None = None,
  306. ) -> None:
  307. """This function takes a text and shows it via an environment specific
  308. pager on stdout.
  309. .. versionchanged:: 3.0
  310. Added the `color` flag.
  311. :param text_or_generator: the text to page, or alternatively, a
  312. generator emitting the text to page.
  313. :param color: controls if the pager supports ANSI colors or not. The
  314. default is autodetection.
  315. """
  316. if inspect.isgeneratorfunction(text_or_generator):
  317. i = t.cast("t.Callable[[], cabc.Iterable[str]]", text_or_generator)()
  318. elif isinstance(text_or_generator, str):
  319. i = [text_or_generator]
  320. else:
  321. i = iter(t.cast("cabc.Iterable[str]", text_or_generator))
  322. # convert every element of i to a text type if necessary
  323. text_generator = (el if isinstance(el, str) else str(el) for el in i)
  324. with get_pager_file(color=color) as pager:
  325. for text in itertools.chain(text_generator, "\n"):
  326. pager.write(text)
  327. # Flush after each write so a slow generator streams to the pager
  328. # incrementally rather than staying invisible until the pipe buffer
  329. # fills (~8 KB).
  330. pager.flush()
  331. @t.overload
  332. def progressbar(
  333. *,
  334. length: int,
  335. label: str | None = None,
  336. hidden: bool = False,
  337. show_eta: bool = True,
  338. show_percent: bool | None = None,
  339. show_pos: bool = False,
  340. fill_char: str = "#",
  341. empty_char: str = "-",
  342. bar_template: str = "%(label)s [%(bar)s] %(info)s",
  343. info_sep: str = " ",
  344. width: int = 36,
  345. file: t.TextIO | None = None,
  346. color: bool | None = None,
  347. update_min_steps: int = 1,
  348. ) -> ProgressBar[int]: ...
  349. @t.overload
  350. def progressbar(
  351. iterable: cabc.Iterable[V] | None = None,
  352. length: int | None = None,
  353. label: str | None = None,
  354. hidden: bool = False,
  355. show_eta: bool = True,
  356. show_percent: bool | None = None,
  357. show_pos: bool = False,
  358. item_show_func: t.Callable[[V | None], str | None] | None = None,
  359. fill_char: str = "#",
  360. empty_char: str = "-",
  361. bar_template: str = "%(label)s [%(bar)s] %(info)s",
  362. info_sep: str = " ",
  363. width: int = 36,
  364. file: t.TextIO | None = None,
  365. color: bool | None = None,
  366. update_min_steps: int = 1,
  367. ) -> ProgressBar[V]: ...
  368. def progressbar(
  369. iterable: cabc.Iterable[V] | None = None,
  370. length: int | None = None,
  371. label: str | None = None,
  372. hidden: bool = False,
  373. show_eta: bool = True,
  374. show_percent: bool | None = None,
  375. show_pos: bool = False,
  376. item_show_func: t.Callable[[V | None], str | None] | None = None,
  377. fill_char: str = "#",
  378. empty_char: str = "-",
  379. bar_template: str = "%(label)s [%(bar)s] %(info)s",
  380. info_sep: str = " ",
  381. width: int = 36,
  382. file: t.TextIO | None = None,
  383. color: bool | None = None,
  384. update_min_steps: int = 1,
  385. ) -> ProgressBar[V]:
  386. """This function creates an iterable context manager that can be used
  387. to iterate over something while showing a progress bar. It will
  388. either iterate over the `iterable` or `length` items (that are counted
  389. up). While iteration happens, this function will print a rendered
  390. progress bar to the given `file` (defaults to stdout) and will attempt
  391. to calculate remaining time and more. By default, this progress bar
  392. will not be rendered if the file is not a terminal.
  393. The context manager creates the progress bar. When the context
  394. manager is entered the progress bar is already created. With every
  395. iteration over the progress bar, the iterable passed to the bar is
  396. advanced and the bar is updated. When the context manager exits,
  397. a newline is printed and the progress bar is finalized on screen.
  398. Note: The progress bar is currently designed for use cases where the
  399. total progress can be expected to take at least several seconds.
  400. Because of this, the ProgressBar class object won't display
  401. progress that is considered too fast, and progress where the time
  402. between steps is less than a second.
  403. No printing must happen or the progress bar will be unintentionally
  404. destroyed.
  405. Example usage::
  406. with progressbar(items) as bar:
  407. for item in bar:
  408. do_something_with(item)
  409. Alternatively, if no iterable is specified, one can manually update the
  410. progress bar through the `update()` method instead of directly
  411. iterating over the progress bar. The update method accepts the number
  412. of steps to increment the bar with::
  413. with progressbar(length=chunks.total_bytes) as bar:
  414. for chunk in chunks:
  415. process_chunk(chunk)
  416. bar.update(chunks.bytes)
  417. The ``update()`` method also takes an optional value specifying the
  418. ``current_item`` at the new position. This is useful when used
  419. together with ``item_show_func`` to customize the output for each
  420. manual step::
  421. with click.progressbar(
  422. length=total_size,
  423. label='Unzipping archive',
  424. item_show_func=lambda a: a.filename
  425. ) as bar:
  426. for archive in zip_file:
  427. archive.extract()
  428. bar.update(archive.size, archive)
  429. :param iterable: an iterable to iterate over. If not provided the length
  430. is required.
  431. :param length: the number of items to iterate over. By default the
  432. progressbar will attempt to ask the iterator about its
  433. length, which might or might not work. If an iterable is
  434. also provided this parameter can be used to override the
  435. length. If an iterable is not provided the progress bar
  436. will iterate over a range of that length.
  437. :param label: the label to show next to the progress bar.
  438. :param hidden: hide the progressbar. Defaults to ``False``. When no tty is
  439. detected, it will only print the progressbar label. Setting this to
  440. ``False`` also disables that.
  441. :param show_eta: enables or disables the estimated time display. This is
  442. automatically disabled if the length cannot be
  443. determined.
  444. :param show_percent: enables or disables the percentage display. The
  445. default is `True` if the iterable has a length or
  446. `False` if not.
  447. :param show_pos: enables or disables the absolute position display. The
  448. default is `False`.
  449. :param item_show_func: A function called with the current item which
  450. can return a string to show next to the progress bar. If the
  451. function returns ``None`` nothing is shown. The current item can
  452. be ``None``, such as when entering and exiting the bar.
  453. :param fill_char: the character to use to show the filled part of the
  454. progress bar.
  455. :param empty_char: the character to use to show the non-filled part of
  456. the progress bar.
  457. :param bar_template: the format string to use as template for the bar.
  458. The parameters in it are ``label`` for the label,
  459. ``bar`` for the progress bar and ``info`` for the
  460. info section.
  461. :param info_sep: the separator between multiple info items (eta etc.)
  462. :param width: the width of the progress bar in characters, 0 means full
  463. terminal width
  464. :param file: The file to write to. If this is not a terminal then
  465. only the label is printed.
  466. :param color: controls if the terminal supports ANSI colors or not. The
  467. default is autodetection. This is only needed if ANSI
  468. codes are included anywhere in the progress bar output
  469. which is not the case by default.
  470. :param update_min_steps: Render only when this many updates have
  471. completed. This allows tuning for very fast iterators.
  472. .. versionadded:: 8.2
  473. The ``hidden`` argument.
  474. .. versionchanged:: 8.0
  475. Output is shown even if execution time is less than 0.5 seconds.
  476. .. versionchanged:: 8.0
  477. ``item_show_func`` shows the current item, not the previous one.
  478. .. versionchanged:: 8.0
  479. Labels are echoed if the output is not a TTY. Reverts a change
  480. in 7.0 that removed all output.
  481. .. versionadded:: 8.0
  482. The ``update_min_steps`` parameter.
  483. .. versionadded:: 4.0
  484. The ``color`` parameter and ``update`` method.
  485. .. versionadded:: 2.0
  486. """
  487. from ._termui_impl import ProgressBar
  488. color = resolve_color_default(color)
  489. return ProgressBar(
  490. iterable=iterable,
  491. length=length,
  492. hidden=hidden,
  493. show_eta=show_eta,
  494. show_percent=show_percent,
  495. show_pos=show_pos,
  496. item_show_func=item_show_func,
  497. fill_char=fill_char,
  498. empty_char=empty_char,
  499. bar_template=bar_template,
  500. info_sep=info_sep,
  501. file=file,
  502. label=label,
  503. width=width,
  504. color=color,
  505. update_min_steps=update_min_steps,
  506. )
  507. def clear() -> None:
  508. """Clears the terminal screen. This will have the effect of clearing
  509. the whole visible space of the terminal and moving the cursor to the
  510. top left. This does not do anything if not connected to a terminal.
  511. .. versionadded:: 2.0
  512. """
  513. if not isatty(sys.stdout):
  514. return
  515. # ANSI escape \033[2J clears the screen, \033[1;1H moves the cursor
  516. echo("\033[2J\033[1;1H", nl=False)
  517. def _interpret_color(color: int | tuple[int, int, int] | str, offset: int = 0) -> str:
  518. """Interprets a color value and returns the corresponding ANSI code."""
  519. if isinstance(color, str) and color in _ansi_colors:
  520. return str(_ansi_colors[color] + offset)
  521. # bool is an int subclass: without the exclusion, True and False would
  522. # silently render as the palette indices 1 and 0.
  523. elif isinstance(color, int) and not isinstance(color, bool):
  524. if 0 <= color <= 255:
  525. return f"{38 + offset};5;{color:d}"
  526. elif (
  527. isinstance(color, (tuple, list))
  528. and len(color) == 3
  529. and all(
  530. isinstance(c, int) and not isinstance(c, bool) and 0 <= c <= 255
  531. for c in color
  532. )
  533. ):
  534. r, g, b = color
  535. return f"{38 + offset};2;{r:d};{g:d};{b:d}"
  536. raise ValueError(_("Unknown color {colour!r}").format(colour=color))
  537. def style(
  538. text: t.Any,
  539. fg: int | tuple[int, int, int] | str | None = None,
  540. bg: int | tuple[int, int, int] | str | None = None,
  541. bold: bool | None = None,
  542. dim: bool | None = None,
  543. underline: bool | None = None,
  544. overline: bool | None = None,
  545. italic: bool | None = None,
  546. blink: bool | None = None,
  547. reverse: bool | None = None,
  548. strikethrough: bool | None = None,
  549. reset: bool = True,
  550. ) -> str:
  551. """Styles a text with ANSI styles and returns the new string. By
  552. default the styling is self contained which means that at the end
  553. of the string a reset code is issued. This can be prevented by
  554. passing ``reset=False``.
  555. Examples::
  556. click.echo(click.style('Hello World!', fg='green'))
  557. click.echo(click.style('ATTENTION!', blink=True))
  558. click.echo(click.style('Some things', reverse=True, fg='cyan'))
  559. click.echo(click.style('More colors', fg=(255, 12, 128), bg=117))
  560. Supported color names:
  561. * ``black`` (might be a gray)
  562. * ``red``
  563. * ``green``
  564. * ``yellow`` (might be an orange)
  565. * ``blue``
  566. * ``magenta``
  567. * ``cyan``
  568. * ``white`` (might be light gray)
  569. * ``bright_black``
  570. * ``bright_red``
  571. * ``bright_green``
  572. * ``bright_yellow``
  573. * ``bright_blue``
  574. * ``bright_magenta``
  575. * ``bright_cyan``
  576. * ``bright_white``
  577. * ``reset`` (reset the color code only)
  578. If the terminal supports it, color may also be specified as:
  579. - An integer in the interval [0, 255]. The terminal must support
  580. 8-bit/256-color mode.
  581. - An RGB tuple of three integers in [0, 255]. The terminal must
  582. support 24-bit/true-color mode.
  583. See https://en.wikipedia.org/wiki/ANSI_color and
  584. https://gist.github.com/XVilka/8346728 for more information.
  585. :param text: the string to style with ansi codes.
  586. :param fg: if provided this will become the foreground color.
  587. :param bg: if provided this will become the background color.
  588. :param bold: if provided this will enable or disable bold mode.
  589. :param dim: if provided this will enable or disable dim mode. This is
  590. badly supported.
  591. :param underline: if provided this will enable or disable underline.
  592. :param overline: if provided this will enable or disable overline.
  593. :param italic: if provided this will enable or disable italic.
  594. :param blink: if provided this will enable or disable blinking.
  595. :param reverse: if provided this will enable or disable inverse
  596. rendering (foreground becomes background and the
  597. other way round).
  598. :param strikethrough: if provided this will enable or disable
  599. striking through text.
  600. :param reset: by default a reset-all code is added at the end of the
  601. string which means that styles do not carry over. This
  602. can be disabled to compose styles.
  603. .. versionchanged:: 8.5.0
  604. All invalid color values raise :exc:`ValueError`. 256-color index
  605. ``0`` is no longer ignored.
  606. .. versionchanged:: 8.0
  607. A non-string ``message`` is converted to a string.
  608. .. versionchanged:: 8.0
  609. Added support for 256 and RGB color codes.
  610. .. versionchanged:: 8.0
  611. Added the ``strikethrough``, ``italic``, and ``overline``
  612. parameters.
  613. .. versionchanged:: 7.0
  614. Added support for bright colors.
  615. .. versionadded:: 2.0
  616. """
  617. if not isinstance(text, str):
  618. text = str(text)
  619. bits = []
  620. if fg is not None:
  621. bits.append(f"\033[{_interpret_color(fg)}m")
  622. if bg is not None:
  623. bits.append(f"\033[{_interpret_color(bg, 10)}m")
  624. if bold is not None:
  625. bits.append(f"\033[{1 if bold else 22}m")
  626. if dim is not None:
  627. bits.append(f"\033[{2 if dim else 22}m")
  628. if underline is not None:
  629. bits.append(f"\033[{4 if underline else 24}m")
  630. if overline is not None:
  631. bits.append(f"\033[{53 if overline else 55}m")
  632. if italic is not None:
  633. bits.append(f"\033[{3 if italic else 23}m")
  634. if blink is not None:
  635. bits.append(f"\033[{5 if blink else 25}m")
  636. if reverse is not None:
  637. bits.append(f"\033[{7 if reverse else 27}m")
  638. if strikethrough is not None:
  639. bits.append(f"\033[{9 if strikethrough else 29}m")
  640. bits.append(text)
  641. if reset:
  642. bits.append(_ansi_reset_all)
  643. return "".join(bits)
  644. def unstyle(text: str) -> str:
  645. """Removes ANSI styling information from a string. Usually it's not
  646. necessary to use this function as Click's echo function will
  647. automatically remove styling if necessary.
  648. .. versionadded:: 2.0
  649. :param text: the text to remove style information from.
  650. """
  651. return strip_ansi(text)
  652. def secho(
  653. message: t.Any | None = None,
  654. file: t.IO[t.AnyStr] | None = None,
  655. nl: bool = True,
  656. err: bool = False,
  657. color: bool | None = None,
  658. **styles: t.Any,
  659. ) -> None:
  660. """This function combines :func:`echo` and :func:`style` into one
  661. call. As such the following two calls are the same::
  662. click.secho('Hello World!', fg='green')
  663. click.echo(click.style('Hello World!', fg='green'))
  664. All keyword arguments are forwarded to the underlying functions
  665. depending on which one they go with.
  666. Non-string types will be converted to :class:`str`. However,
  667. :class:`bytes` are passed directly to :meth:`echo` without applying
  668. style. If you want to style bytes that represent text, call
  669. :meth:`bytes.decode` first.
  670. .. versionchanged:: 8.0
  671. A non-string ``message`` is converted to a string. Bytes are
  672. passed through without style applied.
  673. .. versionadded:: 2.0
  674. """
  675. if message is not None and not isinstance(message, (bytes, bytearray)):
  676. message = style(message, **styles)
  677. return echo(message, file=file, nl=nl, err=err, color=color)
  678. @t.overload
  679. def edit(
  680. text: bytes | bytearray,
  681. editor: str | None = None,
  682. env: cabc.Mapping[str, str] | None = None,
  683. require_save: bool = False,
  684. extension: str = ".txt",
  685. ) -> bytes | None: ...
  686. @t.overload
  687. def edit(
  688. text: str,
  689. editor: str | None = None,
  690. env: cabc.Mapping[str, str] | None = None,
  691. require_save: bool = True,
  692. extension: str = ".txt",
  693. ) -> str | None: ...
  694. @t.overload
  695. def edit(
  696. text: None = None,
  697. editor: str | None = None,
  698. env: cabc.Mapping[str, str] | None = None,
  699. require_save: bool = True,
  700. extension: str = ".txt",
  701. filename: str
  702. | os.PathLike[str]
  703. | cabc.Iterable[str | os.PathLike[str]]
  704. | None = None,
  705. ) -> None: ...
  706. def edit(
  707. text: str | bytes | bytearray | None = None,
  708. editor: str | None = None,
  709. env: cabc.Mapping[str, str] | None = None,
  710. require_save: bool = True,
  711. extension: str = ".txt",
  712. filename: str
  713. | os.PathLike[str]
  714. | cabc.Iterable[str | os.PathLike[str]]
  715. | None = None,
  716. ) -> str | bytes | bytearray | None:
  717. r"""Edits the given text in the defined editor. If an editor is given
  718. (should be the full path to the executable but the regular operating
  719. system search path is used for finding the executable) it overrides
  720. the detected editor. Optionally, some environment variables can be
  721. used. If the editor is closed without changes, `None` is returned. In
  722. case a file is edited directly the return value is always `None` and
  723. `require_save` and `extension` are ignored.
  724. If the editor cannot be opened a :exc:`UsageError` is raised.
  725. Note for Windows: to simplify cross-platform usage, the newlines are
  726. automatically converted from POSIX to Windows and vice versa. As such,
  727. the message here will have ``\n`` as newline markers.
  728. :param text: the text to edit.
  729. :param editor: optionally the editor to use. Defaults to automatic
  730. detection.
  731. :param env: environment variables to forward to the editor.
  732. :param require_save: if this is true, then not saving in the editor
  733. will make the return value become `None`.
  734. :param extension: the extension to tell the editor about. This defaults
  735. to `.txt` but changing this might change syntax
  736. highlighting.
  737. :param filename: if provided it will edit this file instead of the
  738. provided text contents. It will not use a temporary
  739. file as an indirection in that case. It accepts a path
  740. or any iterable of paths. If the editor supports
  741. editing multiple files at once, a sequence of files may
  742. be passed as well. Invoke `click.file` once per file
  743. instead if multiple files cannot be managed at once or
  744. editing the files serially is desired.
  745. .. versionchanged:: 8.2.0
  746. ``filename`` now accepts any ``Iterable[str]`` in addition to a ``str``
  747. if the ``editor`` supports editing multiple files at once.
  748. .. versionchanged:: 8.5.0
  749. ``filename`` accepts ``os.PathLike`` values in addition to strings.
  750. """
  751. from ._termui_impl import Editor
  752. ed = Editor(editor=editor, env=env, require_save=require_save, extension=extension)
  753. if filename is None:
  754. return ed.edit(text)
  755. if isinstance(filename, (str, os.PathLike)):
  756. filename = (filename,)
  757. ed.edit_files(filenames=filename)
  758. return None
  759. def launch(url: str, wait: bool = False, locate: bool = False) -> int:
  760. """This function launches the given URL (or filename) in the default
  761. viewer application for this file type. If this is an executable, it
  762. might launch the executable in a new session. The return value is
  763. the exit code of the launched application. Usually, ``0`` indicates
  764. success.
  765. Examples::
  766. click.launch('https://click.palletsprojects.com/')
  767. click.launch('/my/downloaded/file', locate=True)
  768. .. versionadded:: 2.0
  769. :param url: URL or filename of the thing to launch.
  770. :param wait: Wait for the program to exit before returning. This
  771. only works if the launched program blocks. In particular,
  772. ``xdg-open`` on Linux does not block.
  773. :param locate: if this is set to `True` then instead of launching the
  774. application associated with the URL it will attempt to
  775. launch a file manager with the file located. This
  776. might have weird effects if the URL does not point to
  777. the filesystem.
  778. """
  779. from ._termui_impl import open_url
  780. return open_url(url, wait=wait, locate=locate)
  781. # If this is provided, getchar() calls into this instead. This is used
  782. # for unittesting purposes.
  783. _getchar: t.Callable[[bool], str] | None = None
  784. def getchar(echo: bool = False) -> str:
  785. """Fetches a single character from the terminal and returns it. This
  786. will always return a unicode character and under certain rare
  787. circumstances this might return more than one character. The
  788. situations which more than one character is returned is when for
  789. whatever reason multiple characters end up in the terminal buffer or
  790. standard input was not actually a terminal.
  791. Note that this will always read from the terminal, even if something
  792. is piped into the standard input.
  793. Note for Windows: in rare cases when typing non-ASCII characters, this
  794. function might wait for a second character and then return both at once.
  795. This is because certain Unicode characters look like special-key markers.
  796. .. versionadded:: 2.0
  797. :param echo: if set to `True`, the character read will also show up on
  798. the terminal. The default is to not show it.
  799. """
  800. global _getchar
  801. if _getchar is None:
  802. from ._termui_impl import getchar as f
  803. _getchar = f
  804. return _getchar(echo)
  805. def raw_terminal() -> AbstractContextManager[int]:
  806. from ._termui_impl import raw_terminal as f
  807. return f()
  808. def pause(info: str | None = None, err: bool = False) -> None:
  809. """This command stops execution and waits for the user to press any
  810. key to continue. This is similar to the Windows batch "pause"
  811. command. If the program is not run through a terminal, this command
  812. will instead do nothing.
  813. .. versionadded:: 2.0
  814. .. versionadded:: 4.0
  815. Added the `err` parameter.
  816. :param info: The message to print before pausing. Defaults to
  817. ``"Press any key to continue..."``.
  818. :param err: if set to message goes to ``stderr`` instead of
  819. ``stdout``, the same as with echo.
  820. """
  821. if not isatty(sys.stdin) or not isatty(sys.stdout):
  822. return
  823. if info is None:
  824. info = _("Press any key to continue...")
  825. try:
  826. if info:
  827. echo(info, nl=False, err=err)
  828. try:
  829. getchar()
  830. except (KeyboardInterrupt, EOFError):
  831. pass
  832. finally:
  833. if info:
  834. echo(err=err)