Skip to content
Myr

_termui_impl.py

This file

Path

src/click/_termui_impl.py

673 lines · 20.9 KiB · Python

Last changed by

Merge pull request #1050 from giovannipizzi/fix-fast-editDavid Lordbefore adoption97fde8b

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"""6import contextlib7import math8import os9import sys10import time1112from ._compat import _default_text_stdout13from ._compat import CYGWIN14from ._compat import get_best_encoding15from ._compat import isatty16from ._compat import open_stream17from ._compat import strip_ansi18from ._compat import term_len19from ._compat import WIN20from .exceptions import ClickException21from .utils import echo2223if os.name == "nt":24    BEFORE_BAR = "\r"25    AFTER_BAR = "\n"26else:27    BEFORE_BAR = "\r\033[?25l"28    AFTER_BAR = "\033[?25h\n"293031def _length_hint(obj):32    """Returns the length hint of an object."""33    try:34        return len(obj)35    except (AttributeError, TypeError):36        try:37            get_hint = type(obj).__length_hint__38        except AttributeError:39            return None40        try:41            hint = get_hint(obj)42        except TypeError:43            return None44        if hint is NotImplemented or not isinstance(hint, int) or hint < 0:45            return None46        return hint474849class ProgressBar:50    def __init__(51        self,52        iterable,53        length=None,54        fill_char="#",55        empty_char=" ",56        bar_template="%(bar)s",57        info_sep="  ",58        show_eta=True,59        show_percent=None,60        show_pos=False,61        item_show_func=None,62        label=None,63        file=None,64        color=None,65        width=30,66    ):67        self.fill_char = fill_char68        self.empty_char = empty_char69        self.bar_template = bar_template70        self.info_sep = info_sep71        self.show_eta = show_eta72        self.show_percent = show_percent73        self.show_pos = show_pos74        self.item_show_func = item_show_func75        self.label = label or ""76        if file is None:77            file = _default_text_stdout()78        self.file = file79        self.color = color80        self.width = width81        self.autowidth = width == 08283        if length is None:84            length = _length_hint(iterable)85        if iterable is None:86            if length is None:87                raise TypeError("iterable or length is required")88            iterable = range(length)89        self.iter = iter(iterable)90        self.length = length91        self.length_known = length is not None92        self.pos = 093        self.avg = []94        self.start = self.last_eta = time.time()95        self.eta_known = False96        self.finished = False97        self.max_width = None98        self.entered = False99        self.current_item = None100        self.is_hidden = not isatty(self.file)101        self._last_line = None102        self.short_limit = 0.5103104    def __enter__(self):105        self.entered = True106        self.render_progress()107        return self108109    def __exit__(self, exc_type, exc_value, tb):110        self.render_finish()111112    def __iter__(self):113        if not self.entered:114            raise RuntimeError("You need to use progress bars in a with block.")115        self.render_progress()116        return self.generator()117118    def __next__(self):119        # Iteration is defined in terms of a generator function,120        # returned by iter(self); use that to define next(). This works121        # because `self.iter` is an iterable consumed by that generator,122        # so it is re-entry safe. Calling `next(self.generator())`123        # twice works and does "what you want".124        return next(iter(self))125126    def is_fast(self):127        return time.time() - self.start <= self.short_limit128129    def render_finish(self):130        if self.is_hidden or self.is_fast():131            return132        self.file.write(AFTER_BAR)133        self.file.flush()134135    @property136    def pct(self):137        if self.finished:138            return 1.0139        return min(self.pos / (float(self.length) or 1), 1.0)140141    @property142    def time_per_iteration(self):143        if not self.avg:144            return 0.0145        return sum(self.avg) / float(len(self.avg))146147    @property148    def eta(self):149        if self.length_known and not self.finished:150            return self.time_per_iteration * (self.length - self.pos)151        return 0.0152153    def format_eta(self):154        if self.eta_known:155            t = int(self.eta)156            seconds = t % 60157            t //= 60158            minutes = t % 60159            t //= 60160            hours = t % 24161            t //= 24162            if t > 0:163                return f"{t}d {hours:02}:{minutes:02}:{seconds:02}"164            else:165                return f"{hours:02}:{minutes:02}:{seconds:02}"166        return ""167168    def format_pos(self):169        pos = str(self.pos)170        if self.length_known:171            pos += f"/{self.length}"172        return pos173174    def format_pct(self):175        return f"{int(self.pct * 100): 4}%"[1:]176177    def format_bar(self):178        if self.length_known:179            bar_length = int(self.pct * self.width)180            bar = self.fill_char * bar_length181            bar += self.empty_char * (self.width - bar_length)182        elif self.finished:183            bar = self.fill_char * self.width184        else:185            bar = list(self.empty_char * (self.width or 1))186            if self.time_per_iteration != 0:187                bar[188                    int(189                        (math.cos(self.pos * self.time_per_iteration) / 2.0 + 0.5)190                        * self.width191                    )192                ] = self.fill_char193            bar = "".join(bar)194        return bar195196    def format_progress_line(self):197        show_percent = self.show_percent198199        info_bits = []200        if self.length_known and show_percent is None:201            show_percent = not self.show_pos202203        if self.show_pos:204            info_bits.append(self.format_pos())205        if show_percent:206            info_bits.append(self.format_pct())207        if self.show_eta and self.eta_known and not self.finished:208            info_bits.append(self.format_eta())209        if self.item_show_func is not None:210            item_info = self.item_show_func(self.current_item)211            if item_info is not None:212                info_bits.append(item_info)213214        return (215            self.bar_template216            % {217                "label": self.label,218                "bar": self.format_bar(),219                "info": self.info_sep.join(info_bits),220            }221        ).rstrip()222223    def render_progress(self):224        from .termui import get_terminal_size225226        if self.is_hidden:227            return228229        buf = []230        # Update width in case the terminal has been resized231        if self.autowidth:232            old_width = self.width233            self.width = 0234            clutter_length = term_len(self.format_progress_line())235            new_width = max(0, get_terminal_size()[0] - clutter_length)236            if new_width < old_width:237                buf.append(BEFORE_BAR)238                buf.append(" " * self.max_width)239                self.max_width = new_width240            self.width = new_width241242        clear_width = self.width243        if self.max_width is not None:244            clear_width = self.max_width245246        buf.append(BEFORE_BAR)247        line = self.format_progress_line()248        line_len = term_len(line)249        if self.max_width is None or self.max_width < line_len:250            self.max_width = line_len251252        buf.append(line)253        buf.append(" " * (clear_width - line_len))254        line = "".join(buf)255        # Render the line only if it changed.256257        if line != self._last_line and not self.is_fast():258            self._last_line = line259            echo(line, file=self.file, color=self.color, nl=False)260            self.file.flush()261262    def make_step(self, n_steps):263        self.pos += n_steps264        if self.length_known and self.pos >= self.length:265            self.finished = True266267        if (time.time() - self.last_eta) < 1.0:268            return269270        self.last_eta = time.time()271272        # self.avg is a rolling list of length <= 7 of steps where steps are273        # defined as time elapsed divided by the total progress through274        # self.length.275        if self.pos:276            step = (time.time() - self.start) / self.pos277        else:278            step = time.time() - self.start279280        self.avg = self.avg[-6:] + [step]281282        self.eta_known = self.length_known283284    def update(self, n_steps, current_item=None):285        """Update the progress bar by advancing a specified number of286        steps, and optionally set the ``current_item`` for this new287        position.288289        :param n_steps: Number of steps to advance.290        :param current_item: Optional item to set as ``current_item``291            for the updated position.292293        .. versionadded:: 8.0294            Added the ``current_item`` optional parameter.295        """296        self.make_step(n_steps)297        if current_item is not None:298            self.current_item = current_item299        self.render_progress()300301    def finish(self):302        self.eta_known = 0303        self.current_item = None304        self.finished = True305306    def generator(self):307        """Return a generator which yields the items added to the bar308        during construction, and updates the progress bar *after* the309        yielded block returns.310        """311        # WARNING: the iterator interface for `ProgressBar` relies on312        # this and only works because this is a simple generator which313        # doesn't create or manage additional state. If this function314        # changes, the impact should be evaluated both against315        # `iter(bar)` and `next(bar)`. `next()` in particular may call316        # `self.generator()` repeatedly, and this must remain safe in317        # order for that interface to work.318        if not self.entered:319            raise RuntimeError("You need to use progress bars in a with block.")320321        if self.is_hidden:322            yield from self.iter323        else:324            for rv in self.iter:325                self.current_item = rv326                yield rv327                self.update(1)328            self.finish()329            self.render_progress()330331332def pager(generator, color=None):333    """Decide what method to use for paging through text."""334    stdout = _default_text_stdout()335    if not isatty(sys.stdin) or not isatty(stdout):336        return _nullpager(stdout, generator, color)337    pager_cmd = (os.environ.get("PAGER", None) or "").strip()338    if pager_cmd:339        if WIN:340            return _tempfilepager(generator, pager_cmd, color)341        return _pipepager(generator, pager_cmd, color)342    if os.environ.get("TERM") in ("dumb", "emacs"):343        return _nullpager(stdout, generator, color)344    if WIN or sys.platform.startswith("os2"):345        return _tempfilepager(generator, "more <", color)346    if hasattr(os, "system") and os.system("(less) 2>/dev/null") == 0:347        return _pipepager(generator, "less", color)348349    import tempfile350351    fd, filename = tempfile.mkstemp()352    os.close(fd)353    try:354        if hasattr(os, "system") and os.system(f'more "{filename}"') == 0:355            return _pipepager(generator, "more", color)356        return _nullpager(stdout, generator, color)357    finally:358        os.unlink(filename)359360361def _pipepager(generator, cmd, color):362    """Page through text by feeding it to another program.  Invoking a363    pager through this might support colors.364    """365    import subprocess366367    env = dict(os.environ)368369    # If we're piping to less we might support colors under the370    # condition that371    cmd_detail = cmd.rsplit("/", 1)[-1].split()372    if color is None and cmd_detail[0] == "less":373        less_flags = f"{os.environ.get('LESS', '')}{' '.join(cmd_detail[1:])}"374        if not less_flags:375            env["LESS"] = "-R"376            color = True377        elif "r" in less_flags or "R" in less_flags:378            color = True379380    c = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE, env=env)381    encoding = get_best_encoding(c.stdin)382    try:383        for text in generator:384            if not color:385                text = strip_ansi(text)386387            c.stdin.write(text.encode(encoding, "replace"))388    except (OSError, KeyboardInterrupt):389        pass390    else:391        c.stdin.close()392393    # Less doesn't respect ^C, but catches it for its own UI purposes (aborting394    # search or other commands inside less).395    #396    # That means when the user hits ^C, the parent process (click) terminates,397    # but less is still alive, paging the output and messing up the terminal.398    #399    # If the user wants to make the pager exit on ^C, they should set400    # `LESS='-K'`. It's not our decision to make.401    while True:402        try:403            c.wait()404        except KeyboardInterrupt:405            pass406        else:407            break408409410def _tempfilepager(generator, cmd, color):411    """Page through text by invoking a program on a temporary file."""412    import tempfile413414    filename = tempfile.mktemp()415    # TODO: This never terminates if the passed generator never terminates.416    text = "".join(generator)417    if not color:418        text = strip_ansi(text)419    encoding = get_best_encoding(sys.stdout)420    with open_stream(filename, "wb")[0] as f:421        f.write(text.encode(encoding))422    try:423        os.system(f'{cmd} "{filename}"')424    finally:425        os.unlink(filename)426427428def _nullpager(stream, generator, color):429    """Simply print unformatted text.  This is the ultimate fallback."""430    for text in generator:431        if not color:432            text = strip_ansi(text)433        stream.write(text)434435436class Editor:437    def __init__(self, editor=None, env=None, require_save=True, extension=".txt"):438        self.editor = editor439        self.env = env440        self.require_save = require_save441        self.extension = extension442443    def get_editor(self):444        if self.editor is not None:445            return self.editor446        for key in "VISUAL", "EDITOR":447            rv = os.environ.get(key)448            if rv:449                return rv450        if WIN:451            return "notepad"452        for editor in "sensible-editor", "vim", "nano":453            if os.system(f"which {editor} >/dev/null 2>&1") == 0:454                return editor455        return "vi"456457    def edit_file(self, filename):458        import subprocess459460        editor = self.get_editor()461        if self.env:462            environ = os.environ.copy()463            environ.update(self.env)464        else:465            environ = None466        try:467            c = subprocess.Popen(f'{editor} "{filename}"', env=environ, shell=True)468            exit_code = c.wait()469            if exit_code != 0:470                raise ClickException(f"{editor}: Editing failed!")471        except OSError as e:472            raise ClickException(f"{editor}: Editing failed: {e}")473474    def edit(self, text):475        import tempfile476477        if not text:478            text = ""479480        is_bytes = isinstance(text, (bytes, bytearray))481482        if not is_bytes:483            if text and not text.endswith("\n"):484                text += "\n"485486            if WIN:487                text = text.replace("\n", "\r\n").encode("utf-8-sig")488            else:489                text = text.encode("utf-8")490491        fd, name = tempfile.mkstemp(prefix="editor-", suffix=self.extension)492493        try:494            with os.fdopen(fd, "wb") as f:495                f.write(text)496497            # If the filesystem resolution is 1 second, like Mac OS498            # 10.12 Extended, or 2 seconds, like FAT32, and the editor499            # closes very fast, require_save can fail. Set the modified500            # time to be 2 seconds in the past to work around this.501            os.utime(name, (os.path.getatime(name), os.path.getmtime(name) - 2))502            # Depending on the resolution, the exact value might not be503            # recorded, so get the new recorded value.504            timestamp = os.path.getmtime(name)505506            self.edit_file(name)507508            if self.require_save and os.path.getmtime(name) == timestamp:509                return None510511            with open(name, "rb") as f:512                rv = f.read()513514            if is_bytes:515                return rv516517            return rv.decode("utf-8-sig").replace("\r\n", "\n")518        finally:519            os.unlink(name)520521522def open_url(url, wait=False, locate=False):523    import subprocess524525    def _unquote_file(url):526        import urllib527528        if url.startswith("file://"):529            url = urllib.unquote(url[7:])530        return url531532    if sys.platform == "darwin":533        args = ["open"]534        if wait:535            args.append("-W")536        if locate:537            args.append("-R")538        args.append(_unquote_file(url))539        null = open("/dev/null", "w")540        try:541            return subprocess.Popen(args, stderr=null).wait()542        finally:543            null.close()544    elif WIN:545        if locate:546            url = _unquote_file(url.replace('"', ""))547            args = f'explorer /select,"{url}"'548        else:549            url = url.replace('"', "")550            wait = "/WAIT" if wait else ""551            args = f'start {wait} "" "{url}"'552        return os.system(args)553    elif CYGWIN:554        if locate:555            url = os.path.dirname(_unquote_file(url).replace('"', ""))556            args = f'cygstart "{url}"'557        else:558            url = url.replace('"', "")559            wait = "-w" if wait else ""560            args = f'cygstart {wait} "{url}"'561        return os.system(args)562563    try:564        if locate:565            url = os.path.dirname(_unquote_file(url)) or "."566        else:567            url = _unquote_file(url)568        c = subprocess.Popen(["xdg-open", url])569        if wait:570            return c.wait()571        return 0572    except OSError:573        if url.startswith(("http://", "https://")) and not locate and not wait:574            import webbrowser575576            webbrowser.open(url)577            return 0578        return 1579580581def _translate_ch_to_exc(ch):582    if ch == "\x03":583        raise KeyboardInterrupt()584    if ch == "\x04" and not WIN:  # Unix-like, Ctrl+D585        raise EOFError()586    if ch == "\x1a" and WIN:  # Windows, Ctrl+Z587        raise EOFError()588589590if WIN:591    import msvcrt592593    @contextlib.contextmanager594    def raw_terminal():595        yield596597    def getchar(echo):598        # The function `getch` will return a bytes object corresponding to599        # the pressed character. Since Windows 10 build 1803, it will also600        # return \x00 when called a second time after pressing a regular key.601        #602        # `getwch` does not share this probably-bugged behavior. Moreover, it603        # returns a Unicode object by default, which is what we want.604        #605        # Either of these functions will return \x00 or \xe0 to indicate606        # a special key, and you need to call the same function again to get607        # the "rest" of the code. The fun part is that \u00e0 is608        # "latin small letter a with grave", so if you type that on a French609        # keyboard, you _also_ get a \xe0.610        # E.g., consider the Up arrow. This returns \xe0 and then \x48. The611        # resulting Unicode string reads as "a with grave" + "capital H".612        # This is indistinguishable from when the user actually types613        # "a with grave" and then "capital H".614        #615        # When \xe0 is returned, we assume it's part of a special-key sequence616        # and call `getwch` again, but that means that when the user types617        # the \u00e0 character, `getchar` doesn't return until a second618        # character is typed.619        # The alternative is returning immediately, but that would mess up620        # cross-platform handling of arrow keys and others that start with621        # \xe0. Another option is using `getch`, but then we can't reliably622        # read non-ASCII characters, because return values of `getch` are623        # limited to the current 8-bit codepage.624        #625        # Anyway, Click doesn't claim to do this Right(tm), and using `getwch`626        # is doing the right thing in more situations than with `getch`.627        if echo:628            func = msvcrt.getwche629        else:630            func = msvcrt.getwch631632        rv = func()633        if rv in ("\x00", "\xe0"):634            # \x00 and \xe0 are control characters that indicate special key,635            # see above.636            rv += func()637        _translate_ch_to_exc(rv)638        return rv639640641else:642    import tty643    import termios644645    @contextlib.contextmanager646    def raw_terminal():647        if not isatty(sys.stdin):648            f = open("/dev/tty")649            fd = f.fileno()650        else:651            fd = sys.stdin.fileno()652            f = None653        try:654            old_settings = termios.tcgetattr(fd)655            try:656                tty.setraw(fd)657                yield fd658            finally:659                termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)660                sys.stdout.flush()661                if f is not None:662                    f.close()663        except termios.error:664            pass665666    def getchar(echo):667        with raw_terminal() as fd:668            ch = os.read(fd, 32)669            ch = ch.decode(get_best_encoding(sys.stdin), "replace")670            if echo and isatty(sys.stdout):671                sys.stdout.write(ch)672            _translate_ch_to_exc(ch)673            return ch