Skip to content
Myr

Fix readline backspace/line-wrapping on linux (#2969)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Yorick · committed by GitHub · parent ddede21 · Browse files · 3 files+74 added−21 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Trailers

  • Co-authored-by: Kevin Deldycke <kevin@deldycke.com>

Diff stats

3 files+74 added−21 removed

  • tests:+46 added−9 removed
  • other:+28 added−12 removed

3 files+74 added−21 removed

modified:src/click/termui.py+24 added-12 removed
5 unmodified lines
6import itertools7import sys8import typing as t9from contextlib import AbstractContextManager10from contextlib import redirect_stdout11from gettext import gettext as _1213from ._compat import isatty14from ._compat import strip_ansi15from ._compat import WIN16from .exceptions import Abort17from .exceptions import UsageError18from .globals import resolve_color_default19from .types import Choice
38 unmodified lines
5859 return getpass.getpass(prompt)606162def _readline_prompt(func: t.Callable[[str], str], text: str, err: bool) -> str:63 """Call a prompt function, passing the full prompt on non-Windows so64 readline can handle line editing and cursor positioning correctly.6566 On Windows the prompt is written separately via :func:`echo` for67 colorama support, with only the last character passed to *func*.68 """69 if WIN:70 # Write the prompt separately so that we get nice coloring71 # through colorama on Windows.72 echo(text[:-1], nl=False, err=err)73 # Echo the last character to stdout to work around an issue74 # where readline causes backspace to clear the whole line.75 return func(text[-1:])76 if err:77 with redirect_stdout(sys.stderr):78 return func(text)79 return func(text)808182def _build_prompt(83 text: str,84 suffix: str,85 show_default: bool | str = False,
82 unmodified lines
168169 def prompt_func(text: str) -> str:170 f = hidden_prompt_func if hide_input else visible_prompt_func171 try:150 # Write the prompt separately so that we get nice151 # coloring through colorama on Windows152 echo(text[:-1], nl=False, err=err)153 # Echo the last character to stdout to work around an issue where154 # readline causes backspace to clear the whole line.155 return f(text[-1:])172 return _readline_prompt(f, text, err)173 except (KeyboardInterrupt, EOFError):174 # getpass doesn't print a newline if the user aborts input with ^C.175 # Allegedly this behavior is inherited from getpass(3).176 # A doc bug has been filed at https://bugs.python.org/issue24711
82 unmodified lines
259 )260261 while True:262 try:246 # Write the prompt separately so that we get nice247 # coloring through colorama on Windows248 echo(prompt[:-1], nl=False, err=err)249 # Echo the last character to stdout to work around an issue where250 # readline causes backspace to clear the whole line.251 value = visible_prompt_func(prompt[-1:]).lower().strip()263 value = _readline_prompt(visible_prompt_func, prompt, err).lower().strip()264 except (KeyboardInterrupt, EOFError):265 raise Abort() from None266 if value in ("y", "yes"):267 rv = True
636 unmodified lines
modified:tests/test_utils.py+46 added-9 removed
223 unmodified lines
224 except click.Abort:225 click.echo("interrupted")226227 out, err = capsys.readouterr()228 # On non-Windows, prompt is passed directly to getpass, not echoed separately228 assert out == "Password:\ninterrupted\n"229 assert out == "\ninterrupted\n"230231232@pytest.mark.skipif(WIN, reason="Different behavior on windows.")233@pytest.mark.parametrize(234 ("call", "expected_prompt"),235 [236 (lambda: click.prompt("Name"), "Name: "),237 (lambda: click.prompt("Pw", hide_input=True), "Pw: "),238 (lambda: click.prompt("IP", prompt_suffix="."), "IP."),239 (lambda: click.confirm("OK"), "OK [y/N]: "),240 ],241 ids=["prompt", "prompt-hidden", "prompt-custom-suffix", "confirm"],242)243def test_full_prompt_passed_to_readline(monkeypatch, call, expected_prompt):244 """On non-Windows, prompt and confirm pass the full prompt text to the245 underlying prompt function so readline handles editing correctly.246247 https://github.com/pallets/click/issues/2968248 https://github.com/pallets/click/pull/2969249 """250 received = []251252 def capture(text):253 received.append(text)254 return "y"255256 monkeypatch.setattr("click.termui.visible_prompt_func", capture)257 monkeypatch.setattr("click.termui.hidden_prompt_func", capture)258 call()259 assert received == [expected_prompt]260261262def test_prompts_eof(runner):263 """If too few lines of input are given, prompt should exit, not hang."""264265 @click.command
248 unmodified lines
514 out, err = capfd.readouterr()515 assert out == "Prompt to stdin with no suffix"516 assert err == ""517518 # On non-Windows the full prompt goes through redirect_stdout so519 # nothing leaks to stdout when err=True.520 # https://github.com/pallets/click/issues/2968521 emulate_input("asdlkj\n")522 click.prompt("Prompt to stderr", err=True)523 out, err = capfd.readouterr()490 assert out == " "491 assert err == "Prompt to stderr:"524 assert out == ""525 assert err == "Prompt to stderr: "526527 # https://github.com/pallets/click/issues/3019528 emulate_input("asdlkj\n")529 click.prompt("Prompt to stderr with no suffix", prompt_suffix="", err=True)530 out, err = capfd.readouterr()496 assert out == "x"497 assert err == "Prompt to stderr with no suffi"531 assert out == ""532 assert err == "Prompt to stderr with no suffix"533534 emulate_input("y\n")535 click.confirm("Prompt to stdin")536 out, err = capfd.readouterr()
5 unmodified lines
542 out, err = capfd.readouterr()543 assert out == "Prompt to stdin with no suffix [y/N]"544 assert err == ""545546 # https://github.com/pallets/click/issues/2968547 emulate_input("y\n")548 click.confirm("Prompt to stderr", err=True)549 out, err = capfd.readouterr()514 assert out == " "515 assert err == "Prompt to stderr [y/N]:"550 assert out == ""551 assert err == "Prompt to stderr [y/N]: "552553 # https://github.com/pallets/click/issues/3019554 emulate_input("y\n")555 click.confirm("Prompt to stderr with no suffix", prompt_suffix="", err=True)556 out, err = capfd.readouterr()520 assert out == "]"521 assert err == "Prompt to stderr with no suffix [y/N"557 assert out == ""558 assert err == "Prompt to stderr with no suffix [y/N]"559560 monkeypatch.setattr(click.termui, "isatty", lambda x: True)561 monkeypatch.setattr(click.termui, "getchar", lambda: " ")562
220 unmodified lines
modified:CHANGES.rst+4 added
36 unmodified lines
37- The error hint now uses :meth:`Command.get_help_option_names` to pick38 non-shadowed help option names, so ``Try '... -h'`` no longer points to a39 subcommand option that shadows ``-h``. All surviving names are shown40 (``-h/--help``). :issue:`2790` :pr:`3208`41- Fix readline functionality on non-Windows platforms. Prompt text is now42 passed directly to readline instead of being printed separately, allowing43 proper backspace, line editing, and line wrapping behavior. :issue:`2968`44 :pr:`2969`4546Version 8.3.347-------------48
1364 unmodified lines