File size: 8,241 Bytes
92c3b9e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
diff --git a/CHANGES.md b/CHANGES.md
index 8853860..4976b6c 100644
--- a/CHANGES.md
+++ b/CHANGES.md
@@ -11,6 +11,10 @@ Unreleased
 
 Unreleased
 
+- The `[default: ...]` shown in help for an option with `multiple=True`
+  renders each value the way a single value is rendered: `Enum` members by
+  name, empty strings as `""`. The prompt of an option lists its choices and
+  previews its default the same way, so what it shows can be typed back.
 - Fix `copy.deepcopy()` and `pickle` on a `Parameter`, `Option` or `Command`. {pr}`3805`
 - A `KeyboardInterrupt` arriving while `Command.main()` reports an abort or an error,
   or while it exits, no longer escapes as an unhandled traceback. The command still
diff --git a/src/click/_utils.py b/src/click/_utils.py
index 2d4e8f2..e2811bb 100644
--- a/src/click/_utils.py
+++ b/src/click/_utils.py
@@ -1,7 +1,9 @@
 from __future__ import annotations
 
 import enum
+import inspect
 import typing as t
+from gettext import gettext as _
 
 
 class Sentinel(enum.Enum):
@@ -43,3 +45,33 @@ T_UNSET: t.TypeAlias = t.Literal[Sentinel.UNSET]
 
 T_FLAG_NEEDS_VALUE: t.TypeAlias = t.Literal[Sentinel.FLAG_NEEDS_VALUE]
 """Type hint for the :data:`FLAG_NEEDS_VALUE` sentinel value."""
+
+
+def _format_default_value(value: t.Any) -> str:
+    """Render a value the way ``[default: ...]`` and prompts show it.
+
+    A list or tuple renders as its values, comma separated, each rendered by
+    the same rules as a single value: an Enum member by its name, an empty
+    string as ``""``, a plain function as ``(dynamic)``, anything else with
+    ``str()``.
+
+    :meta private:
+    """
+    if isinstance(value, (list, tuple)):
+        return ", ".join(_format_default_value(item) for item in value)
+    if isinstance(value, enum.Enum):
+        return value.name
+    if inspect.isfunction(value):
+        return _("(dynamic)")
+    if isinstance(value, str) and value == "":
+        return '""'
+    return str(value)
+
+
+def _format_choice(choice: t.Any) -> str:
+    """Render one choice the way prompts and help list it: an Enum member by
+    its name, anything else with ``str()``.
+
+    :meta private:
+    """
+    return choice.name if isinstance(choice, enum.Enum) else str(choice)
diff --git a/src/click/core.py b/src/click/core.py
index 1f9323a..e82eaa0 100644
--- a/src/click/core.py
+++ b/src/click/core.py
@@ -23,6 +23,7 @@ from types import TracebackType
 
 from . import types
 from ._utils import FLAG_NEEDS_VALUE
+from ._utils import _format_default_value
 from ._utils import UNSET
 from .exceptions import Abort
 from .exceptions import BadParameter
@@ -3564,12 +3565,13 @@ class Option(Parameter):
         ):
             if show_default_is_str:
                 default_string = f"({self.show_default})"
-            elif isinstance(default_value, (list, tuple)):
-                default_string = ", ".join(str(d) for d in default_value)
-            elif isinstance(default_value, enum.Enum):
-                default_string = default_value.name
-            elif inspect.isfunction(default_value):
-                default_string = _("(dynamic)")
+            elif isinstance(default_value, (list, tuple)) or (
+                isinstance(default_value, enum.Enum)
+                or inspect.isfunction(default_value)
+            ):
+                # Multi-valued defaults render each value the way the same
+                # value renders for a single-valued option.
+                default_string = _format_default_value(default_value)
             elif self.is_bool_flag and self.secondary_opts:
                 # For boolean flags that have distinct True/False opts,
                 # use the opt without prefix instead of the value.
diff --git a/src/click/termui.py b/src/click/termui.py
index 8fe0085..0caa7cd 100644
--- a/src/click/termui.py
+++ b/src/click/termui.py
@@ -15,6 +15,8 @@ from gettext import gettext as _
 from . import _compat
 from ._compat import isatty
 from ._compat import strip_ansi
+from ._utils import _format_choice
+from ._utils import _format_default_value
 from .exceptions import Abort
 from .exceptions import UsageError
 from .globals import resolve_color_default
