Skip to content
Myr

_termui_impl.py

This file

Path

src/click/_termui_impl.py

762 lines · 24.4 KiB · Python

Last changed by

Fix issues previously type ignored.Andreas Backxbefore adoptionfde47b4

History of this file

Take 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 sys14import time15import typing as t16from gettext import gettext as _17from io import StringIO18from types import TracebackType1920from ._compat import _default_text_stdout21from ._compat import CYGWIN22from ._compat import get_best_encoding23from ._compat import isatty24from ._compat import open_stream25from ._compat import strip_ansi26from ._compat import term_len27from ._compat import WIN28from .exceptions import ClickException29from .utils import echo3031V = t.TypeVar("V")3233if os.name == "nt":34    BEFORE_BAR = "\r"35    AFTER_BAR = "\n"36else:37    BEFORE_BAR = "\r\033[?25l"38    AFTER_BAR = "\033[?25h\n"394041class ProgressBar(t.Generic[V]):42    def __init__(43        self,44        iterable: cabc.Iterable[V] | None,45        length: int | None = None,46        fill_char: str = "#",47        empty_char: str = " ",48        bar_template: str = "%(bar)s",49        info_sep: str = "  ",50        hidden: bool = False,51        show_eta: bool = True,52        show_percent: bool | None = None,53        show_pos: bool = False,54        item_show_func: t.Callable[[V | None], str | None] | None = None,55        label: str | None = None,56        file: t.TextIO | None = None,57        color: bool | None = None,58        update_min_steps: int = 1,59        width: int = 30,60    ) -> None:61        self.fill_char = fill_char62        self.empty_char = empty_char63        self.bar_template = bar_template64        self.info_sep = info_sep65        self.hidden = hidden66        self.show_eta = show_eta67        self.show_percent = show_percent68        self.show_pos = show_pos69        self.item_show_func = item_show_func70        self.label: str = label or ""7172        if file is None:73            file = _default_text_stdout()7475            # There are no standard streams attached to write to. For example,76            # pythonw on Windows.77            if file is None:78                file = StringIO()7980        self.file = file81        self.color = color82        self.update_min_steps = update_min_steps83        self._completed_intervals = 084        self.width: int = width85        self.autowidth: bool = width == 08687        if length is None:88            from operator import length_hint8990            length = length_hint(iterable, -1)9192            if length == -1:93                length = None94        if iterable is None:95            if length is None:96                raise TypeError("iterable or length is required")97            iterable = t.cast("cabc.Iterable[V]", range(length))98        self.iter: cabc.Iterable[V] = iter(iterable)99        self.length = length100        self.pos = 0101        self.avg: list[float] = []102        self.last_eta: float103        self.start: float104        self.start = self.last_eta = time.time()105        self.eta_known: bool = False106        self.finished: bool = False107        self.max_width: int | None = None108        self.entered: bool = False109        self.current_item: V | None = None110        self._is_atty = isatty(self.file)111        self._last_line: str | None = None112113    def __enter__(self) -> ProgressBar[V]:114        self.entered = True115        self.render_progress()116        return self117118    def __exit__(119        self,120        exc_type: type[BaseException] | None,121        exc_value: BaseException | None,122        tb: TracebackType | None,123    ) -> None:124        self.render_finish()125126    def __iter__(self) -> cabc.Iterator[V]:127        if not self.entered:128            raise RuntimeError("You need to use progress bars in a with block.")129        self.render_progress()130        return self.generator()131132    def __next__(self) -> V:133        # Iteration is defined in terms of a generator function,134        # returned by iter(self); use that to define next(). This works135        # because `self.iter` is an iterable consumed by that generator,136        # so it is re-entry safe. Calling `next(self.generator())`137        # twice works and does "what you want".138        return next(iter(self))139140    def render_finish(self) -> None:141        if self.hidden or not self._is_atty:142            return143        self.file.write(AFTER_BAR)144        self.file.flush()145146    @property147    def pct(self) -> float:148        if self.finished:149            return 1.0150        return min(self.pos / (float(self.length or 1) or 1), 1.0)151152    @property153    def time_per_iteration(self) -> float:154        if not self.avg:155            return 0.0156        return sum(self.avg) / float(len(self.avg))157158    @property159    def eta(self) -> float:160        if self.length is not None and not self.finished:161            return self.time_per_iteration * (self.length - self.pos)162        return 0.0163164    def format_eta(self) -> str:165        if self.eta_known:166            t = int(self.eta)167            seconds = t % 60168            t //= 60169            minutes = t % 60170            t //= 60171            hours = t % 24172            t //= 24173            if t > 0:174                return f"{t}d {hours:02}:{minutes:02}:{seconds:02}"175            else:176                return f"{hours:02}:{minutes:02}:{seconds:02}"177        return ""178179    def format_pos(self) -> str:180        pos = str(self.pos)181        if self.length is not None:182            pos += f"/{self.length}"183        return pos184185    def format_pct(self) -> str:186        return f"{int(self.pct * 100): 4}%"[1:]187188    def format_bar(self) -> str:189        if self.length is not None:190            bar_length = int(self.pct * self.width)191            bar = self.fill_char * bar_length192            bar += self.empty_char * (self.width - bar_length)193        elif self.finished:194            bar = self.fill_char * self.width195        else:196            chars = list(self.empty_char * (self.width or 1))197            if self.time_per_iteration != 0:198                chars[199                    int(200                        (math.cos(self.pos * self.time_per_iteration) / 2.0 + 0.5)201                        * self.width202                    )203                ] = self.fill_char204            bar = "".join(chars)205        return bar206207    def format_progress_line(self) -> str:208        show_percent = self.show_percent209210        info_bits = []211        if self.length is not None and show_percent is None:212            show_percent = not self.show_pos213214        if self.show_pos:215            info_bits.append(self.format_pos())216        if show_percent:217            info_bits.append(self.format_pct())218        if self.show_eta and self.eta_known and not self.finished:219            info_bits.append(self.format_eta())220        if self.item_show_func is not None:221            item_info = self.item_show_func(self.current_item)222            if item_info is not None:223                info_bits.append(item_info)224225        return (226            self.bar_template227            % {228                "label": self.label,229                "bar": self.format_bar(),230                "info": self.info_sep.join(info_bits),231            }232        ).rstrip()233234    def render_progress(self) -> None:235        import shutil236237        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            old_width = self.width251            self.width = 0252            clutter_length = term_len(self.format_progress_line())253            new_width = max(0, shutil.get_terminal_size().columns - clutter_length)254            if new_width < old_width and self.max_width is not None:255                buf.append(BEFORE_BAR)256                buf.append(" " * self.max_width)257                self.max_width = new_width258            self.width = new_width259260        clear_width = self.width261        if self.max_width is not None:262            clear_width = self.max_width263264        buf.append(BEFORE_BAR)265        line = self.format_progress_line()266        line_len = term_len(line)267        if self.max_width is None or self.max_width < line_len:268            self.max_width = line_len269270        buf.append(line)271        buf.append(" " * (clear_width - line_len))272        line = "".join(buf)273        # Render the line only if it changed.274275        if line != self._last_line:276            self._last_line = line277            echo(line, file=self.file, color=self.color, nl=False)278            self.file.flush()279280    def make_step(self, n_steps: int) -> None:281        self.pos += n_steps282        if self.length is not None and self.pos >= self.length:283            self.finished = True284285        if (time.time() - self.last_eta) < 1.0:286            return287288        self.last_eta = time.time()289290        # self.avg is a rolling list of length <= 7 of steps where steps are291        # defined as time elapsed divided by the total progress through292        # self.length.293        if self.pos:294            step = (time.time() - self.start) / self.pos295        else:296            step = time.time() - self.start297298        self.avg = self.avg[-6:] + [step]299300        self.eta_known = self.length is not None301302    def update(self, n_steps: int, current_item: V | None = None) -> None:303        """Update the progress bar by advancing a specified number of304        steps, and optionally set the ``current_item`` for this new305        position.306307        :param n_steps: Number of steps to advance.308        :param current_item: Optional item to set as ``current_item``309            for the updated position.310311        .. versionchanged:: 8.0312            Added the ``current_item`` optional parameter.313314        .. versionchanged:: 8.0315            Only render when the number of steps meets the316            ``update_min_steps`` threshold.317        """318        if current_item is not None:319            self.current_item = current_item320321        self._completed_intervals += n_steps322323        if self._completed_intervals >= self.update_min_steps:324            self.make_step(self._completed_intervals)325            self.render_progress()326            self._completed_intervals = 0327328    def finish(self) -> None:329        self.eta_known = False330        self.current_item = None331        self.finished = True332333    def generator(self) -> cabc.Iterator[V]:334        """Return a generator which yields the items added to the bar335        during construction, and updates the progress bar *after* the336        yielded block returns.337        """338        # WARNING: the iterator interface for `ProgressBar` relies on339        # this and only works because this is a simple generator which340        # doesn't create or manage additional state. If this function341        # changes, the impact should be evaluated both against342        # `iter(bar)` and `next(bar)`. `next()` in particular may call343        # `self.generator()` repeatedly, and this must remain safe in344        # order for that interface to work.345        if not self.entered:346            raise RuntimeError("You need to use progress bars in a with block.")347348        if not self._is_atty:349            yield from self.iter350        else:351            for rv in self.iter:352                self.current_item = rv353354                # This allows show_item_func to be updated before the355                # item is processed. Only trigger at the beginning of356                # the update interval.357                if self._completed_intervals == 0:358                    self.render_progress()359360                yield rv361                self.update(1)362363            self.finish()364            self.render_progress()365366367def pager(generator: cabc.Iterable[str], color: bool | None = None) -> None:368    """Decide what method to use for paging through text."""369    stdout = _default_text_stdout()370371    # There are no standard streams attached to write to. For example,372    # pythonw on Windows.373    if stdout is None:374        stdout = StringIO()375376    if not isatty(sys.stdin) or not isatty(stdout):377        return _nullpager(stdout, generator, color)378    pager_cmd = (os.environ.get("PAGER", None) or "").strip()379    if pager_cmd:380        if WIN:381            return _tempfilepager(generator, pager_cmd, color)382        return _pipepager(generator, pager_cmd, color)383    if os.environ.get("TERM") in ("dumb", "emacs"):384        return _nullpager(stdout, generator, color)385    if WIN or sys.platform.startswith("os2"):386        return _tempfilepager(generator, "more <", color)387    if hasattr(os, "system") and os.system("(less) 2>/dev/null") == 0:388        return _pipepager(generator, "less", color)389390    import tempfile391392    fd, filename = tempfile.mkstemp()393    os.close(fd)394    try:395        if hasattr(os, "system") and os.system(f'more "{filename}"') == 0:396            return _pipepager(generator, "more", color)397        return _nullpager(stdout, generator, color)398    finally:399        os.unlink(filename)400401402def _pipepager(generator: cabc.Iterable[str], cmd: str, color: bool | None) -> None:403    """Page through text by feeding it to another program.  Invoking a404    pager through this might support colors.405    """406    import subprocess407408    env = dict(os.environ)409410    # If we're piping to less we might support colors under the411    # condition that412    cmd_detail = cmd.rsplit("/", 1)[-1].split()413    if color is None and cmd_detail[0] == "less":414        less_flags = f"{os.environ.get('LESS', '')}{' '.join(cmd_detail[1:])}"415        if not less_flags:416            env["LESS"] = "-R"417            color = True418        elif "r" in less_flags or "R" in less_flags:419            color = True420421    c = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE, env=env)422    stdin = t.cast(t.BinaryIO, c.stdin)423    encoding = get_best_encoding(stdin)424    try:425        for text in generator:426            if not color:427                text = strip_ansi(text)428429            stdin.write(text.encode(encoding, "replace"))430    except BrokenPipeError:431        # In case the pager exited unexpectedly, ignore the broken pipe error.432        pass433    except Exception as e:434        # In case there is an exception we want to close the pager immediately435        # and let the caller handle it.436        # Otherwise the pager will keep running, and the user may not notice437        # the error message, or worse yet it may leave the terminal in a broken state.438        c.terminate()439        raise e440    finally:441        # We must close stdin and wait for the pager to exit before we continue442        try:443            stdin.close()444        # Close implies flush, so it might throw a BrokenPipeError if the pager445        # process exited already.446        except BrokenPipeError:447            pass448449        # Less doesn't respect ^C, but catches it for its own UI purposes (aborting450        # search or other commands inside less).451        #452        # That means when the user hits ^C, the parent process (click) terminates,453        # but less is still alive, paging the output and messing up the terminal.454        #455        # If the user wants to make the pager exit on ^C, they should set456        # `LESS='-K'`. It's not our decision to make.457        while True:458            try:459                c.wait()460            except KeyboardInterrupt:461                pass462            else:463                break464465466def _tempfilepager(generator: cabc.Iterable[str], cmd: str, color: bool | None) -> None:467    """Page through text by invoking a program on a temporary file."""468    import tempfile469470    fd, filename = tempfile.mkstemp()471    # TODO: This never terminates if the passed generator never terminates.472    text = "".join(generator)473    if not color:474        text = strip_ansi(text)475    encoding = get_best_encoding(sys.stdout)476    with open_stream(filename, "wb")[0] as f:477        f.write(text.encode(encoding))478    try:479        os.system(f'{cmd} "{filename}"')480    finally:481        os.close(fd)482        os.unlink(filename)483484485def _nullpager(486    stream: t.TextIO, generator: cabc.Iterable[str], color: bool | None487) -> None:488    """Simply print unformatted text.  This is the ultimate fallback."""489    for text in generator:490        if not color:491            text = strip_ansi(text)492        stream.write(text)493494495class Editor:496    def __init__(497        self,498        editor: str | None = None,499        env: cabc.Mapping[str, str] | None = None,500        require_save: bool = True,501        extension: str = ".txt",502    ) -> None:503        self.editor = editor504        self.env = env505        self.require_save = require_save506        self.extension = extension507508    def get_editor(self) -> str:509        if self.editor is not None:510            return self.editor511        for key in "VISUAL", "EDITOR":512            rv = os.environ.get(key)513            if rv:514                return rv515        if WIN:516            return "notepad"517        for editor in "sensible-editor", "vim", "nano":518            if os.system(f"which {editor} >/dev/null 2>&1") == 0:519                return editor520        return "vi"521522    def edit_files(self, filenames: cabc.Iterable[str]) -> None:523        import subprocess524525        editor = self.get_editor()526        environ: dict[str, str] | None = None527528        if self.env:529            environ = os.environ.copy()530            environ.update(self.env)531532        exc_filename = " ".join(f'"{filename}"' for filename in filenames)533534        try:535            c = subprocess.Popen(536                args=f"{editor} {exc_filename}", env=environ, shell=True537            )538            exit_code = c.wait()539            if exit_code != 0:540                raise ClickException(541                    _("{editor}: Editing failed").format(editor=editor)542                )543        except OSError as e:544            raise ClickException(545                _("{editor}: Editing failed: {e}").format(editor=editor, e=e)546            ) from e547548    def edit(self, text: t.AnyStr | None) -> t.AnyStr | None:549        import tempfile550551        if not text:552            data = b""553        elif isinstance(text, (bytes, bytearray)):554            data = text555        else:556            if text and not text.endswith("\n"):557                text += "\n"558559            if WIN:560                data = text.replace("\n", "\r\n").encode("utf-8-sig")561            else:562                data = text.encode("utf-8")563564        fd, name = tempfile.mkstemp(prefix="editor-", suffix=self.extension)565        f: t.BinaryIO566567        try:568            with os.fdopen(fd, "wb") as f:569                f.write(data)570571            # If the filesystem resolution is 1 second, like Mac OS572            # 10.12 Extended, or 2 seconds, like FAT32, and the editor573            # closes very fast, require_save can fail. Set the modified574            # time to be 2 seconds in the past to work around this.575            os.utime(name, (os.path.getatime(name), os.path.getmtime(name) - 2))576            # Depending on the resolution, the exact value might not be577            # recorded, so get the new recorded value.578            timestamp = os.path.getmtime(name)579580            self.edit_files((name,))581582            if self.require_save and os.path.getmtime(name) == timestamp:583                return None584585            with open(name, "rb") as f:586                rv = f.read()587588            if isinstance(text, (bytes, bytearray)):589                return rv590591            return rv.decode("utf-8-sig").replace("\r\n", "\n")  # type: ignore592        finally:593            os.unlink(name)594595596def open_url(url: str, wait: bool = False, locate: bool = False) -> int:597    import subprocess598599    def _unquote_file(url: str) -> str:600        from urllib.parse import unquote601602        if url.startswith("file://"):603            url = unquote(url[7:])604605        return url606607    if sys.platform == "darwin":608        args = ["open"]609        if wait:610            args.append("-W")611        if locate:612            args.append("-R")613        args.append(_unquote_file(url))614        null = open("/dev/null", "w")615        try:616            return subprocess.Popen(args, stderr=null).wait()617        finally:618            null.close()619    elif WIN:620        if locate:621            url = _unquote_file(url.replace('"', ""))622            args = f'explorer /select,"{url}"'623        else:624            url = url.replace('"', "")625            wait_str = "/WAIT" if wait else ""626            args = f'start {wait_str} "" "{url}"'627        return os.system(args)628    elif CYGWIN:629        if locate:630            url = os.path.dirname(_unquote_file(url).replace('"', ""))631            args = f'cygstart "{url}"'632        else:633            url = url.replace('"', "")634            wait_str = "-w" if wait else ""635            args = f'cygstart {wait_str} "{url}"'636        return os.system(args)637638    try:639        if locate:640            url = os.path.dirname(_unquote_file(url)) or "."641        else:642            url = _unquote_file(url)643        c = subprocess.Popen(["xdg-open", url])644        if wait:645            return c.wait()646        return 0647    except OSError:648        if url.startswith(("http://", "https://")) and not locate and not wait:649            import webbrowser650651            webbrowser.open(url)652            return 0653        return 1654655656def _translate_ch_to_exc(ch: str) -> None:657    if ch == "\x03":658        raise KeyboardInterrupt()659660    if ch == "\x04" and not WIN:  # Unix-like, Ctrl+D661        raise EOFError()662663    if ch == "\x1a" and WIN:  # Windows, Ctrl+Z664        raise EOFError()665666    return None667668669if WIN:670    import msvcrt671672    @contextlib.contextmanager673    def raw_terminal() -> cabc.Iterator[int]:674        yield -1675676    def getchar(echo: bool) -> str:677        # The function `getch` will return a bytes object corresponding to678        # the pressed character. Since Windows 10 build 1803, it will also679        # return \x00 when called a second time after pressing a regular key.680        #681        # `getwch` does not share this probably-bugged behavior. Moreover, it682        # returns a Unicode object by default, which is what we want.683        #684        # Either of these functions will return \x00 or \xe0 to indicate685        # a special key, and you need to call the same function again to get686        # the "rest" of the code. The fun part is that \u00e0 is687        # "latin small letter a with grave", so if you type that on a French688        # keyboard, you _also_ get a \xe0.689        # E.g., consider the Up arrow. This returns \xe0 and then \x48. The690        # resulting Unicode string reads as "a with grave" + "capital H".691        # This is indistinguishable from when the user actually types692        # "a with grave" and then "capital H".693        #694        # When \xe0 is returned, we assume it's part of a special-key sequence695        # and call `getwch` again, but that means that when the user types696        # the \u00e0 character, `getchar` doesn't return until a second697        # character is typed.698        # The alternative is returning immediately, but that would mess up699        # cross-platform handling of arrow keys and others that start with700        # \xe0. Another option is using `getch`, but then we can't reliably701        # read non-ASCII characters, because return values of `getch` are702        # limited to the current 8-bit codepage.703        #704        # Anyway, Click doesn't claim to do this Right(tm), and using `getwch`705        # is doing the right thing in more situations than with `getch`.706        func: t.Callable[[], str]707708        if echo:709            func = msvcrt.getwche  # type: ignore710        else:711            func = msvcrt.getwch  # type: ignore712713        rv = func()714715        if rv in ("\x00", "\xe0"):716            # \x00 and \xe0 are control characters that indicate special key,717            # see above.718            rv += func()719720        _translate_ch_to_exc(rv)721        return rv722723else:724    import termios725    import tty726727    @contextlib.contextmanager728    def raw_terminal() -> cabc.Iterator[int]:729        f: t.TextIO | None730        fd: int731732        if not isatty(sys.stdin):733            f = open("/dev/tty")734            fd = f.fileno()735        else:736            fd = sys.stdin.fileno()737            f = None738739        try:740            old_settings = termios.tcgetattr(fd)741742            try:743                tty.setraw(fd)744                yield fd745            finally:746                termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)747                sys.stdout.flush()748749                if f is not None:750                    f.close()751        except termios.error:752            pass753754    def getchar(echo: bool) -> str:755        with raw_terminal() as fd:756            ch = os.read(fd, 32).decode(get_best_encoding(sys.stdin), "replace")757758            if echo and isatty(sys.stdout):759                sys.stdout.write(ch)760761            _translate_ch_to_exc(ch)762            return ch