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.
@@ -0,0 +1,109 @@
1
+ """Module contains spinner related resources.
2
+
3
+ Note:
4
+ The spinner is not a standalone spinner to run in the terminal
5
+ but rather a `prompt_toolkit` :class:`~prompt_toolkit.layout.Window` that displays a spinner.
6
+
7
+ Use library such as `yaspin <https://github.com/pavdmyt/yaspin>`_ if you need a plain spinner.
8
+ """
9
+
10
+ import asyncio
11
+ from typing import TYPE_CHECKING, Callable, List, NamedTuple, Optional, Tuple, Union
12
+
13
+ from prompt_toolkit.filters.utils import to_filter
14
+ from prompt_toolkit.layout.containers import ConditionalContainer, Window
15
+ from prompt_toolkit.layout.controls import FormattedTextControl
16
+
17
+ if TYPE_CHECKING:
18
+ from prompt_toolkit.filters.base import Filter
19
+
20
+ __all__ = ["SPINNERS", "SpinnerWindow"]
21
+
22
+
23
+ class SPINNERS(NamedTuple):
24
+ """Presets of spinner patterns.
25
+
26
+ See Also:
27
+ https://github.com/pavdmyt/yaspin/blob/master/yaspin/data/spinners.json
28
+
29
+ This only contains some basic ones thats ready to use. For more patterns, checkout the
30
+ URL above.
31
+
32
+ Examples:
33
+ >>> from InquirerPy import inquirer
34
+ >>> from InquirerPy.spinner import SPINNERS
35
+ >>> inquirer.select(message="", choices=lambda _: [1, 2, 3], spinner_pattern=SPINNERS.dots)
36
+ """
37
+
38
+ dots = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"]
39
+ dots2 = ["⣾", "⣽", "⣻", "⢿", "⡿", "⣟", "⣯", "⣷"]
40
+ line = ["-", "\\", "|", "/"]
41
+ line2 = ["⠂", "-", "–", "—", "–", "-"]
42
+ pipe = ["┤", "┘", "┴", "└", "├", "┌", "┬", "┐"]
43
+ star = ["✶", "✸", "✹", "✺", "✹", "✷"]
44
+ star2 = ["+", "x", "*"]
45
+ flip = ["_", "_", "_", "-", "`", "`", "'", "´", "-", "_", "_", "_"]
46
+ hamburger = ["☱", "☲", "☴"]
47
+ grow_vertical = ["▁", "▃", "▄", "▅", "▆", "▇", "▆", "▅", "▄", "▃"]
48
+ grow_horizontal = ["▏", "▎", "▍", "▌", "▋", "▊", "▉", "▊", "▋", "▌", "▍", "▎"]
49
+ box_bounce = ["▖", "▘", "▝", "▗"]
50
+ triangle = ["◢", "◣", "◤", "◥"]
51
+ arc = ["◜", "◠", "◝", "◞", "◡", "◟"]
52
+ circle = ["◡", "⊙", "◠"]
53
+
54
+
55
+ class SpinnerWindow(ConditionalContainer):
56
+ """Conditional `prompt_toolkit` :class:`~prompt_toolkit.layout.Window` that displays a spinner.
57
+
58
+ Args:
59
+ loading: A :class:`~prompt_toolkit.filters.Condition` to indicate if the spinner should be visible.
60
+ redraw: A redraw function (i.e. :meth:`~prompt_toolkit.application.Application.invalidate`) to refresh the UI.
61
+ pattern: List of pattern to display as the spinner.
62
+ delay: Spinner refresh frequency.
63
+ text: Loading text to display.
64
+ """
65
+
66
+ def __init__(
67
+ self,
68
+ loading: "Filter",
69
+ redraw: Callable[[], None],
70
+ pattern: Optional[Union[List[str], SPINNERS]] = None,
71
+ delay: float = 0.1,
72
+ text: str = "",
73
+ ) -> None:
74
+ self._loading = to_filter(loading)
75
+ self._spinning = False
76
+ self._redraw = redraw
77
+ self._pattern = pattern or SPINNERS.line
78
+ self._char = self._pattern[0]
79
+ self._delay = delay
80
+ self._text = text or "Loading ..."
81
+
82
+ super().__init__(
83
+ content=Window(content=FormattedTextControl(text=self._get_text)),
84
+ filter=self._loading,
85
+ )
86
+
87
+ def _get_text(self) -> List[Tuple[str, str]]:
88
+ """Dynamically get the text for the :class:`~prompt_toolkit.layout.Window`.
89
+
90
+ Returns:
91
+ Formatted text.
92
+ """
93
+ return [
94
+ ("class:spinner_pattern", self._char),
95
+ ("", " "),
96
+ ("class:spinner_text", self._text),
97
+ ]
98
+
99
+ async def start(self) -> None:
100
+ """Start the spinner."""
101
+ if self._spinning:
102
+ return
103
+ self._spinning = True
104
+ while self._loading():
105
+ for char in self._pattern:
106
+ await asyncio.sleep(self._delay)
107
+ self._char = char
108
+ self._redraw()
109
+ self._spinning = False
@@ -0,0 +1,60 @@
1
+ """Module contains :class:`.ValidationWindow` which can be used to display error."""
2
+
3
+ from typing import Optional
4
+
5
+ from prompt_toolkit.filters.base import FilterOrBool
6
+ from prompt_toolkit.formatted_text.base import AnyFormattedText
7
+ from prompt_toolkit.layout.containers import ConditionalContainer, Float, Window
8
+ from prompt_toolkit.layout.controls import FormattedTextControl
9
+
10
+
11
+ class ValidationWindow(ConditionalContainer):
12
+ """Conditional `prompt_toolkit` :class:`~prompt_toolkit.layout.Window` that displays error.
13
+
14
+ Args:
15
+ invalid_message: Error message to display when error occured.
16
+ filter: Condition to display the error window.
17
+ """
18
+
19
+ def __init__(
20
+ self, invalid_message: AnyFormattedText, filter: FilterOrBool, **kwargs
21
+ ) -> None:
22
+ super().__init__(
23
+ Window(
24
+ FormattedTextControl(invalid_message), dont_extend_height=True, **kwargs
25
+ ),
26
+ filter=filter,
27
+ )
28
+
29
+
30
+ class ValidationFloat(Float):
31
+ """:class:`~prompt_toolkit.layout.Float` wrapper around :class:`.ValidationWindow`.
32
+
33
+ Args:
34
+ invalid_message: Error message to display when error occured.
35
+ filter: Condition to display the error window.
36
+ left: Distance to left.
37
+ right: Distance to right.
38
+ bottom: Distance to bottom.
39
+ top: Distance to top.
40
+ """
41
+
42
+ def __init__(
43
+ self,
44
+ invalid_message: AnyFormattedText,
45
+ filter: FilterOrBool,
46
+ left: Optional[int] = None,
47
+ right: Optional[int] = None,
48
+ bottom: Optional[int] = None,
49
+ top: Optional[int] = None,
50
+ **kwargs
51
+ ) -> None:
52
+ super().__init__(
53
+ content=ValidationWindow(
54
+ invalid_message=invalid_message, filter=filter, **kwargs
55
+ ),
56
+ left=left,
57
+ right=right,
58
+ bottom=bottom,
59
+ top=top,
60
+ )
InquirerPy/enum.py ADDED
@@ -0,0 +1,8 @@
1
+ """Module contains common constants."""
2
+
3
+ INQUIRERPY_KEYBOARD_INTERRUPT: str = "INQUIRERPY_KEYBOARD_INTERRUPT"
4
+
5
+ INQUIRERPY_POINTER_SEQUENCE: str = "\u276f"
6
+ INQUIRERPY_FILL_CIRCLE_SEQUENCE: str = "\u25c9"
7
+ INQUIRERPY_EMPTY_CIRCLE_SEQUENCE: str = "\u25cb"
8
+ INQUIRERPY_QMARK_SEQUENCE: str = "\u003f"
@@ -0,0 +1,25 @@
1
+ """Module contains exceptions that will be raised by `InquirerPy`."""
2
+
3
+
4
+ class InvalidArgument(Exception):
5
+ """Provided argument is invalid.
6
+
7
+ Args:
8
+ message: Exception message.
9
+ """
10
+
11
+ def __init__(self, message: str = "invalid argument"):
12
+ self._message = message
13
+ super().__init__(self._message)
14
+
15
+
16
+ class RequiredKeyNotFound(Exception):
17
+ """Missing required keys in dictionary.
18
+
19
+ Args:
20
+ message: Exception message.
21
+ """
22
+
23
+ def __init__(self, message="required key not found"):
24
+ self.message = message
25
+ super().__init__(self.message)
InquirerPy/inquirer.py ADDED
@@ -0,0 +1,31 @@
1
+ """Servers as another entry point for `InquirerPy`.
2
+
3
+ See Also:
4
+ :ref:`index:Alternate Syntax`.
5
+
6
+ `inquirer` directly interact with individual prompt classes. It’s more flexible, easier to customise and also provides IDE type hintings/completions.
7
+ """
8
+
9
+ __all__ = [
10
+ "checkbox",
11
+ "confirm",
12
+ "expand",
13
+ "filepath",
14
+ "fuzzy",
15
+ "text",
16
+ "select",
17
+ "number",
18
+ "rawlist",
19
+ "secret",
20
+ ]
21
+
22
+ from InquirerPy.prompts import CheckboxPrompt as checkbox
23
+ from InquirerPy.prompts import ConfirmPrompt as confirm
24
+ from InquirerPy.prompts import ExpandPrompt as expand
25
+ from InquirerPy.prompts import FilePathPrompt as filepath
26
+ from InquirerPy.prompts import FuzzyPrompt as fuzzy
27
+ from InquirerPy.prompts import InputPrompt as text
28
+ from InquirerPy.prompts import ListPrompt as select
29
+ from InquirerPy.prompts import NumberPrompt as number
30
+ from InquirerPy.prompts import RawlistPrompt as rawlist
31
+ from InquirerPy.prompts import SecretPrompt as secret
@@ -0,0 +1,25 @@
1
+ """Module contains import of all prompts classes."""
2
+
3
+ __all__ = [
4
+ "CheckboxPrompt",
5
+ "ConfirmPrompt",
6
+ "ExpandPrompt",
7
+ "FilePathPrompt",
8
+ "FuzzyPrompt",
9
+ "InputPrompt",
10
+ "ListPrompt",
11
+ "NumberPrompt",
12
+ "RawlistPrompt",
13
+ "SecretPrompt",
14
+ ]
15
+
16
+ from InquirerPy.prompts.checkbox import CheckboxPrompt
17
+ from InquirerPy.prompts.confirm import ConfirmPrompt
18
+ from InquirerPy.prompts.expand import ExpandPrompt
19
+ from InquirerPy.prompts.filepath import FilePathPrompt
20
+ from InquirerPy.prompts.fuzzy import FuzzyPrompt
21
+ from InquirerPy.prompts.input import InputPrompt
22
+ from InquirerPy.prompts.list import ListPrompt
23
+ from InquirerPy.prompts.number import NumberPrompt
24
+ from InquirerPy.prompts.rawlist import RawlistPrompt
25
+ from InquirerPy.prompts.secret import SecretPrompt
@@ -0,0 +1,249 @@
1
+ """Module contains the class to create a checkbox prompt."""
2
+
3
+ from typing import Any, Callable, List, Optional, Tuple, Union
4
+
5
+ from prompt_toolkit.validation import ValidationError
6
+
7
+ from InquirerPy.base import FakeDocument, InquirerPyUIListControl
8
+ from InquirerPy.enum import (
9
+ INQUIRERPY_EMPTY_CIRCLE_SEQUENCE,
10
+ INQUIRERPY_FILL_CIRCLE_SEQUENCE,
11
+ INQUIRERPY_POINTER_SEQUENCE,
12
+ )
13
+ from InquirerPy.prompts.list import ListPrompt
14
+ from InquirerPy.separator import Separator
15
+ from InquirerPy.utils import (
16
+ InquirerPyKeybindings,
17
+ InquirerPyListChoices,
18
+ InquirerPyMessage,
19
+ InquirerPySessionResult,
20
+ InquirerPyStyle,
21
+ InquirerPyValidate,
22
+ )
23
+
24
+ __all__ = ["CheckboxPrompt"]
25
+
26
+
27
+ class InquirerPyCheckboxControl(InquirerPyUIListControl):
28
+ """An :class:`~prompt_toolkit.layout.UIControl` class that displays a list of choices.
29
+
30
+ Reference the parameter definition in :class:`.CheckboxPrompt`.
31
+ """
32
+
33
+ def __init__(
34
+ self,
35
+ choices: InquirerPyListChoices,
36
+ default: Any,
37
+ pointer: str,
38
+ enabled_symbol: str,
39
+ disabled_symbol: str,
40
+ session_result: Optional[InquirerPySessionResult],
41
+ ) -> None:
42
+ """Initialise required attributes and call base class."""
43
+ self._pointer = pointer
44
+ self._enabled_symbol = enabled_symbol
45
+ self._disabled_symbol = disabled_symbol
46
+ super().__init__(
47
+ choices=choices,
48
+ default=default,
49
+ session_result=session_result,
50
+ multiselect=True,
51
+ )
52
+
53
+ def _format_choices(self) -> None:
54
+ pass
55
+
56
+ def _get_hover_text(self, choice) -> List[Tuple[str, str]]:
57
+ display_choices = []
58
+ display_choices.append(("class:pointer", self._pointer))
59
+ if self._pointer:
60
+ display_choices.append(("", " "))
61
+ if not isinstance(choice["value"], Separator):
62
+ display_choices.append(
63
+ (
64
+ "class:checkbox",
65
+ (
66
+ self._enabled_symbol
67
+ if choice["enabled"]
68
+ else self._disabled_symbol
69
+ ),
70
+ )
71
+ )
72
+ if self._enabled_symbol and self._disabled_symbol:
73
+ display_choices.append(("", " "))
74
+ display_choices.append(("[SetCursorPosition]", ""))
75
+ display_choices.append(("class:pointer", choice["name"]))
76
+ return display_choices
77
+
78
+ def _get_normal_text(self, choice) -> List[Tuple[str, str]]:
79
+ display_choices = []
80
+ display_choices.append(("", len(self._pointer) * " "))
81
+ if self._pointer:
82
+ display_choices.append(("", " "))
83
+ if not isinstance(choice["value"], Separator):
84
+ display_choices.append(
85
+ (
86
+ "class:checkbox",
87
+ (
88
+ self._enabled_symbol
89
+ if choice["enabled"]
90
+ else self._disabled_symbol
91
+ ),
92
+ )
93
+ )
94
+ if self._enabled_symbol and self._disabled_symbol:
95
+ display_choices.append(("", " "))
96
+ display_choices.append(("", choice["name"]))
97
+ else:
98
+ display_choices.append(("class:separator", choice["name"]))
99
+ return display_choices
100
+
101
+
102
+ class CheckboxPrompt(ListPrompt):
103
+ """Create a prompt which displays a list of checkboxes to toggle.
104
+
105
+ A wrapper class around :class:`~prompt_toolkit.application.Application`.
106
+
107
+ User can toggle on/off on each checkbox.
108
+
109
+ Works very similar to :class:`~InquirerPy.prompts.list.ListPrompt` with `multiselect` enabled,
110
+ the main difference is visual/UI and also when not toggling anything, the result will be empty.
111
+
112
+ Args:
113
+ message: The question to ask the user.
114
+ Refer to :ref:`pages/dynamic:message` documentation for more details.
115
+ choices: List of choices to display and select.
116
+ Refer to :ref:`pages/dynamic:choices` documentation for more details.
117
+ style: An :class:`InquirerPyStyle` instance.
118
+ Refer to :ref:`Style <pages/style:Alternate Syntax>` documentation for more details.
119
+ vi_mode: Use vim keybinding for the prompt.
120
+ Refer to :ref:`pages/kb:Keybindings` documentation for more details.
121
+ default: Set the default value of the prompt.
122
+ This will be used to determine which choice is highlighted (current selection),
123
+ The default value should be the value of one of the choices.
124
+ Refer to :ref:`pages/dynamic:default` documentation for more details.
125
+ separator: Separator symbol. Custom symbol that will be used as a separator between the choice index number and the choices.
126
+ qmark: Question mark symbol. Custom symbol that will be displayed infront of the question before its answered.
127
+ amark: Answer mark symbol. Custom symbol that will be displayed infront of the question after its answered.
128
+ pointer: Pointer symbol. Customer symbol that will be used to indicate the current choice selection.
129
+ enabled_symbol: Checkbox ticked symbol. Custom symbol which indicate the checkbox is ticked.
130
+ disabled_symbol: Checkbox not ticked symbol. Custom symbol which indicate the checkbox is not ticked.
131
+ instruction: Short instruction to display next to the question.
132
+ long_instruction: Long instructions to display at the bottom of the prompt.
133
+ validate: Add validation to user input.
134
+ The main use case for this prompt would be when `multiselect` is True, you can enforce a min/max selection.
135
+ Refer to :ref:`pages/validator:Validator` documentation for more details.
136
+ invalid_message: Error message to display when user input is invalid.
137
+ Refer to :ref:`pages/validator:Validator` documentation for more details.
138
+ transformer: A function which performs additional transformation on the value that gets printed to the terminal.
139
+ Different than `filter` parameter, this is only visual effect and won’t affect the actual value returned by :meth:`~InquirerPy.base.simple.BaseSimplePrompt.execute`.
140
+ Refer to :ref:`pages/dynamic:transformer` documentation for more details.
141
+ filter: A function which performs additional transformation on the result.
142
+ This affects the actual value returned by :meth:`~InquirerPy.base.simple.BaseSimplePrompt.execute`.
143
+ Refer to :ref:`pages/dynamic:filter` documentation for more details.
144
+ height: Preferred height of the prompt.
145
+ Refer to :ref:`pages/height:Height` documentation for more details.
146
+ max_height: Max height of the prompt.
147
+ Refer to :ref:`pages/height:Height` documentation for more details.
148
+ border: Create border around the choice window.
149
+ keybindings: Customise the builtin keybindings.
150
+ Refer to :ref:`pages/kb:Keybindings` for more details.
151
+ show_cursor: Display cursor at the end of the prompt.
152
+ Set to False to hide the cursor.
153
+ cycle: Return to top item if hit bottom during navigation or vice versa.
154
+ wrap_lines: Soft wrap question lines when question exceeds the terminal width.
155
+ raise_keyboard_interrupt: Raise the :class:`KeyboardInterrupt` exception when `ctrl-c` is pressed. If false, the result
156
+ will be `None` and the question is skiped.
157
+ mandatory: Indicate if the prompt is mandatory. If True, then the question cannot be skipped.
158
+ mandatory_message: Error message to show when user attempts to skip mandatory prompt.
159
+ session_result: Used internally for :ref:`index:Classic Syntax (PyInquirer)`.
160
+
161
+ Examples:
162
+ >>> from InquirerPy import inquirer
163
+ >>> result = inquirer.checkbox(message="Select:", choices=[1, 2, 3]).execute()
164
+ >>> print(result)
165
+ [1]
166
+ """
167
+
168
+ def __init__(
169
+ self,
170
+ message: InquirerPyMessage,
171
+ choices: InquirerPyListChoices,
172
+ default: Any = None,
173
+ style: Optional[InquirerPyStyle] = None,
174
+ vi_mode: bool = False,
175
+ qmark: str = "?",
176
+ amark: str = "?",
177
+ pointer: str = INQUIRERPY_POINTER_SEQUENCE,
178
+ enabled_symbol: str = INQUIRERPY_FILL_CIRCLE_SEQUENCE,
179
+ disabled_symbol: str = INQUIRERPY_EMPTY_CIRCLE_SEQUENCE,
180
+ border: bool = False,
181
+ instruction: str = "",
182
+ long_instruction: str = "",
183
+ transformer: Optional[Callable[[Any], Any]] = None,
184
+ filter: Optional[Callable[[Any], Any]] = None,
185
+ height: Optional[Union[int, str]] = None,
186
+ max_height: Optional[Union[int, str]] = None,
187
+ validate: Optional[InquirerPyValidate] = None,
188
+ invalid_message: str = "Invalid input",
189
+ keybindings: Optional[InquirerPyKeybindings] = None,
190
+ show_cursor: bool = True,
191
+ cycle: bool = True,
192
+ wrap_lines: bool = True,
193
+ raise_keyboard_interrupt: bool = True,
194
+ mandatory: bool = True,
195
+ mandatory_message: str = "Mandatory prompt",
196
+ session_result: Optional[InquirerPySessionResult] = None,
197
+ ) -> None:
198
+ self.content_control = InquirerPyCheckboxControl(
199
+ choices=choices,
200
+ default=default,
201
+ pointer=pointer,
202
+ enabled_symbol=enabled_symbol,
203
+ disabled_symbol=disabled_symbol,
204
+ session_result=session_result,
205
+ )
206
+ super().__init__(
207
+ message=message,
208
+ choices=choices,
209
+ style=style,
210
+ border=border,
211
+ vi_mode=vi_mode,
212
+ qmark=qmark,
213
+ amark=amark,
214
+ instruction=instruction,
215
+ long_instruction=long_instruction,
216
+ transformer=transformer,
217
+ filter=filter,
218
+ height=height,
219
+ max_height=max_height,
220
+ validate=validate,
221
+ invalid_message=invalid_message,
222
+ multiselect=True,
223
+ keybindings=keybindings,
224
+ show_cursor=show_cursor,
225
+ cycle=cycle,
226
+ wrap_lines=wrap_lines,
227
+ raise_keyboard_interrupt=raise_keyboard_interrupt,
228
+ mandatory=mandatory,
229
+ mandatory_message=mandatory_message,
230
+ session_result=session_result,
231
+ )
232
+
233
+ def _handle_enter(self, event) -> None:
234
+ """Override this method to force empty array result.
235
+
236
+ When user does not select anything, exit with empty list.
237
+
238
+ Args:
239
+ event: Keypress event.
240
+ """
241
+ try:
242
+ fake_document = FakeDocument(self.result_value)
243
+ self._validator.validate(fake_document) # type: ignore
244
+ except ValidationError:
245
+ self._invalid = True
246
+ else:
247
+ self.status["answered"] = True
248
+ self.status["result"] = self.result_name
249
+ event.app.exit(result=self.result_value)