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
Provenance
- Commit
2468b70- Tree
51a4e63- Author
Yorick <yorickvanpelt@gmail.com>- Committer
GitHub <noreply@github.com>- Parent
ddede21
3 files changed+74 added−21 removed
modified:src/click/termui.py+24 added-12 removed
5 unmodified lines6 import itertools7 import sys8 import typing as t9 from contextlib import AbstractContextManager10+from contextlib import redirect_stdout11 from gettext import gettext as _12 13 from ._compat import isatty14 from ._compat import strip_ansi15+from ._compat import WIN16 from .exceptions import Abort17 from .exceptions import UsageError18 from .globals import resolve_color_default19 from .types import Choice38 unmodified lines58 59 return getpass.getpass(prompt)60 61 62+def _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.65+66+ 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)80+81+82 def _build_prompt(83 text: str,84 suffix: str,85 show_default: bool | str = False,82 unmodified lines168 169 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/issue2471182 unmodified lines259 )260 261 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 = True636 unmodified linesmodified:tests/test_utils.py+46 added-9 removed
223 unmodified lines224 except click.Abort:225 click.echo("interrupted")226 227 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"230 231 232+@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+)243+def 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.246+247+ https://github.com/pallets/click/issues/2968248+ https://github.com/pallets/click/pull/2969249+ """250+ received = []251+252+ def capture(text):253+ received.append(text)254+ return "y"255+256+ monkeypatch.setattr("click.termui.visible_prompt_func", capture)257+ monkeypatch.setattr("click.termui.hidden_prompt_func", capture)258+ call()259+ assert received == [expected_prompt]260+261+262 def test_prompts_eof(runner):263 """If too few lines of input are given, prompt should exit, not hang."""264 265 @click.command248 unmodified lines514 out, err = capfd.readouterr()515 assert out == "Prompt to stdin with no suffix"516 assert err == ""517 518+ # 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: "526 527+ # 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"533 534 emulate_input("y\n")535 click.confirm("Prompt to stdin")536 out, err = capfd.readouterr()5 unmodified lines542 out, err = capfd.readouterr()543 assert out == "Prompt to stdin with no suffix [y/N]"544 assert err == ""545 546+ # 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]: "552 553+ # 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]"559 560 monkeypatch.setattr(click.termui, "isatty", lambda x: True)561 monkeypatch.setattr(click.termui, "getchar", lambda: " ")562 220 unmodified linesmodified:CHANGES.rst+4 added
36 unmodified lines37 - 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`45 46 Version 8.3.347 -------------48 1364 unmodified lines