@@ -115,7 +117,9 @@ def _build_prompt(
 ) -> str:
     prompt = text
     if type is not None and show_choices and isinstance(type, Choice):
-        prompt += f" ({', '.join(map(str, type.choices))})"
+        # Each choice is listed the way it can be typed back, which for an
+        # Enum member is its name, as the help and the error message show it.
+        prompt += f" ({', '.join(_format_choice(choice) for choice in type.choices)})"
     default_preview = ""
     if show_default:
         if isinstance(show_default, str):
@@ -132,7 +136,9 @@ def _format_default(default: V) -> V | str:
         if name is not None:
             return str(name)
 
-    return default
+    # The default is previewed the way the help renders it, so that what is
+    # shown is what the user can type back.
+    return _format_default_value(default)
 
 
 @t.overload
@@ -250,6 +256,15 @@ def prompt(
     prompt = _build_prompt(
         text, prompt_suffix, show_default, default, show_choices, type
     )
+    # The default exactly as the prompt shows it. Typing that text back
+    # selects the default itself, as pressing Enter does, so that a value
+    # rendered for display (a quoted empty string, a list of values) can be
+    # typed back as shown.
+    shown_default = (
+        str(_format_default(default))
+        if default is not None and show_default and not isinstance(show_default, str)
+        else None
+    )
 
     if confirmation_prompt:
         if confirmation_prompt is True:
@@ -269,7 +284,9 @@ def prompt(
                 value = t.cast("str", default)
                 break
         try:
-            result = value_proc(value)
+            result = value_proc(
+                default if shown_default is not None and value == shown_default else value
+            )
         except UsageError as e:
             message = _mask_hidden_input(e.message, value) if hide_input else e.message
             echo(_("Error: {message}").format(message=message), err=err)
diff --git a/tests/test_help_defaults_multiple.py b/tests/test_help_defaults_multiple.py
new file mode 100644
index 0000000..cb6eb77
--- /dev/null
+++ b/tests/test_help_defaults_multiple.py
@@ -0,0 +1,69 @@
+import enum
+
+import click
+from click.testing import CliRunner
+
+
+class Color(enum.Enum):
+    Red = "r"
+    Blue = "b"
+
+
+def _help(**kwargs):
+    @click.command()
+    @click.option("--opt", show_default=True, **kwargs)
+    def cmd(opt):
+        pass
+
+    return CliRunner().invoke(cmd, ["--help"]).output
+
+
+def test_multiple_enum_default_shows_names():
+    assert "[default: Red, Blue]" in _help(
+        type=click.Choice(Color), multiple=True, default=[Color.Red, Color.Blue]
+    )
+
+
+def test_multiple_empty_string_default_is_quoted():
+    assert '[default: "", x]' in _help(multiple=True, default=["", "x"])
+
+
+def test_nargs_with_multiple_renders_every_value():
+    assert "[default: 1, 2, 3, 4]" in _help(nargs=2, multiple=True, default=[(1, 2), (3, 4)])
+
+
+def _prompt_line(input_text="\n", **kwargs):
+    @click.command()
+    @click.option("--opt", prompt="Value", **kwargs)
+    def cmd(opt):
+        pass
+
+    return CliRunner().invoke(cmd, [], input=input_text).output.split("\n", 1)[0]
+
+
+def test_prompt_lists_enum_choices_and_default_by_name():
+    line = _prompt_line(type=click.Choice(Color), default=Color.Blue)
+    assert "(Red, Blue)" in line
+    assert "[Blue]" in line
+
+
+def test_prompt_previews_empty_string_default_quoted():
+    assert '[""]' in _prompt_line(default="")
+
+
+def test_prompt_default_typed_back_as_shown():
+    line = CliRunner().invoke(
+        _typed_back_cmd(multiple=True, default=["", "x"]), [], input='"", x\n'
+    ).output
+    assert "GOT=('', 'x')" in line
+    line = CliRunner().invoke(_typed_back_cmd(default=""), [], input='""\n').output
+    assert "GOT=''" in line
+
+
+def _typed_back_cmd(**kwargs):
+    @click.command()
+    @click.option("--opt", prompt="Value", **kwargs)
+    def cmd(opt):
+        click.echo(f"GOT={opt!r}")
+
+    return cmd