PyInquirer 1.0.4__py2.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.
- PyInquirer/__init__.py +29 -0
- PyInquirer/color_print.py +41 -0
- PyInquirer/prompt.py +106 -0
- PyInquirer/prompts/__init__.py +0 -0
- PyInquirer/prompts/checkbox.py +256 -0
- PyInquirer/prompts/common.py +92 -0
- PyInquirer/prompts/confirm.py +86 -0
- PyInquirer/prompts/editor.py +182 -0
- PyInquirer/prompts/expand.py +195 -0
- PyInquirer/prompts/input.py +62 -0
- PyInquirer/prompts/list.py +191 -0
- PyInquirer/prompts/password.py +14 -0
- PyInquirer/prompts/rawlist.py +183 -0
- PyInquirer/separator.py +15 -0
- PyInquirer/utils.py +34 -0
- examples/__init__.py +33 -0
- examples/checkbox.py +71 -0
- examples/confirm.py +32 -0
- examples/editor.py +28 -0
- examples/expand.py +46 -0
- examples/hierarchical.py +87 -0
- examples/input.py +47 -0
- examples/list.py +55 -0
- examples/password.py +21 -0
- examples/pizza.py +110 -0
- examples/rawlist.py +36 -0
- examples/when.py +46 -0
- pyinquirer-1.0.4.dist-info/METADATA +403 -0
- pyinquirer-1.0.4.dist-info/RECORD +32 -0
- pyinquirer-1.0.4.dist-info/WHEEL +6 -0
- pyinquirer-1.0.4.dist-info/licenses/LICENSE +19 -0
- pyinquirer-1.0.4.dist-info/top_level.txt +2 -0
PyInquirer/__init__.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
|
|
3
|
+
from __future__ import absolute_import, print_function
|
|
4
|
+
import os
|
|
5
|
+
|
|
6
|
+
from prompt_toolkit.token import Token
|
|
7
|
+
from prompt_toolkit.styles import style_from_dict
|
|
8
|
+
from prompt_toolkit.validation import Validator, ValidationError
|
|
9
|
+
|
|
10
|
+
from .utils import print_json, format_json
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
__version__ = '1.0.4'
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def here(p):
|
|
17
|
+
return os.path.abspath(os.path.join(os.path.dirname(__file__), p))
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class PromptParameterException(ValueError):
|
|
21
|
+
def __init__(self, message, errors=None):
|
|
22
|
+
|
|
23
|
+
# Call the base class constructor with the parameters it needs
|
|
24
|
+
super(PromptParameterException, self).__init__(
|
|
25
|
+
'You must provide a `%s` value' % message, errors)
|
|
26
|
+
|
|
27
|
+
from .prompt import prompt
|
|
28
|
+
from .separator import Separator
|
|
29
|
+
from .prompts.common import default_style
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""
|
|
3
|
+
provide colorized output
|
|
4
|
+
"""
|
|
5
|
+
from __future__ import print_function, unicode_literals
|
|
6
|
+
import sys
|
|
7
|
+
from prompt_toolkit.shortcuts import print_tokens, style_from_dict, Token
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def _print_token_factory(col):
|
|
11
|
+
"""Internal helper to provide color names."""
|
|
12
|
+
def _helper(msg):
|
|
13
|
+
style = style_from_dict({
|
|
14
|
+
Token.Color: col,
|
|
15
|
+
})
|
|
16
|
+
tokens = [
|
|
17
|
+
(Token.Color, msg)
|
|
18
|
+
]
|
|
19
|
+
print_tokens(tokens, style=style)
|
|
20
|
+
|
|
21
|
+
def _helper_no_terminal(msg):
|
|
22
|
+
# workaround if we have no terminal
|
|
23
|
+
print(msg)
|
|
24
|
+
if sys.stdout.isatty():
|
|
25
|
+
return _helper
|
|
26
|
+
else:
|
|
27
|
+
return _helper_no_terminal
|
|
28
|
+
|
|
29
|
+
# used this for color source:
|
|
30
|
+
# http://unix.stackexchange.com/questions/105568/how-can-i-list-the-available-color-names
|
|
31
|
+
yellow = _print_token_factory('#dfaf00')
|
|
32
|
+
blue = _print_token_factory('#0087ff')
|
|
33
|
+
gray = _print_token_factory('#6c6c6c')
|
|
34
|
+
|
|
35
|
+
# TODO
|
|
36
|
+
#black
|
|
37
|
+
#red
|
|
38
|
+
#green
|
|
39
|
+
#magenta
|
|
40
|
+
#cyan
|
|
41
|
+
#white
|
PyInquirer/prompt.py
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
|
|
3
|
+
from __future__ import absolute_import, print_function
|
|
4
|
+
|
|
5
|
+
from prompt_toolkit.shortcuts import run_application
|
|
6
|
+
|
|
7
|
+
from . import PromptParameterException, prompts
|
|
8
|
+
from .prompts import list, confirm, input, password, checkbox, rawlist, expand, editor
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def prompt(questions, answers=None, **kwargs):
|
|
12
|
+
if isinstance(questions, dict):
|
|
13
|
+
questions = [questions]
|
|
14
|
+
answers = answers or {}
|
|
15
|
+
|
|
16
|
+
patch_stdout = kwargs.pop('patch_stdout', False)
|
|
17
|
+
return_asyncio_coroutine = kwargs.pop('return_asyncio_coroutine', False)
|
|
18
|
+
true_color = kwargs.pop('true_color', False)
|
|
19
|
+
refresh_interval = kwargs.pop('refresh_interval', 0)
|
|
20
|
+
eventloop = kwargs.pop('eventloop', None)
|
|
21
|
+
raise_kbi = kwargs.pop('raise_keyboard_interrupt', False)
|
|
22
|
+
kbi_msg = kwargs.pop('keyboard_interrupt_msg', 'Cancelled by user')
|
|
23
|
+
|
|
24
|
+
for question in questions:
|
|
25
|
+
# import the question
|
|
26
|
+
if 'type' not in question:
|
|
27
|
+
raise PromptParameterException('type')
|
|
28
|
+
if 'name' not in question:
|
|
29
|
+
raise PromptParameterException('name')
|
|
30
|
+
if 'message' not in question:
|
|
31
|
+
raise PromptParameterException('message')
|
|
32
|
+
try:
|
|
33
|
+
choices = question.get('choices')
|
|
34
|
+
if choices is not None and callable(choices):
|
|
35
|
+
question['choices'] = choices(answers)
|
|
36
|
+
|
|
37
|
+
_kwargs = {}
|
|
38
|
+
_kwargs.update(kwargs)
|
|
39
|
+
_kwargs.update(question)
|
|
40
|
+
type = _kwargs.pop('type')
|
|
41
|
+
name = _kwargs.pop('name')
|
|
42
|
+
message = _kwargs.pop('message')
|
|
43
|
+
when = _kwargs.pop('when', None)
|
|
44
|
+
filter = _kwargs.pop('filter', None)
|
|
45
|
+
|
|
46
|
+
if when is not None:
|
|
47
|
+
# at least a little sanity check!
|
|
48
|
+
if callable(question['when']):
|
|
49
|
+
try:
|
|
50
|
+
if not question['when'](answers):
|
|
51
|
+
continue
|
|
52
|
+
except Exception as e:
|
|
53
|
+
raise ValueError(
|
|
54
|
+
'Problem in \'when\' check of %s question: %s' %
|
|
55
|
+
(name, e))
|
|
56
|
+
elif when is False:
|
|
57
|
+
continue
|
|
58
|
+
elif when and when is not True:
|
|
59
|
+
raise ValueError('\'when\' needs to be function that ' \
|
|
60
|
+
'accepts a dict argument')
|
|
61
|
+
if filter:
|
|
62
|
+
# at least a little sanity check!
|
|
63
|
+
if not callable(question['filter']):
|
|
64
|
+
raise ValueError('\'filter\' needs to be function that ' \
|
|
65
|
+
'accepts an argument')
|
|
66
|
+
|
|
67
|
+
if callable(question.get('default')):
|
|
68
|
+
_kwargs['default'] = question['default'](answers)
|
|
69
|
+
|
|
70
|
+
if callable(message):
|
|
71
|
+
message = message(answers)
|
|
72
|
+
|
|
73
|
+
application = getattr(prompts, type).question(message, **_kwargs)
|
|
74
|
+
|
|
75
|
+
answer = run_application(
|
|
76
|
+
application,
|
|
77
|
+
patch_stdout=patch_stdout,
|
|
78
|
+
return_asyncio_coroutine=return_asyncio_coroutine,
|
|
79
|
+
true_color=true_color,
|
|
80
|
+
refresh_interval=refresh_interval,
|
|
81
|
+
eventloop=eventloop)
|
|
82
|
+
|
|
83
|
+
if answer is not None:
|
|
84
|
+
if filter:
|
|
85
|
+
try:
|
|
86
|
+
answer = question['filter'](answer)
|
|
87
|
+
except Exception as e:
|
|
88
|
+
raise ValueError(
|
|
89
|
+
'Problem processing \'filter\' of %s question: %s' %
|
|
90
|
+
(name, e))
|
|
91
|
+
answers[name] = answer
|
|
92
|
+
except AttributeError as e:
|
|
93
|
+
print(e)
|
|
94
|
+
raise ValueError('No question type \'%s\'' % type)
|
|
95
|
+
except KeyboardInterrupt:
|
|
96
|
+
if raise_kbi:
|
|
97
|
+
raise
|
|
98
|
+
print('')
|
|
99
|
+
print(kbi_msg)
|
|
100
|
+
print('')
|
|
101
|
+
return {}
|
|
102
|
+
return answers
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
# TODO:
|
|
106
|
+
# Bottom Bar - inquirer.ui.BottomBar
|
|
File without changes
|
|
@@ -0,0 +1,256 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""
|
|
3
|
+
`checkbox` type question
|
|
4
|
+
"""
|
|
5
|
+
from __future__ import print_function, unicode_literals
|
|
6
|
+
from prompt_toolkit.application import Application
|
|
7
|
+
from prompt_toolkit.key_binding.manager import KeyBindingManager
|
|
8
|
+
from prompt_toolkit.keys import Keys
|
|
9
|
+
from prompt_toolkit.layout.containers import Window
|
|
10
|
+
from prompt_toolkit.filters import Condition, IsDone
|
|
11
|
+
from prompt_toolkit.layout.controls import TokenListControl
|
|
12
|
+
from prompt_toolkit.layout.containers import ConditionalContainer, \
|
|
13
|
+
ScrollOffsets, HSplit
|
|
14
|
+
from prompt_toolkit.layout.dimension import LayoutDimension as D
|
|
15
|
+
from prompt_toolkit.token import Token
|
|
16
|
+
from prompt_toolkit.validation import ValidationError
|
|
17
|
+
|
|
18
|
+
from .. import PromptParameterException
|
|
19
|
+
from ..separator import Separator
|
|
20
|
+
from .common import setup_simple_validator, default_style, if_mousedown
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
# custom control based on TokenListControl
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class InquirerControl(TokenListControl):
|
|
27
|
+
def __init__(self, choices, **kwargs):
|
|
28
|
+
self.pointer_index = 0
|
|
29
|
+
self.selected_options = [] # list of names
|
|
30
|
+
self.answered = False
|
|
31
|
+
self.error_message = None
|
|
32
|
+
self._init_choices(choices)
|
|
33
|
+
super(InquirerControl, self).__init__(self._get_choice_tokens,
|
|
34
|
+
**kwargs)
|
|
35
|
+
|
|
36
|
+
def _init_choices(self, choices):
|
|
37
|
+
# helper to convert from question format to internal format
|
|
38
|
+
self.choices = [] # list (name, value)
|
|
39
|
+
searching_first_choice = True
|
|
40
|
+
for i, c in enumerate(choices):
|
|
41
|
+
if isinstance(c, Separator):
|
|
42
|
+
self.choices.append(c)
|
|
43
|
+
else:
|
|
44
|
+
if not hasattr(c, 'get'): # not a dict
|
|
45
|
+
c = {'name': c}
|
|
46
|
+
name = c['name']
|
|
47
|
+
value = c.get('value', name)
|
|
48
|
+
disabled = c.get('disabled', None)
|
|
49
|
+
if 'checked' in c and c['checked'] and not disabled:
|
|
50
|
+
self.selected_options.append(value)
|
|
51
|
+
self.choices.append((name, value, disabled))
|
|
52
|
+
if searching_first_choice and not disabled: # find the first (available) choice
|
|
53
|
+
self.pointer_index = i
|
|
54
|
+
searching_first_choice = False
|
|
55
|
+
|
|
56
|
+
@property
|
|
57
|
+
def choice_count(self):
|
|
58
|
+
return len(self.choices)
|
|
59
|
+
|
|
60
|
+
def _get_choice_tokens(self, cli):
|
|
61
|
+
tokens = []
|
|
62
|
+
T = Token
|
|
63
|
+
|
|
64
|
+
def append(index, line):
|
|
65
|
+
if isinstance(line, Separator):
|
|
66
|
+
tokens.append((T.Separator, ' %s\n' % line))
|
|
67
|
+
else:
|
|
68
|
+
line_name = line[0]
|
|
69
|
+
line_value = line[1]
|
|
70
|
+
selected = (line_value in self.selected_options) # use value to check if option has been selected
|
|
71
|
+
pointed_at = (index == self.pointer_index)
|
|
72
|
+
|
|
73
|
+
@if_mousedown
|
|
74
|
+
def select_item(cli, mouse_event):
|
|
75
|
+
# bind option with this index to mouse event
|
|
76
|
+
self.error_message = None
|
|
77
|
+
if line_value in self.selected_options:
|
|
78
|
+
self.selected_options.remove(line_value)
|
|
79
|
+
else:
|
|
80
|
+
self.selected_options.append(line_value)
|
|
81
|
+
|
|
82
|
+
if pointed_at:
|
|
83
|
+
tokens.append((T.Pointer, ' \u276f', select_item)) # ' >'
|
|
84
|
+
else:
|
|
85
|
+
tokens.append((T, ' ', select_item))
|
|
86
|
+
# 'o ' - FISHEYE
|
|
87
|
+
if choice[2]: # disabled
|
|
88
|
+
tokens.append((T, '- %s (%s)' % (choice[0], choice[2])))
|
|
89
|
+
else:
|
|
90
|
+
if selected:
|
|
91
|
+
tokens.append((T.Selected, '\u25cf ', select_item))
|
|
92
|
+
else:
|
|
93
|
+
tokens.append((T, '\u25cb ', select_item))
|
|
94
|
+
|
|
95
|
+
if pointed_at:
|
|
96
|
+
tokens.append((Token.SetCursorPosition, ''))
|
|
97
|
+
|
|
98
|
+
tokens.append((T, '%s' % line_name, select_item))
|
|
99
|
+
tokens.append((T, '\n'))
|
|
100
|
+
|
|
101
|
+
# prepare the select choices
|
|
102
|
+
for i, choice in enumerate(self.choices):
|
|
103
|
+
append(i, choice)
|
|
104
|
+
tokens.pop() # Remove last newline.
|
|
105
|
+
return tokens
|
|
106
|
+
|
|
107
|
+
def get_selected_values(self):
|
|
108
|
+
# get values not labels
|
|
109
|
+
return [c[1] for c in self.choices if not isinstance(c, Separator) and
|
|
110
|
+
c[1] in self.selected_options]
|
|
111
|
+
|
|
112
|
+
@property
|
|
113
|
+
def line_count(self):
|
|
114
|
+
return len(self.choices)
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def question(message, **kwargs):
|
|
118
|
+
# TODO add bottom-bar (Move up and down to reveal more choices)
|
|
119
|
+
# TODO extract common parts for list, checkbox, rawlist, expand
|
|
120
|
+
if not 'choices' in kwargs:
|
|
121
|
+
raise PromptParameterException('choices')
|
|
122
|
+
# this does not implement default, use checked...
|
|
123
|
+
if 'default' in kwargs:
|
|
124
|
+
raise ValueError('Checkbox does not implement \'default\' '
|
|
125
|
+
'use \'checked\':True\' in choice!')
|
|
126
|
+
|
|
127
|
+
choices = kwargs.pop('choices', None)
|
|
128
|
+
validator = setup_simple_validator(kwargs)
|
|
129
|
+
|
|
130
|
+
# TODO style defaults on detail level
|
|
131
|
+
style = kwargs.pop('style', default_style)
|
|
132
|
+
|
|
133
|
+
ic = InquirerControl(choices)
|
|
134
|
+
qmark = kwargs.pop('qmark', '?')
|
|
135
|
+
|
|
136
|
+
def get_prompt_tokens(cli):
|
|
137
|
+
tokens = []
|
|
138
|
+
|
|
139
|
+
tokens.append((Token.QuestionMark, qmark))
|
|
140
|
+
tokens.append((Token.Question, ' %s ' % message))
|
|
141
|
+
if ic.answered:
|
|
142
|
+
nbr_selected = len(ic.selected_options)
|
|
143
|
+
if nbr_selected == 0:
|
|
144
|
+
tokens.append((Token.Answer, ' done'))
|
|
145
|
+
elif nbr_selected == 1:
|
|
146
|
+
tokens.append((Token.Answer, ' [%s]' % ic.selected_options[0]))
|
|
147
|
+
else:
|
|
148
|
+
tokens.append((Token.Answer,
|
|
149
|
+
' done (%d selections)' % nbr_selected))
|
|
150
|
+
else:
|
|
151
|
+
tokens.append((Token.Instruction,
|
|
152
|
+
' (<up>, <down> to move, <space> to select, <a> '
|
|
153
|
+
'to toggle, <i> to invert)'))
|
|
154
|
+
return tokens
|
|
155
|
+
|
|
156
|
+
def get_error_tokens(cli):
|
|
157
|
+
return [(Token.Toolbar.Validation, ic.error_message or '')]
|
|
158
|
+
|
|
159
|
+
# assemble layout
|
|
160
|
+
layout = HSplit([
|
|
161
|
+
Window(height=D.exact(1),
|
|
162
|
+
content=TokenListControl(get_prompt_tokens, align_center=False)
|
|
163
|
+
),
|
|
164
|
+
ConditionalContainer(
|
|
165
|
+
Window(
|
|
166
|
+
ic,
|
|
167
|
+
width=D.exact(43),
|
|
168
|
+
height=D(min=3),
|
|
169
|
+
scroll_offsets=ScrollOffsets(top=1, bottom=1)
|
|
170
|
+
),
|
|
171
|
+
filter=~IsDone()
|
|
172
|
+
),
|
|
173
|
+
ConditionalContainer(
|
|
174
|
+
Window(
|
|
175
|
+
TokenListControl(get_error_tokens),
|
|
176
|
+
dont_extend_height=True,
|
|
177
|
+
wrap_lines=True
|
|
178
|
+
),
|
|
179
|
+
filter=~IsDone() & Condition(lambda cli: bool(ic.error_message))
|
|
180
|
+
)
|
|
181
|
+
])
|
|
182
|
+
|
|
183
|
+
# key bindings
|
|
184
|
+
manager = KeyBindingManager.for_prompt()
|
|
185
|
+
|
|
186
|
+
@manager.registry.add_binding(Keys.ControlQ, eager=True)
|
|
187
|
+
@manager.registry.add_binding(Keys.ControlC, eager=True)
|
|
188
|
+
def _(event):
|
|
189
|
+
raise KeyboardInterrupt()
|
|
190
|
+
# event.cli.set_return_value(None)
|
|
191
|
+
|
|
192
|
+
@manager.registry.add_binding(' ', eager=True)
|
|
193
|
+
def toggle(event):
|
|
194
|
+
ic.error_message = None
|
|
195
|
+
pointed_choice = ic.choices[ic.pointer_index][1] # value
|
|
196
|
+
if pointed_choice in ic.selected_options:
|
|
197
|
+
ic.selected_options.remove(pointed_choice)
|
|
198
|
+
else:
|
|
199
|
+
ic.selected_options.append(pointed_choice)
|
|
200
|
+
|
|
201
|
+
@manager.registry.add_binding('i', eager=True)
|
|
202
|
+
def invert(event):
|
|
203
|
+
ic.error_message = None
|
|
204
|
+
inverted_selection = [c[1] for c in ic.choices if
|
|
205
|
+
not isinstance(c, Separator) and
|
|
206
|
+
c[1] not in ic.selected_options and
|
|
207
|
+
not c[2]]
|
|
208
|
+
ic.selected_options = inverted_selection
|
|
209
|
+
|
|
210
|
+
@manager.registry.add_binding('a', eager=True)
|
|
211
|
+
def all(event):
|
|
212
|
+
ic.error_message = None
|
|
213
|
+
all_selected = True # all choices have been selected
|
|
214
|
+
for c in ic.choices:
|
|
215
|
+
if not isinstance(c, Separator) and c[1] not in ic.selected_options and not c[2]:
|
|
216
|
+
# add missing ones
|
|
217
|
+
ic.selected_options.append(c[1])
|
|
218
|
+
all_selected = False
|
|
219
|
+
if all_selected:
|
|
220
|
+
ic.selected_options = []
|
|
221
|
+
|
|
222
|
+
@manager.registry.add_binding(Keys.Down, eager=True)
|
|
223
|
+
def move_cursor_down(event):
|
|
224
|
+
def _next():
|
|
225
|
+
ic.pointer_index = ((ic.pointer_index + 1) % ic.line_count)
|
|
226
|
+
_next()
|
|
227
|
+
while isinstance(ic.choices[ic.pointer_index], Separator) or \
|
|
228
|
+
ic.choices[ic.pointer_index][2]:
|
|
229
|
+
_next()
|
|
230
|
+
|
|
231
|
+
@manager.registry.add_binding(Keys.Up, eager=True)
|
|
232
|
+
def move_cursor_up(event):
|
|
233
|
+
def _prev():
|
|
234
|
+
ic.pointer_index = ((ic.pointer_index - 1) % ic.line_count)
|
|
235
|
+
_prev()
|
|
236
|
+
while isinstance(ic.choices[ic.pointer_index], Separator) or \
|
|
237
|
+
ic.choices[ic.pointer_index][2]:
|
|
238
|
+
_prev()
|
|
239
|
+
|
|
240
|
+
@manager.registry.add_binding(Keys.Enter, eager=True)
|
|
241
|
+
def set_answer(event):
|
|
242
|
+
answer = ic.get_selected_values()
|
|
243
|
+
try:
|
|
244
|
+
validator(answer)
|
|
245
|
+
except ValidationError as e:
|
|
246
|
+
ic.error_message = e.message
|
|
247
|
+
return
|
|
248
|
+
ic.answered = True
|
|
249
|
+
event.cli.set_return_value(answer)
|
|
250
|
+
|
|
251
|
+
return Application(
|
|
252
|
+
layout=layout,
|
|
253
|
+
key_bindings_registry=manager.registry,
|
|
254
|
+
mouse_support=True,
|
|
255
|
+
style=style
|
|
256
|
+
)
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""
|
|
3
|
+
common prompt functionality
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
import inspect
|
|
7
|
+
import sys
|
|
8
|
+
|
|
9
|
+
from prompt_toolkit.validation import Validator, ValidationError
|
|
10
|
+
from prompt_toolkit.styles import style_from_dict
|
|
11
|
+
from prompt_toolkit.token import Token
|
|
12
|
+
from prompt_toolkit.mouse_events import MouseEventTypes
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
PY3 = sys.version_info[0] >= 3
|
|
16
|
+
|
|
17
|
+
if PY3:
|
|
18
|
+
basestring = str
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def if_mousedown(handler):
|
|
22
|
+
def handle_if_mouse_down(cli, mouse_event):
|
|
23
|
+
if mouse_event.event_type == MouseEventTypes.MOUSE_DOWN:
|
|
24
|
+
return handler(cli, mouse_event)
|
|
25
|
+
else:
|
|
26
|
+
return NotImplemented
|
|
27
|
+
|
|
28
|
+
return handle_if_mouse_down
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
# TODO probably better to use base.Condition
|
|
32
|
+
def setup_validator(kwargs):
|
|
33
|
+
# this is an internal helper not meant for public consumption!
|
|
34
|
+
# note this works on a dictionary
|
|
35
|
+
validate_prompt = kwargs.pop('validate', None)
|
|
36
|
+
if validate_prompt:
|
|
37
|
+
if inspect.isclass(validate_prompt) and issubclass(validate_prompt, Validator):
|
|
38
|
+
kwargs['validator'] = validate_prompt()
|
|
39
|
+
elif isinstance(validate_prompt, Validator):
|
|
40
|
+
kwargs['validator'] = validate_prompt
|
|
41
|
+
elif callable(validate_prompt):
|
|
42
|
+
class _InputValidator(Validator):
|
|
43
|
+
def validate(self, document):
|
|
44
|
+
#print('validation!!')
|
|
45
|
+
verdict = validate_prompt(document.text)
|
|
46
|
+
if isinstance(verdict, basestring):
|
|
47
|
+
raise ValidationError(
|
|
48
|
+
message=verdict,
|
|
49
|
+
cursor_position=len(document.text))
|
|
50
|
+
elif not verdict == True:
|
|
51
|
+
raise ValidationError(
|
|
52
|
+
message='invalid input',
|
|
53
|
+
cursor_position=len(document.text))
|
|
54
|
+
kwargs['validator'] = _InputValidator()
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def setup_simple_validator(kwargs):
|
|
58
|
+
# this is an internal helper not meant for public consumption!
|
|
59
|
+
# note this works on a dictionary
|
|
60
|
+
# this validates the answer not a buffer
|
|
61
|
+
validate = kwargs.pop('validate', None)
|
|
62
|
+
# Validator classes validate a buffer, they can't be used here
|
|
63
|
+
if validate is None or inspect.isclass(validate):
|
|
64
|
+
def _always(answer):
|
|
65
|
+
return True
|
|
66
|
+
return _always
|
|
67
|
+
elif not callable(validate):
|
|
68
|
+
raise ValueError('Here a simple validate function is expected, no class')
|
|
69
|
+
|
|
70
|
+
def _validator(answer):
|
|
71
|
+
verdict = validate(answer)
|
|
72
|
+
if isinstance(verdict, basestring):
|
|
73
|
+
raise ValidationError(
|
|
74
|
+
message=verdict
|
|
75
|
+
)
|
|
76
|
+
elif not verdict == True:
|
|
77
|
+
raise ValidationError(
|
|
78
|
+
message='invalid input'
|
|
79
|
+
)
|
|
80
|
+
return _validator
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
# FIXME style defaults on detail level
|
|
84
|
+
default_style = style_from_dict({
|
|
85
|
+
Token.Separator: '#6C6C6C',
|
|
86
|
+
Token.QuestionMark: '#5F819D',
|
|
87
|
+
Token.Selected: '', # default
|
|
88
|
+
Token.Pointer: '#FF9D00 bold', # AWS orange
|
|
89
|
+
Token.Instruction: '', # default
|
|
90
|
+
Token.Answer: '#FF9D00 bold', # AWS orange
|
|
91
|
+
Token.Question: 'bold',
|
|
92
|
+
})
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""
|
|
3
|
+
confirm type question
|
|
4
|
+
"""
|
|
5
|
+
from __future__ import print_function, unicode_literals
|
|
6
|
+
from prompt_toolkit.application import Application
|
|
7
|
+
from prompt_toolkit.key_binding.manager import KeyBindingManager
|
|
8
|
+
from prompt_toolkit.keys import Keys
|
|
9
|
+
from prompt_toolkit.layout.containers import Window, HSplit
|
|
10
|
+
from prompt_toolkit.layout.controls import TokenListControl
|
|
11
|
+
from prompt_toolkit.layout.dimension import LayoutDimension as D
|
|
12
|
+
from prompt_toolkit.token import Token
|
|
13
|
+
from prompt_toolkit.shortcuts import create_prompt_application
|
|
14
|
+
from prompt_toolkit.styles import style_from_dict
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
# custom control based on TokenListControl
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def question(message, **kwargs):
|
|
21
|
+
# TODO need ENTER confirmation
|
|
22
|
+
default = kwargs.pop('default', True)
|
|
23
|
+
|
|
24
|
+
# TODO style defaults on detail level
|
|
25
|
+
style = kwargs.pop('style', style_from_dict({
|
|
26
|
+
Token.QuestionMark: '#5F819D',
|
|
27
|
+
#Token.Selected: '#FF9D00', # AWS orange
|
|
28
|
+
Token.Instruction: '', # default
|
|
29
|
+
Token.Answer: '#FF9D00 bold', # AWS orange
|
|
30
|
+
Token.Question: 'bold',
|
|
31
|
+
}))
|
|
32
|
+
status = {'answer': None}
|
|
33
|
+
|
|
34
|
+
qmark = kwargs.pop('qmark', '?')
|
|
35
|
+
|
|
36
|
+
def get_prompt_tokens(cli):
|
|
37
|
+
tokens = []
|
|
38
|
+
|
|
39
|
+
tokens.append((Token.QuestionMark, qmark))
|
|
40
|
+
tokens.append((Token.Question, ' %s ' % message))
|
|
41
|
+
if isinstance(status['answer'], bool):
|
|
42
|
+
tokens.append((Token.Answer, ' Yes' if status['answer'] else ' No'))
|
|
43
|
+
else:
|
|
44
|
+
if default:
|
|
45
|
+
instruction = ' (Y/n)'
|
|
46
|
+
else:
|
|
47
|
+
instruction = ' (y/N)'
|
|
48
|
+
tokens.append((Token.Instruction, instruction))
|
|
49
|
+
return tokens
|
|
50
|
+
|
|
51
|
+
# key bindings
|
|
52
|
+
manager = KeyBindingManager.for_prompt()
|
|
53
|
+
|
|
54
|
+
@manager.registry.add_binding(Keys.ControlQ, eager=True)
|
|
55
|
+
@manager.registry.add_binding(Keys.ControlC, eager=True)
|
|
56
|
+
def _(event):
|
|
57
|
+
raise KeyboardInterrupt()
|
|
58
|
+
|
|
59
|
+
@manager.registry.add_binding(Keys.Any)
|
|
60
|
+
def ignore_other_keys(event):
|
|
61
|
+
pass
|
|
62
|
+
|
|
63
|
+
@manager.registry.add_binding('n')
|
|
64
|
+
@manager.registry.add_binding('N')
|
|
65
|
+
def key_n(event):
|
|
66
|
+
status['answer'] = False
|
|
67
|
+
event.cli.set_return_value(False)
|
|
68
|
+
|
|
69
|
+
@manager.registry.add_binding('y')
|
|
70
|
+
@manager.registry.add_binding('Y')
|
|
71
|
+
def key_y(event):
|
|
72
|
+
status['answer'] = True
|
|
73
|
+
event.cli.set_return_value(True)
|
|
74
|
+
|
|
75
|
+
@manager.registry.add_binding(Keys.Enter, eager=True)
|
|
76
|
+
def set_answer(event):
|
|
77
|
+
status['answer'] = default
|
|
78
|
+
event.cli.set_return_value(default)
|
|
79
|
+
|
|
80
|
+
return create_prompt_application(
|
|
81
|
+
get_prompt_tokens=get_prompt_tokens,
|
|
82
|
+
key_bindings_registry=manager.registry,
|
|
83
|
+
mouse_support=False,
|
|
84
|
+
style=style,
|
|
85
|
+
erase_when_done=False,
|
|
86
|
+
)
|