_termui_impl.py
This file
Path
src/click/_termui_impl.py
871 lines · 27.5 KiB · Python
Last changed by
Merge branch 'stable' into unset-in-default-mapRowlando13before adoptionc07bb93
History of this fileTake it
1"""2This module contains implementations for the termui module. To keep the3import time of Click down, some infrequently used functionality is4placed in this module and only imported as needed.5"""67from __future__ import annotations89import collections.abc as cabc10import contextlib11import math12import os13import shlex14import sys15import time16import typing as t17from gettext import gettext as _18from io import StringIO19from pathlib import Path20from types import TracebackType2122from ._compat import _default_text_stdout23from ._compat import CYGWIN24from ._compat import get_best_encoding25from ._compat import isatty26from ._compat import open_stream27from ._compat import strip_ansi28from ._compat import term_len29from ._compat import WIN30from .exceptions import ClickException31from .utils import echo3233V = t.TypeVar("V")3435if os.name == "nt":36 BEFORE_BAR = "\r"37 AFTER_BAR = "\n"38else:39 BEFORE_BAR = "\r\033[?25l"40 AFTER_BAR = "\033[?25h\n"414243class ProgressBar(t.Generic[V]):44 def __init__(45 self,46 iterable: cabc.Iterable[V] | None,47 length: int | None = None,48 fill_char: str = "#",49 empty_char: str = " ",50 bar_template: str = "%(bar)s",51 info_sep: str = " ",52 hidden: bool = False,53 show_eta: bool = True,54 show_percent: bool | None = None,55 show_pos: bool = False,56 item_show_func: t.Callable[[V | None], str | None] | None = None,57 label: str | None = None,58 file: t.TextIO | None = None,59 color: bool | None = None,60 update_min_steps: int = 1,61 width: int = 30,62 ) -> None:63 self.fill_char = fill_char64 self.empty_char = empty_char65 self.bar_template = bar_template66 self.info_sep = info_sep67 self.hidden = hidden68 self.show_eta = show_eta69 self.show_percent = show_percent70 self.show_pos = show_pos71 self.item_show_func = item_show_func72 self.label: str = label or ""7374 if file is None:75 file = _default_text_stdout()7677 # There are no standard streams attached to write to. For example,78 # pythonw on Windows.79 if file is None:80 file = StringIO()8182 self.file = file83 self.color = color84 self.update_min_steps = update_min_steps85 self._completed_intervals = 086 self.width: int = width87 self.autowidth: bool = width == 08889 if length is None:90 from operator import length_hint9192 length = length_hint(iterable, -1)9394 if length == -1:95 length = None96 if iterable is None:97 if length is None:98 raise TypeError("iterable or length is required")99 iterable = t.cast("cabc.Iterable[V]", range(length))100 self.iter: cabc.Iterable[V] = iter(iterable)101 self.length = length102 self.pos: int = 0103 self.avg: list[float] = []104 self.last_eta: float105 self.start: float106 self.start = self.last_eta = time.time()107 self.eta_known: bool = False108 self.finished: bool = False109 self.max_width: int | None = None110 self.entered: bool = False111 self.current_item: V | None = None112 self._is_atty = isatty(self.file)113 self._last_line: str | None = None114115 def __enter__(self) -> ProgressBar[V]:116 self.entered = True117 self.render_progress()118 return self119120 def __exit__(121 self,122 exc_type: type[BaseException] | None,123 exc_value: BaseException | None,124 tb: TracebackType | None,125 ) -> None:126 self.render_finish()127128 def __iter__(self) -> cabc.Iterator[V]:129 if not self.entered:130 raise RuntimeError("You need to use progress bars in a with block.")131 self.render_progress()132 return self.generator()133134 def __next__(self) -> V:135 # Iteration is defined in terms of a generator function,136 # returned by iter(self); use that to define next(). This works137 # because `self.iter` is an iterable consumed by that generator,138 # so it is re-entry safe. Calling `next(self.generator())`139 # twice works and does "what you want".140 return next(iter(self))141142 def render_finish(self) -> None:143 if self.hidden or not self._is_atty:144 return145 self.file.write(AFTER_BAR)146 self.file.flush()147148 @property149 def pct(self) -> float:150 if self.finished:151 return 1.0152 return min(self.pos / (float(self.length or 1) or 1), 1.0)153154 @property155 def time_per_iteration(self) -> float:156 if not self.avg:157 return 0.0158 return sum(self.avg) / float(len(self.avg))159160 @property161 def eta(self) -> float:162 if self.length is not None and not self.finished:163 return self.time_per_iteration * (self.length - self.pos)164 return 0.0165166 def format_eta(self) -> str:167 if self.eta_known:168 t = int(self.eta)169 seconds = t % 60170 t //= 60171 minutes = t % 60172 t //= 60173 hours = t % 24174 t //= 24175 if t > 0:176 return f"{t}d {hours:02}:{minutes:02}:{seconds:02}"177 else:178 return f"{hours:02}:{minutes:02}:{seconds:02}"179 return ""180181 def format_pos(self) -> str:182 pos = str(self.pos)183 if self.length is not None:184 pos += f"/{self.length}"185 return pos186187 def format_pct(self) -> str:188 return f"{int(self.pct * 100): 4}%"[1:]189190 def format_bar(self) -> str:191 if self.length is not None:192 bar_length = int(self.pct * self.width)193 bar = self.fill_char * bar_length194 bar += self.empty_char * (self.width - bar_length)195 elif self.finished:196 bar = self.fill_char * self.width197 else:198 chars = list(self.empty_char * (self.width or 1))199 if self.time_per_iteration != 0:200 chars[201 int(202 (math.cos(self.pos * self.time_per_iteration) / 2.0 + 0.5)203 * self.width204 )205 ] = self.fill_char206 bar = "".join(chars)207 return bar208209 def format_progress_line(self) -> str:210 show_percent = self.show_percent211212 info_bits = []213 if self.length is not None and show_percent is None:214 show_percent = not self.show_pos215216 if self.show_pos:217 info_bits.append(self.format_pos())218 if show_percent:219 info_bits.append(self.format_pct())220 if self.show_eta and self.eta_known and not self.finished:221 info_bits.append(self.format_eta())222 if self.item_show_func is not None:223 item_info = self.item_show_func(self.current_item)224 if item_info is not None:225 info_bits.append(item_info)226227 return (228 self.bar_template229 % {230 "label": self.label,231 "bar": self.format_bar(),232 "info": self.info_sep.join(info_bits),233 }234 ).rstrip()235236 def render_progress(self) -> None:237 if self.hidden:238 return239240 if not self._is_atty:241 # Only output the label once if the output is not a TTY.242 if self._last_line != self.label:243 self._last_line = self.label244 echo(self.label, file=self.file, color=self.color)245 return246247 buf = []248 # Update width in case the terminal has been resized249 if self.autowidth:250 import shutil251252 old_width = self.width253 self.width = 0254 clutter_length = term_len(self.format_progress_line())255 new_width = max(0, shutil.get_terminal_size().columns - clutter_length)256 if new_width < old_width and self.max_width is not None:257 buf.append(BEFORE_BAR)258 buf.append(" " * self.max_width)259 self.max_width = new_width260 self.width = new_width261262 clear_width = self.width263 if self.max_width is not None:264 clear_width = self.max_width265266 buf.append(BEFORE_BAR)267 line = self.format_progress_line()268 line_len = term_len(line)269 if self.max_width is None or self.max_width < line_len:270 self.max_width = line_len271272 buf.append(line)273 buf.append(" " * (clear_width - line_len))274 line = "".join(buf)275 # Render the line only if it changed.276277 if line != self._last_line:278 self._last_line = line279 echo(line, file=self.file, color=self.color, nl=False)280 self.file.flush()281282 def make_step(self, n_steps: int) -> None:283 self.pos += n_steps284 if self.length is not None and self.pos >= self.length:285 self.finished = True286287 if (time.time() - self.last_eta) < 1.0:288 return289290 self.last_eta = time.time()291292 # self.avg is a rolling list of length <= 7 of steps where steps are293 # defined as time elapsed divided by the total progress through294 # self.length.295 if self.pos:296 step = (time.time() - self.start) / self.pos297 else:298 step = time.time() - self.start299300 self.avg = self.avg[-6:] + [step]301302 self.eta_known = self.length is not None303304 def update(self, n_steps: int, current_item: V | None = None) -> None:305 """Update the progress bar by advancing a specified number of306 steps, and optionally set the ``current_item`` for this new307 position.308309 :param n_steps: Number of steps to advance.310 :param current_item: Optional item to set as ``current_item``311 for the updated position.312313 .. versionchanged:: 8.0314 Added the ``current_item`` optional parameter.315316 .. versionchanged:: 8.0317 Only render when the number of steps meets the318 ``update_min_steps`` threshold.319 """320 if current_item is not None:321 self.current_item = current_item322323 self._completed_intervals += n_steps324325 if self._completed_intervals >= self.update_min_steps:326 self.make_step(self._completed_intervals)327 self.render_progress()328 self._completed_intervals = 0329330 def finish(self) -> None:331 self.eta_known = False332 self.current_item = None333 self.finished = True334335 def generator(self) -> cabc.Iterator[V]:336 """Return a generator which yields the items added to the bar337 during construction, and updates the progress bar *after* the338 yielded block returns.339 """340 # WARNING: the iterator interface for `ProgressBar` relies on341 # this and only works because this is a simple generator which342 # doesn't create or manage additional state. If this function343 # changes, the impact should be evaluated both against344 # `iter(bar)` and `next(bar)`. `next()` in particular may call345 # `self.generator()` repeatedly, and this must remain safe in346 # order for that interface to work.347 if not self.entered:348 raise RuntimeError("You need to use progress bars in a with block.")349350 if not self._is_atty:351 yield from self.iter352 else:353 for rv in self.iter:354 self.current_item = rv355356 # This allows show_item_func to be updated before the357 # item is processed. Only trigger at the beginning of358 # the update interval.359 if self._completed_intervals == 0:360 self.render_progress()361362 yield rv363 self.update(1)364365 self.finish()366 self.render_progress()367368369def pager(generator: cabc.Iterable[str], color: bool | None = None) -> None:370 """Decide what method to use for paging through text."""371 stdout = _default_text_stdout()372373 # There are no standard streams attached to write to. For example,374 # pythonw on Windows.375 if stdout is None:376 stdout = StringIO()377378 if not isatty(sys.stdin) or not isatty(stdout):379 return _nullpager(stdout, generator, color)380381 # Split using POSIX mode (the default) so that quote characters are382 # stripped from tokens and quoted Windows paths are preserved.383 # posix=False was rejected (PR #1477) because it retains quotes in384 # tokens, and the shlex.quote approach was also reverted (PR #1543).385 # See also: issue #1026, PR #2775.386 pager_cmd_parts = shlex.split(os.environ.get("PAGER", ""))387 if pager_cmd_parts:388 if WIN:389 if _tempfilepager(generator, pager_cmd_parts, color):390 return391 elif _pipepager(generator, pager_cmd_parts, color):392 return393394 if os.environ.get("TERM") in ("dumb", "emacs"):395 return _nullpager(stdout, generator, color)396 if (WIN or sys.platform.startswith("os2")) and _tempfilepager(397 generator, ["more"], color398 ):399 return400 if _pipepager(generator, ["less"], color):401 return402403 import tempfile404405 fd, filename = tempfile.mkstemp()406 os.close(fd)407 try:408 if _pipepager(generator, ["more"], color):409 return410 return _nullpager(stdout, generator, color)411 finally:412 os.unlink(filename)413414415def _pipepager(416 generator: cabc.Iterable[str], cmd_parts: list[str], color: bool | None417) -> bool:418 """Page through text by feeding it to another program.419420 Invokes the pager via :class:`subprocess.Popen` with an ``argv`` list421 produced by :func:`shlex.split`. The command is resolved to an absolute422 path with :func:`shutil.which` as recommended by the423 :mod:`subprocess` docs for Windows compatibility.424425 Invoking a pager through this might support colors: if piping to426 ``less`` and the user hasn't decided on colors, ``LESS=-R`` is set427 automatically.428429 Returns ``True`` if the command was found and executed, ``False``430 otherwise so another pager can be attempted.431 """432 # Split the command into the invoked CLI and its parameters.433 if not cmd_parts:434 return False435436 import shutil437438 cmd = cmd_parts[0]439 cmd_params = cmd_parts[1:]440441 cmd_filepath = shutil.which(cmd)442 if not cmd_filepath:443 return False444445 # Produces a normalized absolute path string.446 # multi-call binaries such as busybox derive their identity from the symlink447 # less -> busybox. resolve() causes them to misbehave. (eg. less becomes busybox)448 cmd_path = Path(cmd_filepath).absolute()449 cmd_name = cmd_path.name450451 import subprocess452453 # Make a local copy of the environment to not affect the global one.454 env = dict(os.environ)455456 # If we're piping to less and the user hasn't decided on colors, we enable457 # them by default we find the -R flag in the command line arguments.458 if color is None and cmd_name == "less":459 less_flags = f"{os.environ.get('LESS', '')}{' '.join(cmd_params)}"460 if not less_flags:461 env["LESS"] = "-R"462 color = True463 elif "r" in less_flags or "R" in less_flags:464 color = True465466 c = subprocess.Popen(467 [str(cmd_path)] + cmd_params,468 shell=False,469 stdin=subprocess.PIPE,470 env=env,471 errors="replace",472 text=True,473 )474 assert c.stdin is not None475 try:476 for text in generator:477 if not color:478 text = strip_ansi(text)479480 c.stdin.write(text)481 except BrokenPipeError:482 # In case the pager exited unexpectedly, ignore the broken pipe error.483 pass484 except Exception as e:485 # In case there is an exception we want to close the pager immediately486 # and let the caller handle it.487 # Otherwise the pager will keep running, and the user may not notice488 # the error message, or worse yet it may leave the terminal in a broken state.489 c.terminate()490 raise e491 finally:492 # We must close stdin and wait for the pager to exit before we continue493 try:494 c.stdin.close()495 # Close implies flush, so it might throw a BrokenPipeError if the pager496 # process exited already.497 except BrokenPipeError:498 pass499500 # Less doesn't respect ^C, but catches it for its own UI purposes (aborting501 # search or other commands inside less).502 #503 # That means when the user hits ^C, the parent process (click) terminates,504 # but less is still alive, paging the output and messing up the terminal.505 #506 # If the user wants to make the pager exit on ^C, they should set507 # `LESS='-K'`. It's not our decision to make.508 while True:509 try:510 c.wait()511 except KeyboardInterrupt:512 pass513 else:514 break515516 return True517518519def _tempfilepager(520 generator: cabc.Iterable[str], cmd_parts: list[str], color: bool | None521) -> bool:522 """Page through text by invoking a program on a temporary file.523524 Used as the primary pager strategy on Windows (where piping to525 ``more`` adds spurious ``\\r\\n``), and as a fallback on other526 platforms. The command is resolved to an absolute path with527 :func:`shutil.which`.528529 Returns ``True`` if the command was found and executed, ``False``530 otherwise so another pager can be attempted.531 """532 # Split the command into the invoked CLI and its parameters.533 if not cmd_parts:534 return False535536 import shutil537538 cmd = cmd_parts[0]539540 cmd_filepath = shutil.which(cmd)541 if not cmd_filepath:542 return False543 # Produces a normalized absolute path string.544 # multi-call binaries such as busybox derive their identity from the symlink545 # less -> busybox. resolve() causes them to misbehave. (eg. less becomes busybox)546 cmd_path = Path(cmd_filepath).absolute()547548 import subprocess549 import tempfile550551 fd, filename = tempfile.mkstemp()552 # TODO: This never terminates if the passed generator never terminates.553 text = "".join(generator)554 if not color:555 text = strip_ansi(text)556 encoding = get_best_encoding(sys.stdout)557 with open_stream(filename, "wb")[0] as f:558 f.write(text.encode(encoding))559 try:560 subprocess.call([str(cmd_path), filename])561 except OSError:562 # Command not found563 pass564 finally:565 os.close(fd)566 os.unlink(filename)567568 return True569570571def _nullpager(572 stream: t.TextIO, generator: cabc.Iterable[str], color: bool | None573) -> None:574 """Simply print unformatted text. This is the ultimate fallback."""575 for text in generator:576 if not color:577 text = strip_ansi(text)578 stream.write(text)579580581class Editor:582 def __init__(583 self,584 editor: str | None = None,585 env: cabc.Mapping[str, str] | None = None,586 require_save: bool = True,587 extension: str = ".txt",588 ) -> None:589 self.editor = editor590 self.env = env591 self.require_save = require_save592 self.extension = extension593594 def get_editor(self) -> str:595 if self.editor is not None:596 return self.editor597 for key in "VISUAL", "EDITOR":598 rv = os.environ.get(key)599 if rv:600 return rv601 if WIN:602 return "notepad"603604 from shutil import which605606 for editor in "sensible-editor", "vim", "nano":607 if which(editor) is not None:608 return editor609 return "vi"610611 def edit_files(self, filenames: cabc.Iterable[str]) -> None:612 """Open files in the user's editor."""613 import shlex614 import subprocess615616 editor = self.get_editor()617 environ: dict[str, str] | None = None618619 if self.env:620 environ = os.environ.copy()621 environ.update(self.env)622623 try:624 # Split in POSIX mode (the default) for the same reasons as625 # in pager(): strips quotes from tokens and preserves quoted626 # Windows paths. See issue #1026, PR #1477.627 c = subprocess.Popen(628 args=shlex.split(editor) + list(filenames),629 env=environ,630 )631 exit_code = c.wait()632 if exit_code != 0:633 raise ClickException(634 _("{editor}: Editing failed").format(editor=editor)635 )636 except OSError as e:637 raise ClickException(638 _("{editor}: Editing failed: {e}").format(editor=editor, e=e)639 ) from e640641 @t.overload642 def edit(self, text: bytes | bytearray) -> bytes | None: ...643644 # We cannot know whether or not the type expected is str or bytes when None645 # is passed, so str is returned as that was what was done before.646 @t.overload647 def edit(self, text: str | None) -> str | None: ...648649 def edit(self, text: str | bytes | bytearray | None) -> str | bytes | None:650 import tempfile651652 if text is None:653 data: bytes | bytearray = b""654 elif isinstance(text, (bytes, bytearray)):655 data = text656 else:657 if text and not text.endswith("\n"):658 text += "\n"659660 if WIN:661 data = text.replace("\n", "\r\n").encode("utf-8-sig")662 else:663 data = text.encode("utf-8")664665 fd, name = tempfile.mkstemp(prefix="editor-", suffix=self.extension)666 f: t.BinaryIO667668 try:669 with os.fdopen(fd, "wb") as f:670 f.write(data)671672 # If the filesystem resolution is 1 second, like Mac OS673 # 10.12 Extended, or 2 seconds, like FAT32, and the editor674 # closes very fast, require_save can fail. Set the modified675 # time to be 2 seconds in the past to work around this.676 os.utime(name, (os.path.getatime(name), os.path.getmtime(name) - 2))677 # Depending on the resolution, the exact value might not be678 # recorded, so get the new recorded value.679 timestamp = os.path.getmtime(name)680681 self.edit_files((name,))682683 if self.require_save and os.path.getmtime(name) == timestamp:684 return None685686 with open(name, "rb") as f:687 rv = f.read()688689 if isinstance(text, (bytes, bytearray)):690 return rv691692 return rv.decode("utf-8-sig").replace("\r\n", "\n")693 finally:694 os.unlink(name)695696697def open_url(url: str, wait: bool = False, locate: bool = False) -> int:698 import subprocess699700 def _unquote_file(url: str) -> str:701 from urllib.parse import unquote702703 if url.startswith("file://"):704 url = unquote(url[7:])705706 return url707708 if sys.platform == "darwin":709 args = ["open"]710 if wait:711 args.append("-W")712 if locate:713 args.append("-R")714 args.append(_unquote_file(url))715 null = open("/dev/null", "w")716 try:717 return subprocess.Popen(args, stderr=null).wait()718 finally:719 null.close()720 elif WIN:721 if locate:722 url = _unquote_file(url)723 args = ["explorer", f"/select,{url}"]724 else:725 args = ["start"]726 if wait:727 args.append("/WAIT")728 args.append("")729 args.append(url)730 try:731 return subprocess.call(args)732 except OSError:733 # Command not found734 return 127735 elif CYGWIN:736 if locate:737 url = _unquote_file(url)738 args = ["cygstart", os.path.dirname(url)]739 else:740 args = ["cygstart"]741 if wait:742 args.append("-w")743 args.append(url)744 try:745 return subprocess.call(args)746 except OSError:747 # Command not found748 return 127749750 try:751 if locate:752 url = os.path.dirname(_unquote_file(url)) or "."753 else:754 url = _unquote_file(url)755 c = subprocess.Popen(["xdg-open", url])756 if wait:757 return c.wait()758 return 0759 except OSError:760 if url.startswith(("http://", "https://")) and not locate and not wait:761 import webbrowser762763 webbrowser.open(url)764 return 0765 return 1766767768def _translate_ch_to_exc(ch: str) -> None:769 if ch == "\x03":770 raise KeyboardInterrupt()771772 if ch == "\x04" and not WIN: # Unix-like, Ctrl+D773 raise EOFError()774775 if ch == "\x1a" and WIN: # Windows, Ctrl+Z776 raise EOFError()777778779if sys.platform == "win32":780 import msvcrt781782 @contextlib.contextmanager783 def raw_terminal() -> cabc.Iterator[int]:784 yield -1785786 def getchar(echo: bool) -> str:787 # The function `getch` will return a bytes object corresponding to788 # the pressed character. Since Windows 10 build 1803, it will also789 # return \x00 when called a second time after pressing a regular key.790 #791 # `getwch` does not share this probably-bugged behavior. Moreover, it792 # returns a Unicode object by default, which is what we want.793 #794 # Either of these functions will return \x00 or \xe0 to indicate795 # a special key, and you need to call the same function again to get796 # the "rest" of the code. The fun part is that \u00e0 is797 # "latin small letter a with grave", so if you type that on a French798 # keyboard, you _also_ get a \xe0.799 # E.g., consider the Up arrow. This returns \xe0 and then \x48. The800 # resulting Unicode string reads as "a with grave" + "capital H".801 # This is indistinguishable from when the user actually types802 # "a with grave" and then "capital H".803 #804 # When \xe0 is returned, we assume it's part of a special-key sequence805 # and call `getwch` again, but that means that when the user types806 # the \u00e0 character, `getchar` doesn't return until a second807 # character is typed.808 # The alternative is returning immediately, but that would mess up809 # cross-platform handling of arrow keys and others that start with810 # \xe0. Another option is using `getch`, but then we can't reliably811 # read non-ASCII characters, because return values of `getch` are812 # limited to the current 8-bit codepage.813 #814 # Anyway, Click doesn't claim to do this Right(tm), and using `getwch`815 # is doing the right thing in more situations than with `getch`.816817 if echo:818 func = t.cast(t.Callable[[], str], msvcrt.getwche)819 else:820 func = t.cast(t.Callable[[], str], msvcrt.getwch)821822 rv = func()823824 if rv in ("\x00", "\xe0"):825 # \x00 and \xe0 are control characters that indicate special key,826 # see above.827 rv += func()828829 _translate_ch_to_exc(rv)830 return rv831832else:833 import termios834 import tty835836 @contextlib.contextmanager837 def raw_terminal() -> cabc.Iterator[int]:838 f: t.TextIO | None839 fd: int840841 if not isatty(sys.stdin):842 f = open("/dev/tty")843 fd = f.fileno()844 else:845 fd = sys.stdin.fileno()846 f = None847848 try:849 old_settings = termios.tcgetattr(fd)850851 try:852 tty.setraw(fd)853 yield fd854 finally:855 termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)856 sys.stdout.flush()857858 if f is not None:859 f.close()860 except termios.error:861 pass862863 def getchar(echo: bool) -> str:864 with raw_terminal() as fd:865 ch = os.read(fd, 32).decode(get_best_encoding(sys.stdin), "replace")866867 if echo and isatty(sys.stdout):868 sys.stdout.write(ch)869870 _translate_ch_to_exc(ch)871 return ch