InquirerPrompt 0.3.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- InquirerPy/__init__.py +4 -0
- InquirerPy/base/__init__.py +24 -0
- InquirerPy/base/complex.py +295 -0
- InquirerPy/base/control.py +230 -0
- InquirerPy/base/list.py +239 -0
- InquirerPy/base/simple.py +379 -0
- InquirerPy/containers/__init__.py +3 -0
- InquirerPy/containers/instruction.py +38 -0
- InquirerPy/containers/message.py +42 -0
- InquirerPy/containers/spinner.py +109 -0
- InquirerPy/containers/validation.py +60 -0
- InquirerPy/enum.py +8 -0
- InquirerPy/exceptions.py +25 -0
- InquirerPy/inquirer.py +31 -0
- InquirerPy/prompts/__init__.py +25 -0
- InquirerPy/prompts/checkbox.py +249 -0
- InquirerPy/prompts/confirm.py +202 -0
- InquirerPy/prompts/expand.py +459 -0
- InquirerPy/prompts/filepath.py +193 -0
- InquirerPy/prompts/fuzzy.py +685 -0
- InquirerPy/prompts/input.py +256 -0
- InquirerPy/prompts/list.py +371 -0
- InquirerPy/prompts/number.py +621 -0
- InquirerPy/prompts/rawlist.py +286 -0
- InquirerPy/prompts/secret.py +137 -0
- InquirerPy/py.typed +1 -0
- InquirerPy/resolver.py +220 -0
- InquirerPy/separator.py +23 -0
- InquirerPy/utils.py +291 -0
- InquirerPy/validator.py +166 -0
- inquirerprompt-0.3.0.dist-info/METADATA +217 -0
- inquirerprompt-0.3.0.dist-info/RECORD +34 -0
- inquirerprompt-0.3.0.dist-info/WHEEL +4 -0
- inquirerprompt-0.3.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,256 @@
|
|
|
1
|
+
"""Module contains the class to create an input prompt."""
|
|
2
|
+
|
|
3
|
+
from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Tuple, Union
|
|
4
|
+
|
|
5
|
+
from prompt_toolkit.buffer import ValidationState
|
|
6
|
+
from prompt_toolkit.completion import NestedCompleter
|
|
7
|
+
from prompt_toolkit.completion.base import Completer
|
|
8
|
+
from prompt_toolkit.filters.base import Condition
|
|
9
|
+
from prompt_toolkit.keys import Keys
|
|
10
|
+
from prompt_toolkit.lexers import SimpleLexer
|
|
11
|
+
from prompt_toolkit.shortcuts.prompt import CompleteStyle, PromptSession
|
|
12
|
+
from prompt_toolkit.validation import ValidationError
|
|
13
|
+
|
|
14
|
+
from InquirerPy.base import BaseSimplePrompt
|
|
15
|
+
from InquirerPy.enum import INQUIRERPY_POINTER_SEQUENCE
|
|
16
|
+
from InquirerPy.exceptions import InvalidArgument
|
|
17
|
+
from InquirerPy.utils import (
|
|
18
|
+
InquirerPyDefault,
|
|
19
|
+
InquirerPyKeybindings,
|
|
20
|
+
InquirerPyMessage,
|
|
21
|
+
InquirerPySessionResult,
|
|
22
|
+
InquirerPyStyle,
|
|
23
|
+
InquirerPyValidate,
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
if TYPE_CHECKING:
|
|
27
|
+
from prompt_toolkit.input.base import Input
|
|
28
|
+
from prompt_toolkit.key_binding.key_processor import KeyPressEvent
|
|
29
|
+
from prompt_toolkit.output.base import Output
|
|
30
|
+
|
|
31
|
+
__all__ = ["InputPrompt"]
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class InputPrompt(BaseSimplePrompt):
|
|
35
|
+
"""Create a text prompt that accepts user input.
|
|
36
|
+
|
|
37
|
+
A wrapper class around :class:`~prompt_toolkit.shortcuts.PromptSession`.
|
|
38
|
+
|
|
39
|
+
Args:
|
|
40
|
+
message: The question to ask the user.
|
|
41
|
+
Refer to :ref:`pages/dynamic:message` documentation for more details.
|
|
42
|
+
style: An :class:`InquirerPyStyle` instance.
|
|
43
|
+
Refer to :ref:`Style <pages/style:Alternate Syntax>` documentation for more details.
|
|
44
|
+
vi_mode: Use vim keybinding for the prompt.
|
|
45
|
+
Refer to :ref:`pages/kb:Keybindings` documentation for more details.
|
|
46
|
+
default: Set the default text value of the prompt.
|
|
47
|
+
Refer to :ref:`pages/dynamic:default` documentation for more details.
|
|
48
|
+
qmark: Question mark symbol. Custom symbol that will be displayed infront of the question before its answered.
|
|
49
|
+
amark: Answer mark symbol. Custom symbol that will be displayed infront of the question after its answered.
|
|
50
|
+
instruction: Short instruction to display next to the question.
|
|
51
|
+
long_instruction: Long instructions to display at the bottom of the prompt.
|
|
52
|
+
completer: Add auto completion to the prompt.
|
|
53
|
+
Refer to :ref:`pages/prompts/input:Auto Completion` documentation for more details.
|
|
54
|
+
multicolumn_complete: Change the auto-completion UI to a multi column display.
|
|
55
|
+
multiline: Enable multiline edit. While multiline edit is active, pressing `enter` won't complete the answer.
|
|
56
|
+
and will create a new line. Use `esc` followd by `enter` to complete the question.
|
|
57
|
+
validate: Add validation to user input.
|
|
58
|
+
Refer to :ref:`pages/validator:Validator` documentation for more details.
|
|
59
|
+
invalid_message: Error message to display when user input is invalid.
|
|
60
|
+
Refer to :ref:`pages/validator:Validator` documentation for more details.
|
|
61
|
+
transformer: A function which performs additional transformation on the value that gets printed to the terminal.
|
|
62
|
+
Different than `filter` parameter, this is only visual effect and won’t affect the actual value returned by :meth:`~InquirerPy.base.simple.BaseSimplePrompt.execute`.
|
|
63
|
+
Refer to :ref:`pages/dynamic:transformer` documentation for more details.
|
|
64
|
+
filter: A function which performs additional transformation on the result.
|
|
65
|
+
This affects the actual value returned by :meth:`~InquirerPy.base.simple.BaseSimplePrompt.execute`.
|
|
66
|
+
Refer to :ref:`pages/dynamic:filter` documentation for more details.
|
|
67
|
+
keybindings: Customise the builtin keybindings.
|
|
68
|
+
Refer to :ref:`pages/kb:Keybindings` for more details.
|
|
69
|
+
wrap_lines: Soft wrap question lines when question exceeds the terminal width.
|
|
70
|
+
raise_keyboard_interrupt: Raise the :class:`KeyboardInterrupt` exception when `ctrl-c` is pressed. If false, the result
|
|
71
|
+
will be `None` and the question is skiped.
|
|
72
|
+
is_password: Used internally for :class:`~InquirerPy.prompts.secret.SecretPrompt`.
|
|
73
|
+
mandatory: Indicate if the prompt is mandatory. If True, then the question cannot be skipped.
|
|
74
|
+
mandatory_message: Error message to show when user attempts to skip mandatory prompt.
|
|
75
|
+
session_result: Used internally for :ref:`index:Classic Syntax (PyInquirer)`.
|
|
76
|
+
input: Used internally and will be removed in future updates.
|
|
77
|
+
output: Used internally and will be removed in future updates.
|
|
78
|
+
|
|
79
|
+
Examples:
|
|
80
|
+
>>> from InquirerPy import inquirer
|
|
81
|
+
>>> result = inquirer.text(message="Enter your name:").execute()
|
|
82
|
+
>>> print(f"Name: {result}")
|
|
83
|
+
Name: Michael
|
|
84
|
+
"""
|
|
85
|
+
|
|
86
|
+
def __init__(
|
|
87
|
+
self,
|
|
88
|
+
message: InquirerPyMessage,
|
|
89
|
+
style: Optional[InquirerPyStyle] = None,
|
|
90
|
+
vi_mode: bool = False,
|
|
91
|
+
default: InquirerPyDefault = "",
|
|
92
|
+
qmark: str = "?",
|
|
93
|
+
amark: str = "?",
|
|
94
|
+
instruction: str = "",
|
|
95
|
+
long_instruction: str = "",
|
|
96
|
+
completer: Optional[Union[Dict[str, Optional[str]], "Completer"]] = None,
|
|
97
|
+
multicolumn_complete: bool = False,
|
|
98
|
+
multiline: bool = False,
|
|
99
|
+
validate: Optional[InquirerPyValidate] = None,
|
|
100
|
+
invalid_message: str = "Invalid input",
|
|
101
|
+
transformer: Optional[Callable[[str], Any]] = None,
|
|
102
|
+
filter: Optional[Callable[[str], Any]] = None,
|
|
103
|
+
keybindings: Optional[InquirerPyKeybindings] = None,
|
|
104
|
+
wrap_lines: bool = True,
|
|
105
|
+
raise_keyboard_interrupt: bool = True,
|
|
106
|
+
is_password: bool = False,
|
|
107
|
+
mandatory: bool = True,
|
|
108
|
+
mandatory_message: str = "Mandatory prompt",
|
|
109
|
+
session_result: Optional[InquirerPySessionResult] = None,
|
|
110
|
+
input: Optional["Input"] = None,
|
|
111
|
+
output: Optional["Output"] = None,
|
|
112
|
+
) -> None:
|
|
113
|
+
super().__init__(
|
|
114
|
+
message,
|
|
115
|
+
style,
|
|
116
|
+
vi_mode=vi_mode,
|
|
117
|
+
qmark=qmark,
|
|
118
|
+
amark=amark,
|
|
119
|
+
instruction=instruction,
|
|
120
|
+
validate=validate,
|
|
121
|
+
invalid_message=invalid_message,
|
|
122
|
+
transformer=transformer,
|
|
123
|
+
filter=filter,
|
|
124
|
+
session_result=session_result,
|
|
125
|
+
default=default,
|
|
126
|
+
wrap_lines=wrap_lines,
|
|
127
|
+
mandatory=mandatory,
|
|
128
|
+
mandatory_message=mandatory_message,
|
|
129
|
+
raise_keyboard_interrupt=raise_keyboard_interrupt,
|
|
130
|
+
)
|
|
131
|
+
if not isinstance(self._default, str):
|
|
132
|
+
raise InvalidArgument(
|
|
133
|
+
f"{type(self).__name__} argument 'default' should be type of str"
|
|
134
|
+
)
|
|
135
|
+
self._completer = None
|
|
136
|
+
if isinstance(completer, dict):
|
|
137
|
+
self._completer = NestedCompleter.from_nested_dict(completer)
|
|
138
|
+
elif isinstance(completer, Completer):
|
|
139
|
+
self._completer = completer
|
|
140
|
+
self._multiline = multiline
|
|
141
|
+
self._complete_style = (
|
|
142
|
+
CompleteStyle.COLUMN
|
|
143
|
+
if not multicolumn_complete
|
|
144
|
+
else CompleteStyle.MULTI_COLUMN
|
|
145
|
+
)
|
|
146
|
+
|
|
147
|
+
@Condition
|
|
148
|
+
def is_multiline():
|
|
149
|
+
return self._multiline
|
|
150
|
+
|
|
151
|
+
if not keybindings:
|
|
152
|
+
keybindings = {}
|
|
153
|
+
self.kb_maps = {
|
|
154
|
+
"answer": [
|
|
155
|
+
{"key": Keys.Enter, "filter": ~is_multiline},
|
|
156
|
+
{"key": [Keys.Escape, Keys.Enter], "filter": is_multiline},
|
|
157
|
+
],
|
|
158
|
+
"completion": [{"key": "c-space"}],
|
|
159
|
+
**keybindings,
|
|
160
|
+
}
|
|
161
|
+
self.kb_func_lookup = {"completion": [{"func": self._handle_completion}]}
|
|
162
|
+
self._keybinding_factory()
|
|
163
|
+
|
|
164
|
+
self._session = PromptSession(
|
|
165
|
+
message=self._get_prompt_message,
|
|
166
|
+
key_bindings=self._kb,
|
|
167
|
+
style=self._style,
|
|
168
|
+
completer=self._completer,
|
|
169
|
+
validator=self._validator,
|
|
170
|
+
validate_while_typing=False,
|
|
171
|
+
input=input,
|
|
172
|
+
output=output,
|
|
173
|
+
editing_mode=self._editing_mode,
|
|
174
|
+
lexer=SimpleLexer(self._lexer),
|
|
175
|
+
is_password=is_password,
|
|
176
|
+
multiline=self._multiline,
|
|
177
|
+
complete_style=self._complete_style,
|
|
178
|
+
wrap_lines=wrap_lines,
|
|
179
|
+
bottom_toolbar=(
|
|
180
|
+
[("class:long_instruction", long_instruction)]
|
|
181
|
+
if long_instruction
|
|
182
|
+
else None
|
|
183
|
+
),
|
|
184
|
+
)
|
|
185
|
+
|
|
186
|
+
def _set_error(self, message: str) -> None:
|
|
187
|
+
self._session.default_buffer.validation_state = ValidationState.INVALID
|
|
188
|
+
self._session.default_buffer.validation_error = ValidationError(message=message)
|
|
189
|
+
|
|
190
|
+
def _handle_enter(self, event: "KeyPressEvent") -> None:
|
|
191
|
+
try:
|
|
192
|
+
self._session.validator.validate(self._session.default_buffer) # type: ignore
|
|
193
|
+
except ValidationError:
|
|
194
|
+
self._session.default_buffer.validate_and_handle()
|
|
195
|
+
else:
|
|
196
|
+
self.status["answered"] = True
|
|
197
|
+
self.status["result"] = self._session.default_buffer.text
|
|
198
|
+
self._session.default_buffer.text = ""
|
|
199
|
+
event.app.exit(result=self.status["result"])
|
|
200
|
+
|
|
201
|
+
def _handle_completion(self, event) -> None:
|
|
202
|
+
if self._completer is None:
|
|
203
|
+
return
|
|
204
|
+
buff = event.app.current_buffer
|
|
205
|
+
if buff.complete_state:
|
|
206
|
+
buff.complete_next()
|
|
207
|
+
else:
|
|
208
|
+
buff.start_completion(select_first=False)
|
|
209
|
+
|
|
210
|
+
def _get_prompt_message(
|
|
211
|
+
self,
|
|
212
|
+
pre_answer: Optional[Tuple[str, str]] = None,
|
|
213
|
+
post_answer: Optional[Tuple[str, str]] = None,
|
|
214
|
+
) -> List[Tuple[str, str]]:
|
|
215
|
+
"""Get message to display infront of the input buffer.
|
|
216
|
+
|
|
217
|
+
Args:
|
|
218
|
+
pre_answer: The formatted text to display before answering the question.
|
|
219
|
+
post_answer: The formatted text to display after answering the question.
|
|
220
|
+
|
|
221
|
+
Returns:
|
|
222
|
+
Formatted text in list of tuple format.
|
|
223
|
+
"""
|
|
224
|
+
if not pre_answer:
|
|
225
|
+
if self._multiline and not self._instruction:
|
|
226
|
+
pre_answer = ("class:instruction", " ESC + Enter to finish input")
|
|
227
|
+
else:
|
|
228
|
+
pre_answer = (
|
|
229
|
+
"class:instruction",
|
|
230
|
+
" %s " % self.instruction if self.instruction else " ",
|
|
231
|
+
)
|
|
232
|
+
if not post_answer:
|
|
233
|
+
if self._multiline and self.status["result"]:
|
|
234
|
+
lines = self.status["result"].split("\n")
|
|
235
|
+
if len(lines) > 1:
|
|
236
|
+
number_of_chars = len("".join(lines[1:]))
|
|
237
|
+
lines[0] += "...[%s char%s]" % (
|
|
238
|
+
number_of_chars,
|
|
239
|
+
"s" if number_of_chars > 1 else "",
|
|
240
|
+
)
|
|
241
|
+
post_answer = ("class:answer", " %s" % lines[0])
|
|
242
|
+
else:
|
|
243
|
+
post_answer = ("class:answer", " %s" % self.status["result"])
|
|
244
|
+
|
|
245
|
+
formatted_message = super()._get_prompt_message(pre_answer, post_answer)
|
|
246
|
+
if not self.status["answered"] and self._multiline:
|
|
247
|
+
formatted_message.append(
|
|
248
|
+
("class:questionmark", "\n%s " % INQUIRERPY_POINTER_SEQUENCE)
|
|
249
|
+
)
|
|
250
|
+
return formatted_message
|
|
251
|
+
|
|
252
|
+
def _run(self) -> str:
|
|
253
|
+
return self._session.prompt(default=self._default)
|
|
254
|
+
|
|
255
|
+
async def _run_async(self) -> Any:
|
|
256
|
+
return await self._session.prompt_async(default=self._default)
|
|
@@ -0,0 +1,371 @@
|
|
|
1
|
+
"""Module contains the class to create a list prompt."""
|
|
2
|
+
|
|
3
|
+
import shutil
|
|
4
|
+
from typing import TYPE_CHECKING, Any, Callable, List, Optional, Tuple, Union
|
|
5
|
+
|
|
6
|
+
from prompt_toolkit.application.application import Application
|
|
7
|
+
from prompt_toolkit.filters.cli import IsDone
|
|
8
|
+
from prompt_toolkit.layout.containers import (
|
|
9
|
+
ConditionalContainer,
|
|
10
|
+
FloatContainer,
|
|
11
|
+
HSplit,
|
|
12
|
+
Window,
|
|
13
|
+
)
|
|
14
|
+
from prompt_toolkit.layout.controls import DummyControl
|
|
15
|
+
from prompt_toolkit.layout.dimension import Dimension
|
|
16
|
+
from prompt_toolkit.layout.layout import Layout
|
|
17
|
+
from prompt_toolkit.validation import ValidationError
|
|
18
|
+
from prompt_toolkit.widgets.base import Frame
|
|
19
|
+
|
|
20
|
+
from InquirerPy.base import InquirerPyUIListControl
|
|
21
|
+
from InquirerPy.base.complex import FakeDocument
|
|
22
|
+
from InquirerPy.base.list import BaseListPrompt
|
|
23
|
+
from InquirerPy.containers.instruction import InstructionWindow
|
|
24
|
+
from InquirerPy.containers.message import MessageWindow
|
|
25
|
+
from InquirerPy.containers.validation import ValidationFloat
|
|
26
|
+
from InquirerPy.enum import INQUIRERPY_POINTER_SEQUENCE
|
|
27
|
+
from InquirerPy.separator import Separator
|
|
28
|
+
from InquirerPy.utils import (
|
|
29
|
+
InquirerPyDefault,
|
|
30
|
+
InquirerPyKeybindings,
|
|
31
|
+
InquirerPyListChoices,
|
|
32
|
+
InquirerPyMessage,
|
|
33
|
+
InquirerPySessionResult,
|
|
34
|
+
InquirerPyStyle,
|
|
35
|
+
InquirerPyValidate,
|
|
36
|
+
calculate_height,
|
|
37
|
+
)
|
|
38
|
+
|
|
39
|
+
if TYPE_CHECKING:
|
|
40
|
+
from prompt_toolkit.key_binding.key_processor import KeyPressEvent
|
|
41
|
+
|
|
42
|
+
__all__ = ["ListPrompt"]
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class InquirerPyListControl(InquirerPyUIListControl):
|
|
46
|
+
"""An :class:`~prompt_toolkit.layout.UIControl` class that displays a list of choices.
|
|
47
|
+
|
|
48
|
+
Reference the parameter definition in :class:`.ListPrompt`.
|
|
49
|
+
"""
|
|
50
|
+
|
|
51
|
+
def __init__(
|
|
52
|
+
self,
|
|
53
|
+
choices: InquirerPyListChoices,
|
|
54
|
+
default: Any,
|
|
55
|
+
pointer: str,
|
|
56
|
+
marker: str,
|
|
57
|
+
session_result: Optional[InquirerPySessionResult],
|
|
58
|
+
multiselect: bool,
|
|
59
|
+
marker_pl: str,
|
|
60
|
+
) -> None:
|
|
61
|
+
self._pointer: str = pointer
|
|
62
|
+
self._marker: str = marker
|
|
63
|
+
self._marker_pl: str = marker_pl
|
|
64
|
+
super().__init__(
|
|
65
|
+
choices=choices,
|
|
66
|
+
default=default,
|
|
67
|
+
session_result=session_result,
|
|
68
|
+
multiselect=multiselect,
|
|
69
|
+
)
|
|
70
|
+
|
|
71
|
+
def _get_hover_text(self, choice) -> List[Tuple[str, str]]:
|
|
72
|
+
display_choices = []
|
|
73
|
+
display_choices.append(("class:pointer", self._pointer))
|
|
74
|
+
display_choices.append(
|
|
75
|
+
(
|
|
76
|
+
"class:marker",
|
|
77
|
+
self._marker if choice["enabled"] else self._marker_pl,
|
|
78
|
+
)
|
|
79
|
+
)
|
|
80
|
+
display_choices.append(("[SetCursorPosition]", ""))
|
|
81
|
+
display_choices.append(("class:pointer", choice["name"]))
|
|
82
|
+
return display_choices
|
|
83
|
+
|
|
84
|
+
def _get_normal_text(self, choice) -> List[Tuple[str, str]]:
|
|
85
|
+
display_choices = []
|
|
86
|
+
display_choices.append(("", len(self._pointer) * " "))
|
|
87
|
+
display_choices.append(
|
|
88
|
+
(
|
|
89
|
+
"class:marker",
|
|
90
|
+
self._marker if choice["enabled"] else self._marker_pl,
|
|
91
|
+
)
|
|
92
|
+
)
|
|
93
|
+
if not isinstance(choice["value"], Separator):
|
|
94
|
+
display_choices.append(("", choice["name"]))
|
|
95
|
+
else:
|
|
96
|
+
display_choices.append(("class:separator", choice["name"]))
|
|
97
|
+
return display_choices
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
class ListPrompt(BaseListPrompt):
|
|
101
|
+
"""Create a prompt that displays a list of choices to select.
|
|
102
|
+
|
|
103
|
+
A wrapper class around :class:`~prompt_toolkit.application.Application`.
|
|
104
|
+
|
|
105
|
+
Args:
|
|
106
|
+
message: The question to ask the user.
|
|
107
|
+
Refer to :ref:`pages/dynamic:message` documentation for more details.
|
|
108
|
+
choices: List of choices to display and select.
|
|
109
|
+
Refer to :ref:`pages/dynamic:choices` documentation for more details.
|
|
110
|
+
style: An :class:`InquirerPyStyle` instance.
|
|
111
|
+
Refer to :ref:`Style <pages/style:Alternate Syntax>` documentation for more details.
|
|
112
|
+
vi_mode: Use vim keybinding for the prompt.
|
|
113
|
+
Refer to :ref:`pages/kb:Keybindings` documentation for more details.
|
|
114
|
+
default: Set the default value of the prompt.
|
|
115
|
+
This will be used to determine which choice is highlighted (current selection),
|
|
116
|
+
The default value should be the value of one of the choices.
|
|
117
|
+
Refer to :ref:`pages/dynamic:default` documentation for more details.
|
|
118
|
+
qmark: Question mark symbol. Custom symbol that will be displayed infront of the question before its answered.
|
|
119
|
+
amark: Answer mark symbol. Custom symbol that will be displayed infront of the question after its answered.
|
|
120
|
+
pointer: Pointer symbol. Customer symbol that will be used to indicate the current choice selection.
|
|
121
|
+
instruction: Short instruction to display next to the question.
|
|
122
|
+
long_instruction: Long instructions to display at the bottom of the prompt.
|
|
123
|
+
validate: Add validation to user input.
|
|
124
|
+
The main use case for this prompt would be when `multiselect` is True, you can enforce a min/max selection.
|
|
125
|
+
Refer to :ref:`pages/validator:Validator` documentation for more details.
|
|
126
|
+
invalid_message: Error message to display when user input is invalid.
|
|
127
|
+
Refer to :ref:`pages/validator:Validator` documentation for more details.
|
|
128
|
+
transformer: A function which performs additional transformation on the value that gets printed to the terminal.
|
|
129
|
+
Different than `filter` parameter, this is only visual effect and won’t affect the actual value returned by :meth:`~InquirerPy.base.simple.BaseSimplePrompt.execute`.
|
|
130
|
+
Refer to :ref:`pages/dynamic:transformer` documentation for more details.
|
|
131
|
+
filter: A function which performs additional transformation on the result.
|
|
132
|
+
This affects the actual value returned by :meth:`~InquirerPy.base.simple.BaseSimplePrompt.execute`.
|
|
133
|
+
Refer to :ref:`pages/dynamic:filter` documentation for more details.
|
|
134
|
+
height: Preferred height of the prompt.
|
|
135
|
+
Refer to :ref:`pages/height:Height` documentation for more details.
|
|
136
|
+
max_height: Max height of the prompt.
|
|
137
|
+
Refer to :ref:`pages/height:Height` documentation for more details.
|
|
138
|
+
multiselect: Enable multi-selection on choices.
|
|
139
|
+
You can use `validate` parameter to control min/max selections.
|
|
140
|
+
Setting to True will also change the result from a single value to a list of values.
|
|
141
|
+
marker: Marker Symbol. Custom symbol to indicate if a choice is selected.
|
|
142
|
+
This will take effects when `multiselect` is True.
|
|
143
|
+
marker_pl: Marker place holder when the choice is not selected.
|
|
144
|
+
This is empty space by default.
|
|
145
|
+
border: Create border around the choice window.
|
|
146
|
+
keybindings: Customise the builtin keybindings.
|
|
147
|
+
Refer to :ref:`pages/kb:Keybindings` for more details.
|
|
148
|
+
show_cursor: Display cursor at the end of the prompt.
|
|
149
|
+
Set to False to hide the cursor.
|
|
150
|
+
cycle: Return to top item if hit bottom during navigation or vice versa.
|
|
151
|
+
wrap_lines: Soft wrap question lines when question exceeds the terminal width.
|
|
152
|
+
raise_keyboard_interrupt: Raise the :class:`KeyboardInterrupt` exception when `ctrl-c` is pressed. If false, the result
|
|
153
|
+
will be `None` and the question is skiped.
|
|
154
|
+
mandatory: Indicate if the prompt is mandatory. If True, then the question cannot be skipped.
|
|
155
|
+
mandatory_message: Error message to show when user attempts to skip mandatory prompt.
|
|
156
|
+
session_result: Used internally for :ref:`index:Classic Syntax (PyInquirer)`.
|
|
157
|
+
|
|
158
|
+
Examples:
|
|
159
|
+
>>> from InquirerPy import inquirer
|
|
160
|
+
>>> result = inquirer.select(message="Select one:", choices=[1, 2, 3]).execute()
|
|
161
|
+
>>> print(result)
|
|
162
|
+
1
|
|
163
|
+
"""
|
|
164
|
+
|
|
165
|
+
def __init__(
|
|
166
|
+
self,
|
|
167
|
+
message: InquirerPyMessage,
|
|
168
|
+
choices: InquirerPyListChoices,
|
|
169
|
+
default: InquirerPyDefault = None,
|
|
170
|
+
style: Optional[InquirerPyStyle] = None,
|
|
171
|
+
vi_mode: bool = False,
|
|
172
|
+
qmark: str = "?",
|
|
173
|
+
amark: str = "?",
|
|
174
|
+
pointer: str = INQUIRERPY_POINTER_SEQUENCE,
|
|
175
|
+
instruction: str = "",
|
|
176
|
+
long_instruction: str = "",
|
|
177
|
+
transformer: Optional[Callable[[Any], Any]] = None,
|
|
178
|
+
filter: Optional[Callable[[Any], Any]] = None,
|
|
179
|
+
height: Optional[Union[int, str]] = None,
|
|
180
|
+
max_height: Optional[Union[int, str]] = None,
|
|
181
|
+
multiselect: bool = False,
|
|
182
|
+
marker: str = INQUIRERPY_POINTER_SEQUENCE,
|
|
183
|
+
marker_pl: str = " ",
|
|
184
|
+
border: bool = False,
|
|
185
|
+
validate: Optional[InquirerPyValidate] = None,
|
|
186
|
+
invalid_message: str = "Invalid input",
|
|
187
|
+
keybindings: Optional[InquirerPyKeybindings] = None,
|
|
188
|
+
show_cursor: bool = True,
|
|
189
|
+
cycle: bool = True,
|
|
190
|
+
wrap_lines: bool = True,
|
|
191
|
+
raise_keyboard_interrupt: bool = True,
|
|
192
|
+
mandatory: bool = True,
|
|
193
|
+
mandatory_message: str = "Mandatory prompt",
|
|
194
|
+
session_result: Optional[InquirerPySessionResult] = None,
|
|
195
|
+
) -> None:
|
|
196
|
+
if not hasattr(self, "_content_control"):
|
|
197
|
+
self.content_control = InquirerPyListControl(
|
|
198
|
+
choices=choices,
|
|
199
|
+
default=default,
|
|
200
|
+
pointer=pointer,
|
|
201
|
+
marker=marker,
|
|
202
|
+
session_result=session_result,
|
|
203
|
+
multiselect=multiselect,
|
|
204
|
+
marker_pl=marker_pl,
|
|
205
|
+
)
|
|
206
|
+
super().__init__(
|
|
207
|
+
message=message,
|
|
208
|
+
style=style,
|
|
209
|
+
border=border,
|
|
210
|
+
vi_mode=vi_mode,
|
|
211
|
+
qmark=qmark,
|
|
212
|
+
amark=amark,
|
|
213
|
+
instruction=instruction,
|
|
214
|
+
long_instruction=long_instruction,
|
|
215
|
+
transformer=transformer,
|
|
216
|
+
filter=filter,
|
|
217
|
+
validate=validate,
|
|
218
|
+
invalid_message=invalid_message,
|
|
219
|
+
multiselect=multiselect,
|
|
220
|
+
keybindings=keybindings,
|
|
221
|
+
cycle=cycle,
|
|
222
|
+
wrap_lines=wrap_lines,
|
|
223
|
+
raise_keyboard_interrupt=raise_keyboard_interrupt,
|
|
224
|
+
mandatory=mandatory,
|
|
225
|
+
mandatory_message=mandatory_message,
|
|
226
|
+
session_result=session_result,
|
|
227
|
+
)
|
|
228
|
+
self._show_cursor = show_cursor
|
|
229
|
+
self._dimmension_height, self._dimmension_max_height = calculate_height(
|
|
230
|
+
height, max_height, height_offset=self.height_offset
|
|
231
|
+
)
|
|
232
|
+
main_content_window = Window(
|
|
233
|
+
content=self.content_control,
|
|
234
|
+
height=Dimension(
|
|
235
|
+
max=self._dimmension_max_height,
|
|
236
|
+
preferred=self._dimmension_height,
|
|
237
|
+
),
|
|
238
|
+
dont_extend_height=True,
|
|
239
|
+
)
|
|
240
|
+
|
|
241
|
+
if self._border:
|
|
242
|
+
main_content_window = Frame(main_content_window)
|
|
243
|
+
|
|
244
|
+
self._layout = FloatContainer(
|
|
245
|
+
content=HSplit(
|
|
246
|
+
[
|
|
247
|
+
MessageWindow(
|
|
248
|
+
message=(
|
|
249
|
+
self._get_prompt_message_with_cursor
|
|
250
|
+
if self._show_cursor
|
|
251
|
+
else self._get_prompt_message
|
|
252
|
+
),
|
|
253
|
+
filter=True,
|
|
254
|
+
wrap_lines=self._wrap_lines,
|
|
255
|
+
show_cursor=self._show_cursor,
|
|
256
|
+
),
|
|
257
|
+
ConditionalContainer(main_content_window, filter=~IsDone()),
|
|
258
|
+
ConditionalContainer(
|
|
259
|
+
Window(content=DummyControl()),
|
|
260
|
+
filter=~IsDone() & self._is_displaying_long_instruction,
|
|
261
|
+
),
|
|
262
|
+
InstructionWindow(
|
|
263
|
+
message=self._long_instruction,
|
|
264
|
+
filter=~IsDone() & self._is_displaying_long_instruction,
|
|
265
|
+
wrap_lines=self._wrap_lines,
|
|
266
|
+
),
|
|
267
|
+
]
|
|
268
|
+
),
|
|
269
|
+
floats=[
|
|
270
|
+
ValidationFloat(
|
|
271
|
+
invalid_message=self._get_error_message,
|
|
272
|
+
filter=self._is_invalid & ~IsDone(),
|
|
273
|
+
wrap_lines=self._wrap_lines,
|
|
274
|
+
left=0,
|
|
275
|
+
bottom=self._validation_window_bottom_offset,
|
|
276
|
+
),
|
|
277
|
+
],
|
|
278
|
+
)
|
|
279
|
+
|
|
280
|
+
self.application = Application(
|
|
281
|
+
layout=Layout(self._layout),
|
|
282
|
+
style=self._style,
|
|
283
|
+
key_bindings=self._kb,
|
|
284
|
+
after_render=self._after_render,
|
|
285
|
+
)
|
|
286
|
+
|
|
287
|
+
def _get_prompt_message_with_cursor(self) -> List[Tuple[str, str]]:
|
|
288
|
+
"""Obtain the prompt message to display and display cursor behind the message.
|
|
289
|
+
|
|
290
|
+
This ensures that cursor is always at the end of the window.
|
|
291
|
+
"""
|
|
292
|
+
message = self._get_prompt_message()
|
|
293
|
+
message.append(("[SetCursorPosition]", ""))
|
|
294
|
+
message.append(("", " ")) # [SetCursorPosition] require char behind it
|
|
295
|
+
return message
|
|
296
|
+
|
|
297
|
+
def _handle_toggle_choice(self, _) -> None:
|
|
298
|
+
"""Toggle the `enabled` status of the choice."""
|
|
299
|
+
if not self._multiselect:
|
|
300
|
+
return
|
|
301
|
+
self.content_control.selection["enabled"] = not self.content_control.selection[
|
|
302
|
+
"enabled"
|
|
303
|
+
]
|
|
304
|
+
|
|
305
|
+
def _handle_toggle_all(self, _, value: Optional[bool] = None) -> None:
|
|
306
|
+
"""Toggle all choice `enabled` status.
|
|
307
|
+
|
|
308
|
+
Args:
|
|
309
|
+
value: Sepcify a value to toggle.
|
|
310
|
+
"""
|
|
311
|
+
if not self._multiselect:
|
|
312
|
+
return
|
|
313
|
+
for choice in self.content_control.choices:
|
|
314
|
+
if isinstance(choice["value"], Separator):
|
|
315
|
+
continue
|
|
316
|
+
choice["enabled"] = value if value else not choice["enabled"]
|
|
317
|
+
|
|
318
|
+
def _handle_up(self, event) -> None:
|
|
319
|
+
"""Handle the event when user attempt to move up."""
|
|
320
|
+
while True:
|
|
321
|
+
cap = super()._handle_up(event)
|
|
322
|
+
if not isinstance(self.content_control.selection["value"], Separator):
|
|
323
|
+
break
|
|
324
|
+
else:
|
|
325
|
+
if cap and not self._cycle:
|
|
326
|
+
self._handle_down(event)
|
|
327
|
+
break
|
|
328
|
+
|
|
329
|
+
def _handle_down(self, event) -> None:
|
|
330
|
+
"""Handle the event when user attempt to move down."""
|
|
331
|
+
while True:
|
|
332
|
+
cap = super()._handle_down(event)
|
|
333
|
+
if not isinstance(self.content_control.selection["value"], Separator):
|
|
334
|
+
break
|
|
335
|
+
else:
|
|
336
|
+
if cap and not self._cycle:
|
|
337
|
+
self._handle_up(event)
|
|
338
|
+
break
|
|
339
|
+
|
|
340
|
+
def _handle_enter(self, event: "KeyPressEvent") -> None:
|
|
341
|
+
"""Handle the event when user hit `enter` key.
|
|
342
|
+
|
|
343
|
+
1. Set the prompt state to answered.
|
|
344
|
+
2. Set the result to the name of the selected choices.
|
|
345
|
+
3. Exit the app with the value of the selected choices.
|
|
346
|
+
|
|
347
|
+
In multiselect scenario, if nothing is selected, return the current highlighted choice.
|
|
348
|
+
"""
|
|
349
|
+
try:
|
|
350
|
+
fake_document = FakeDocument(self.result_value)
|
|
351
|
+
self._validator.validate(fake_document) # type: ignore
|
|
352
|
+
except ValidationError as e:
|
|
353
|
+
self._set_error(str(e))
|
|
354
|
+
else:
|
|
355
|
+
self.status["answered"] = True
|
|
356
|
+
if self._multiselect and not self.selected_choices:
|
|
357
|
+
self.status["result"] = [self.content_control.selection["name"]]
|
|
358
|
+
event.app.exit(result=[self.content_control.selection["value"]])
|
|
359
|
+
else:
|
|
360
|
+
self.status["result"] = self.result_name
|
|
361
|
+
event.app.exit(result=self.result_value)
|
|
362
|
+
|
|
363
|
+
@property
|
|
364
|
+
def extra_message_line_count(self) -> int:
|
|
365
|
+
"""int: Get extra lines created for message caused by line wrapping.
|
|
366
|
+
|
|
367
|
+
Overriding it to count the cursor as well.
|
|
368
|
+
"""
|
|
369
|
+
cursor_offset = -1 if not self._show_cursor else 0
|
|
370
|
+
term_width, _ = shutil.get_terminal_size()
|
|
371
|
+
return (self.total_message_length + cursor_offset) // term_width
|