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