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
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""
|
|
3
|
+
`editor` type question
|
|
4
|
+
"""
|
|
5
|
+
from __future__ import print_function, unicode_literals
|
|
6
|
+
import os
|
|
7
|
+
import sys
|
|
8
|
+
from prompt_toolkit.token import Token
|
|
9
|
+
from prompt_toolkit.shortcuts import create_prompt_application
|
|
10
|
+
from prompt_toolkit.layout.lexers import SimpleLexer
|
|
11
|
+
|
|
12
|
+
from .common import default_style, setup_validator
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
# use std prompt-toolkit control
|
|
16
|
+
|
|
17
|
+
WIN = sys.platform.startswith('win')
|
|
18
|
+
|
|
19
|
+
class EditorArgumentsError(Exception):
|
|
20
|
+
pass
|
|
21
|
+
|
|
22
|
+
class Editor(object):
|
|
23
|
+
|
|
24
|
+
def __init__(self, editor=None, env=None, require_save=True, extension='.txt'):
|
|
25
|
+
self.editor = editor
|
|
26
|
+
self.env = env
|
|
27
|
+
self.require_save = require_save
|
|
28
|
+
self.extension = extension
|
|
29
|
+
|
|
30
|
+
def get_editor(self):
|
|
31
|
+
if self.editor is not None and self.editor.lower() != "default":
|
|
32
|
+
return self.editor
|
|
33
|
+
for key in 'VISUAL', 'EDITOR':
|
|
34
|
+
rv = os.environ.get(key)
|
|
35
|
+
if rv:
|
|
36
|
+
return rv
|
|
37
|
+
if WIN:
|
|
38
|
+
return 'notepad'
|
|
39
|
+
for editor in 'vim', 'nano':
|
|
40
|
+
if os.system('which %s >/dev/null 2>&1' % editor) == 0:
|
|
41
|
+
return editor
|
|
42
|
+
return 'vi'
|
|
43
|
+
|
|
44
|
+
def edit_file(self, filename):
|
|
45
|
+
import subprocess
|
|
46
|
+
editor = self.get_editor()
|
|
47
|
+
if self.env:
|
|
48
|
+
environ = os.environ.copy()
|
|
49
|
+
environ.update(self.env)
|
|
50
|
+
else:
|
|
51
|
+
environ = None
|
|
52
|
+
try:
|
|
53
|
+
c = subprocess.Popen('%s "%s"' % (editor, filename),
|
|
54
|
+
env=environ, shell=True)
|
|
55
|
+
exit_code = c.wait()
|
|
56
|
+
if exit_code != 0:
|
|
57
|
+
raise Exception('%s: Editing failed!' % editor)
|
|
58
|
+
except OSError as e:
|
|
59
|
+
raise Exception('%s: Editing failed: %s' % (editor, e))
|
|
60
|
+
|
|
61
|
+
def edit(self, text):
|
|
62
|
+
import tempfile
|
|
63
|
+
|
|
64
|
+
text = text or ''
|
|
65
|
+
if text and not text.endswith('\n'):
|
|
66
|
+
text += '\n'
|
|
67
|
+
|
|
68
|
+
fd, name = tempfile.mkstemp(prefix='editor-', suffix=self.extension)
|
|
69
|
+
try:
|
|
70
|
+
if WIN:
|
|
71
|
+
encoding = 'utf-8-sig'
|
|
72
|
+
text = text.replace('\n', '\r\n')
|
|
73
|
+
else:
|
|
74
|
+
encoding = 'utf-8'
|
|
75
|
+
text = text.encode(encoding)
|
|
76
|
+
|
|
77
|
+
f = os.fdopen(fd, 'wb')
|
|
78
|
+
f.write(text)
|
|
79
|
+
f.close()
|
|
80
|
+
timestamp = os.path.getmtime(name)
|
|
81
|
+
|
|
82
|
+
self.edit_file(name)
|
|
83
|
+
|
|
84
|
+
if self.require_save \
|
|
85
|
+
and os.path.getmtime(name) == timestamp:
|
|
86
|
+
return None
|
|
87
|
+
|
|
88
|
+
f = open(name, 'rb')
|
|
89
|
+
try:
|
|
90
|
+
rv = f.read()
|
|
91
|
+
finally:
|
|
92
|
+
f.close()
|
|
93
|
+
return rv.decode('utf-8-sig').replace('\r\n', '\n')
|
|
94
|
+
finally:
|
|
95
|
+
os.unlink(name)
|
|
96
|
+
|
|
97
|
+
def edit(text=None, editor=None, env=None, require_save=True,
|
|
98
|
+
extension='.txt', filename=None):
|
|
99
|
+
r"""Edits the given text in the defined editor. If an editor is given
|
|
100
|
+
(should be the full path to the executable but the regular operating
|
|
101
|
+
system search path is used for finding the executable) it overrides
|
|
102
|
+
the detected editor. Optionally, some environment variables can be
|
|
103
|
+
used. If the editor is closed without changes, `None` is returned. In
|
|
104
|
+
case a file is edited directly the return value is always `None` and
|
|
105
|
+
`require_save` and `extension` are ignored.
|
|
106
|
+
|
|
107
|
+
If the editor cannot be opened a :exc:`UsageError` is raised.
|
|
108
|
+
|
|
109
|
+
Note for Windows: to simplify cross-platform usage, the newlines are
|
|
110
|
+
automatically converted from POSIX to Windows and vice versa. As such,
|
|
111
|
+
the message here will have ``\n`` as newline markers.
|
|
112
|
+
|
|
113
|
+
:param text: the text to edit.
|
|
114
|
+
:param editor: optionally the editor to use. Defaults to automatic
|
|
115
|
+
detection.
|
|
116
|
+
:param env: environment variables to forward to the editor.
|
|
117
|
+
:param require_save: if this is true, then not saving in the editor
|
|
118
|
+
will make the return value become `None`.
|
|
119
|
+
:param extension: the extension to tell the editor about. This defaults
|
|
120
|
+
to `.txt` but changing this might change syntax
|
|
121
|
+
highlighting.
|
|
122
|
+
:param filename: if provided it will edit this file instead of the
|
|
123
|
+
provided text contents. It will not use a temporary
|
|
124
|
+
file as an indirection in that case.
|
|
125
|
+
"""
|
|
126
|
+
|
|
127
|
+
editor = Editor(editor=editor, env=env, require_save=require_save,
|
|
128
|
+
extension=extension)
|
|
129
|
+
if filename is None:
|
|
130
|
+
return editor.edit(text)
|
|
131
|
+
editor.edit_file(filename)
|
|
132
|
+
|
|
133
|
+
def question(message, **kwargs):
|
|
134
|
+
default = kwargs.pop('default', '')
|
|
135
|
+
eargs = kwargs.pop('eargs', {})
|
|
136
|
+
setup_validator(kwargs)
|
|
137
|
+
|
|
138
|
+
for k, v in eargs.items():
|
|
139
|
+
if v == "" or v == " ":
|
|
140
|
+
raise EditorArgumentsError(
|
|
141
|
+
"Args '{}' value should not be empty".format(k)
|
|
142
|
+
)
|
|
143
|
+
|
|
144
|
+
editor = eargs.get("editor", None)
|
|
145
|
+
ext = eargs.get("ext", ".txt")
|
|
146
|
+
env = eargs.get("env", None)
|
|
147
|
+
text = default
|
|
148
|
+
filename = eargs.get("filename", None)
|
|
149
|
+
multiline = True if not editor else False
|
|
150
|
+
save = eargs.get("save", None)
|
|
151
|
+
|
|
152
|
+
if editor:
|
|
153
|
+
_text = edit(
|
|
154
|
+
editor=editor,
|
|
155
|
+
extension=ext,
|
|
156
|
+
text=text,
|
|
157
|
+
env=env,
|
|
158
|
+
filename=filename,
|
|
159
|
+
require_save=save
|
|
160
|
+
)
|
|
161
|
+
if filename:
|
|
162
|
+
default = filename
|
|
163
|
+
else:
|
|
164
|
+
default = _text
|
|
165
|
+
|
|
166
|
+
# TODO style defaults on detail level
|
|
167
|
+
kwargs['style'] = kwargs.pop('style', default_style)
|
|
168
|
+
qmark = kwargs.pop('qmark', '?')
|
|
169
|
+
|
|
170
|
+
def _get_prompt_tokens(cli):
|
|
171
|
+
return [
|
|
172
|
+
(Token.QuestionMark, qmark),
|
|
173
|
+
(Token.Question, ' %s ' % message)
|
|
174
|
+
]
|
|
175
|
+
|
|
176
|
+
return create_prompt_application(
|
|
177
|
+
get_prompt_tokens=_get_prompt_tokens,
|
|
178
|
+
lexer=SimpleLexer(Token.Answer),
|
|
179
|
+
default=default,
|
|
180
|
+
multiline=multiline,
|
|
181
|
+
**kwargs
|
|
182
|
+
)
|
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""
|
|
3
|
+
`expand` type question
|
|
4
|
+
"""
|
|
5
|
+
from __future__ import print_function, unicode_literals
|
|
6
|
+
|
|
7
|
+
import sys
|
|
8
|
+
|
|
9
|
+
from prompt_toolkit.application import Application
|
|
10
|
+
from prompt_toolkit.key_binding.manager import KeyBindingManager
|
|
11
|
+
from prompt_toolkit.keys import Keys
|
|
12
|
+
from prompt_toolkit.layout.containers import Window
|
|
13
|
+
from prompt_toolkit.filters import IsDone
|
|
14
|
+
from prompt_toolkit.layout.controls import TokenListControl
|
|
15
|
+
from prompt_toolkit.layout.containers import ConditionalContainer, HSplit
|
|
16
|
+
from prompt_toolkit.layout.dimension import LayoutDimension as D
|
|
17
|
+
from prompt_toolkit.token import Token
|
|
18
|
+
|
|
19
|
+
from .. import PromptParameterException
|
|
20
|
+
from ..separator import Separator
|
|
21
|
+
from .common import default_style
|
|
22
|
+
from .common import if_mousedown
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
PY3 = sys.version_info[0] >= 3
|
|
26
|
+
|
|
27
|
+
if PY3:
|
|
28
|
+
basestring = str
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
# custom control based on TokenListControl
|
|
32
|
+
|
|
33
|
+
class InquirerControl(TokenListControl):
|
|
34
|
+
def __init__(self, choices, default=None, **kwargs):
|
|
35
|
+
self.pointer_index = 0
|
|
36
|
+
self.answered = False
|
|
37
|
+
self._init_choices(choices, default)
|
|
38
|
+
self._help_active = False # help is activated via 'h' key
|
|
39
|
+
super(InquirerControl, self).__init__(self._get_choice_tokens,
|
|
40
|
+
**kwargs)
|
|
41
|
+
|
|
42
|
+
def _init_choices(self, choices, default=None):
|
|
43
|
+
# helper to convert from question format to internal format
|
|
44
|
+
|
|
45
|
+
self.choices = [] # list (key, name, value)
|
|
46
|
+
|
|
47
|
+
if not default:
|
|
48
|
+
default = 'h'
|
|
49
|
+
for i, c in enumerate(choices):
|
|
50
|
+
if isinstance(c, Separator):
|
|
51
|
+
self.choices.append(c)
|
|
52
|
+
else:
|
|
53
|
+
if isinstance(c, basestring):
|
|
54
|
+
self.choices.append((key, c, c))
|
|
55
|
+
else:
|
|
56
|
+
key = c.get('key')
|
|
57
|
+
name = c.get('name')
|
|
58
|
+
value = c.get('value', name)
|
|
59
|
+
if default and default == key:
|
|
60
|
+
self.pointer_index = i
|
|
61
|
+
key = key.upper() # default key is in uppercase
|
|
62
|
+
self.choices.append((key, name, value))
|
|
63
|
+
# append the help choice
|
|
64
|
+
key = 'h'
|
|
65
|
+
if not default:
|
|
66
|
+
self.pointer_index = len(self.choices)
|
|
67
|
+
key = key.upper() # default key is in uppercase
|
|
68
|
+
self.choices.append((key, 'Help, list all options', None))
|
|
69
|
+
|
|
70
|
+
@property
|
|
71
|
+
def choice_count(self):
|
|
72
|
+
return len(self.choices)
|
|
73
|
+
|
|
74
|
+
def _get_choice_tokens(self, cli):
|
|
75
|
+
tokens = []
|
|
76
|
+
T = Token
|
|
77
|
+
|
|
78
|
+
def _append(index, line):
|
|
79
|
+
if isinstance(line, Separator):
|
|
80
|
+
tokens.append((T.Separator, ' %s\n' % line))
|
|
81
|
+
else:
|
|
82
|
+
key = line[0]
|
|
83
|
+
line = line[1]
|
|
84
|
+
pointed_at = (index == self.pointer_index)
|
|
85
|
+
|
|
86
|
+
@if_mousedown
|
|
87
|
+
def select_item(cli, mouse_event):
|
|
88
|
+
# bind option with this index to mouse event
|
|
89
|
+
self.pointer_index = index
|
|
90
|
+
|
|
91
|
+
if pointed_at:
|
|
92
|
+
tokens.append((T.Selected, ' %s) %s' % (key, line),
|
|
93
|
+
select_item))
|
|
94
|
+
else:
|
|
95
|
+
tokens.append((T, ' %s) %s' % (key, line),
|
|
96
|
+
select_item))
|
|
97
|
+
tokens.append((T, '\n'))
|
|
98
|
+
|
|
99
|
+
if self._help_active:
|
|
100
|
+
# prepare the select choices
|
|
101
|
+
for i, choice in enumerate(self.choices):
|
|
102
|
+
_append(i, choice)
|
|
103
|
+
tokens.append((T, ' Answer: %s' %
|
|
104
|
+
self.choices[self.pointer_index][0]))
|
|
105
|
+
else:
|
|
106
|
+
tokens.append((T.Pointer, '>> '))
|
|
107
|
+
tokens.append((T, self.choices[self.pointer_index][1]))
|
|
108
|
+
return tokens
|
|
109
|
+
|
|
110
|
+
def get_selected_value(self):
|
|
111
|
+
# get value not label
|
|
112
|
+
return self.choices[self.pointer_index][2]
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def question(message, **kwargs):
|
|
116
|
+
# TODO extract common parts for list, checkbox, rawlist, expand
|
|
117
|
+
# TODO up, down navigation
|
|
118
|
+
if not 'choices' in kwargs:
|
|
119
|
+
raise PromptParameterException('choices')
|
|
120
|
+
|
|
121
|
+
choices = kwargs.pop('choices', None)
|
|
122
|
+
default = kwargs.pop('default', None)
|
|
123
|
+
qmark = kwargs.pop('qmark', '?')
|
|
124
|
+
# TODO style defaults on detail level
|
|
125
|
+
style = kwargs.pop('style', default_style)
|
|
126
|
+
|
|
127
|
+
ic = InquirerControl(choices, default)
|
|
128
|
+
|
|
129
|
+
def get_prompt_tokens(cli):
|
|
130
|
+
tokens = []
|
|
131
|
+
T = Token
|
|
132
|
+
|
|
133
|
+
tokens.append((T.QuestionMark, qmark))
|
|
134
|
+
tokens.append((T.Question, ' %s ' % message))
|
|
135
|
+
if not ic.answered:
|
|
136
|
+
tokens.append((T.Instruction, ' (%s)' % ''.join(
|
|
137
|
+
[k[0] for k in ic.choices if not isinstance(k, Separator)])))
|
|
138
|
+
else:
|
|
139
|
+
tokens.append((T.Answer, ' %s' % ic.get_selected_value()))
|
|
140
|
+
return tokens
|
|
141
|
+
|
|
142
|
+
#@Condition
|
|
143
|
+
#def is_help_active(cli):
|
|
144
|
+
# return ic._help_active
|
|
145
|
+
|
|
146
|
+
# assemble layout
|
|
147
|
+
layout = HSplit([
|
|
148
|
+
Window(height=D.exact(1),
|
|
149
|
+
content=TokenListControl(get_prompt_tokens)
|
|
150
|
+
),
|
|
151
|
+
ConditionalContainer(
|
|
152
|
+
Window(ic),
|
|
153
|
+
#filter=is_help_active & ~IsDone() # ~ bitwise inverse
|
|
154
|
+
filter=~IsDone() # ~ bitwise inverse
|
|
155
|
+
)
|
|
156
|
+
])
|
|
157
|
+
|
|
158
|
+
# key bindings
|
|
159
|
+
manager = KeyBindingManager.for_prompt()
|
|
160
|
+
|
|
161
|
+
@manager.registry.add_binding(Keys.ControlQ, eager=True)
|
|
162
|
+
@manager.registry.add_binding(Keys.ControlC, eager=True)
|
|
163
|
+
def _(event):
|
|
164
|
+
raise KeyboardInterrupt()
|
|
165
|
+
|
|
166
|
+
# add key bindings for choices
|
|
167
|
+
for i, c in enumerate(ic.choices):
|
|
168
|
+
if not isinstance(c, Separator):
|
|
169
|
+
def _reg_binding(i, keys):
|
|
170
|
+
# trick out late evaluation with a "function factory":
|
|
171
|
+
# http://stackoverflow.com/questions/3431676/creating-functions-in-a-loop
|
|
172
|
+
@manager.registry.add_binding(keys, eager=True)
|
|
173
|
+
def select_choice(event):
|
|
174
|
+
ic.pointer_index = i
|
|
175
|
+
if c[0] not in ['h', 'H']:
|
|
176
|
+
_reg_binding(i, c[0])
|
|
177
|
+
if c[0].isupper():
|
|
178
|
+
_reg_binding(i, c[0].lower())
|
|
179
|
+
|
|
180
|
+
@manager.registry.add_binding('H', eager=True)
|
|
181
|
+
@manager.registry.add_binding('h', eager=True)
|
|
182
|
+
def help_choice(event):
|
|
183
|
+
ic._help_active = True
|
|
184
|
+
|
|
185
|
+
@manager.registry.add_binding(Keys.Enter, eager=True)
|
|
186
|
+
def set_answer(event):
|
|
187
|
+
ic.answered = True
|
|
188
|
+
event.cli.set_return_value(ic.get_selected_value())
|
|
189
|
+
|
|
190
|
+
return Application(
|
|
191
|
+
layout=layout,
|
|
192
|
+
key_bindings_registry=manager.registry,
|
|
193
|
+
mouse_support=True,
|
|
194
|
+
style=style
|
|
195
|
+
)
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""
|
|
3
|
+
`input` type question
|
|
4
|
+
"""
|
|
5
|
+
from __future__ import print_function, unicode_literals
|
|
6
|
+
import inspect
|
|
7
|
+
import sys
|
|
8
|
+
from prompt_toolkit.token import Token
|
|
9
|
+
from prompt_toolkit.shortcuts import create_prompt_application
|
|
10
|
+
from prompt_toolkit.validation import Validator, ValidationError
|
|
11
|
+
from prompt_toolkit.layout.lexers import SimpleLexer
|
|
12
|
+
|
|
13
|
+
from .common import default_style
|
|
14
|
+
|
|
15
|
+
PY3 = sys.version_info[0] >= 3
|
|
16
|
+
|
|
17
|
+
if PY3:
|
|
18
|
+
basestring = str
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
# use std prompt-toolkit control
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def question(message, **kwargs):
|
|
25
|
+
default = kwargs.pop('default', '')
|
|
26
|
+
if default is None:
|
|
27
|
+
default = ''
|
|
28
|
+
elif not isinstance(default, basestring):
|
|
29
|
+
default = str(default)
|
|
30
|
+
validate_prompt = kwargs.pop('validate', None)
|
|
31
|
+
if validate_prompt:
|
|
32
|
+
if inspect.isclass(validate_prompt) and issubclass(validate_prompt, Validator):
|
|
33
|
+
kwargs['validator'] = validate_prompt()
|
|
34
|
+
elif callable(validate_prompt):
|
|
35
|
+
class _InputValidator(Validator):
|
|
36
|
+
def validate(self, document):
|
|
37
|
+
verdict = validate_prompt(document.text)
|
|
38
|
+
if not verdict == True:
|
|
39
|
+
if verdict == False:
|
|
40
|
+
verdict = 'invalid input'
|
|
41
|
+
raise ValidationError(
|
|
42
|
+
message=verdict,
|
|
43
|
+
cursor_position=len(document.text))
|
|
44
|
+
kwargs['validator'] = _InputValidator()
|
|
45
|
+
|
|
46
|
+
# TODO style defaults on detail level
|
|
47
|
+
kwargs['style'] = kwargs.pop('style', default_style)
|
|
48
|
+
qmark = kwargs.pop('qmark', '?')
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _get_prompt_tokens(cli):
|
|
52
|
+
return [
|
|
53
|
+
(Token.QuestionMark, qmark),
|
|
54
|
+
(Token.Question, ' %s ' % message)
|
|
55
|
+
]
|
|
56
|
+
|
|
57
|
+
return create_prompt_application(
|
|
58
|
+
get_prompt_tokens=_get_prompt_tokens,
|
|
59
|
+
lexer=SimpleLexer(Token.Answer),
|
|
60
|
+
default=default,
|
|
61
|
+
**kwargs
|
|
62
|
+
)
|
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""
|
|
3
|
+
`list` type question
|
|
4
|
+
"""
|
|
5
|
+
from __future__ import print_function
|
|
6
|
+
from __future__ import unicode_literals
|
|
7
|
+
|
|
8
|
+
from prompt_toolkit.application import Application
|
|
9
|
+
from prompt_toolkit.key_binding.manager import KeyBindingManager
|
|
10
|
+
from prompt_toolkit.keys import Keys
|
|
11
|
+
from prompt_toolkit.layout.containers import Window
|
|
12
|
+
from prompt_toolkit.filters import IsDone
|
|
13
|
+
from prompt_toolkit.layout.controls import TokenListControl
|
|
14
|
+
from prompt_toolkit.layout.containers import ConditionalContainer, \
|
|
15
|
+
ScrollOffsets, HSplit
|
|
16
|
+
from prompt_toolkit.layout.dimension import LayoutDimension as D
|
|
17
|
+
from prompt_toolkit.token import Token
|
|
18
|
+
|
|
19
|
+
from .. import PromptParameterException
|
|
20
|
+
from ..separator import Separator
|
|
21
|
+
from .common import if_mousedown, default_style
|
|
22
|
+
|
|
23
|
+
# custom control based on TokenListControl
|
|
24
|
+
# docu here:
|
|
25
|
+
# https://github.com/jonathanslenders/python-prompt-toolkit/issues/281
|
|
26
|
+
# https://github.com/jonathanslenders/python-prompt-toolkit/blob/master/examples/full-screen-layout.py
|
|
27
|
+
# https://github.com/jonathanslenders/python-prompt-toolkit/blob/master/docs/pages/full_screen_apps.rst
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class InquirerControl(TokenListControl):
|
|
31
|
+
def __init__(self, choices, default=None, **kwargs):
|
|
32
|
+
self.selected_option_index = 0
|
|
33
|
+
self.answered = False
|
|
34
|
+
self.choices = choices
|
|
35
|
+
self._init_choices(choices, default)
|
|
36
|
+
super(InquirerControl, self).__init__(self._get_choice_tokens,
|
|
37
|
+
**kwargs)
|
|
38
|
+
|
|
39
|
+
def _init_choices(self, choices, default=None):
|
|
40
|
+
# helper to convert from question format to internal format
|
|
41
|
+
self.choices = [] # list (name, value, disabled)
|
|
42
|
+
searching_first_choice = True
|
|
43
|
+
for i, c in enumerate(choices):
|
|
44
|
+
if isinstance(c, Separator):
|
|
45
|
+
self.choices.append((c, None, None))
|
|
46
|
+
else:
|
|
47
|
+
if not hasattr(c, 'get'): # not a dict
|
|
48
|
+
self.choices.append((c, c, None))
|
|
49
|
+
else:
|
|
50
|
+
name = c.get('name')
|
|
51
|
+
value = c.get('value', name)
|
|
52
|
+
disabled = c.get('disabled', None)
|
|
53
|
+
self.choices.append((name, value, disabled))
|
|
54
|
+
if searching_first_choice and not self.choices[i][2]:
|
|
55
|
+
self.selected_option_index = i # found the first choice
|
|
56
|
+
searching_first_choice = False
|
|
57
|
+
if default is not None:
|
|
58
|
+
self._select_default(default)
|
|
59
|
+
|
|
60
|
+
def _select_default(self, default):
|
|
61
|
+
# the default is the value, the name or the index of a choice
|
|
62
|
+
selectable = [i for i, c in enumerate(self.choices)
|
|
63
|
+
if not isinstance(c[0], Separator) and not c[2]]
|
|
64
|
+
matches = [i for i in selectable if self.choices[i][1] == default]
|
|
65
|
+
matches += [i for i in selectable if self.choices[i][0] == default]
|
|
66
|
+
if isinstance(default, int) and not isinstance(default, bool):
|
|
67
|
+
matches += [i for i in selectable if i == default]
|
|
68
|
+
if matches:
|
|
69
|
+
self.selected_option_index = matches[0]
|
|
70
|
+
|
|
71
|
+
@property
|
|
72
|
+
def choice_count(self):
|
|
73
|
+
return len(self.choices)
|
|
74
|
+
|
|
75
|
+
def _get_choice_tokens(self, cli):
|
|
76
|
+
tokens = []
|
|
77
|
+
T = Token
|
|
78
|
+
|
|
79
|
+
def append(index, choice):
|
|
80
|
+
selected = (index == self.selected_option_index)
|
|
81
|
+
|
|
82
|
+
@if_mousedown
|
|
83
|
+
def select_item(cli, mouse_event):
|
|
84
|
+
# bind option with this index to mouse event
|
|
85
|
+
self.selected_option_index = index
|
|
86
|
+
self.answered = True
|
|
87
|
+
cli.set_return_value(self.get_selection()[1])
|
|
88
|
+
|
|
89
|
+
tokens.append((T.Pointer if selected else T, ' \u276f ' if selected
|
|
90
|
+
else ' '))
|
|
91
|
+
if selected:
|
|
92
|
+
tokens.append((Token.SetCursorPosition, ''))
|
|
93
|
+
if isinstance(choice[0], Separator):
|
|
94
|
+
tokens.append((T, str(choice[0])))
|
|
95
|
+
elif choice[2]: # disabled
|
|
96
|
+
tokens.append((T.Selected if selected else T,
|
|
97
|
+
'- %s (%s)' % (choice[0], choice[2])))
|
|
98
|
+
else:
|
|
99
|
+
try:
|
|
100
|
+
tokens.append((T.Selected if selected else T, str(choice[0]),
|
|
101
|
+
select_item))
|
|
102
|
+
except:
|
|
103
|
+
tokens.append((T.Selected if selected else T, choice[0],
|
|
104
|
+
select_item))
|
|
105
|
+
tokens.append((T, '\n'))
|
|
106
|
+
|
|
107
|
+
# prepare the select choices
|
|
108
|
+
for i, choice in enumerate(self.choices):
|
|
109
|
+
append(i, choice)
|
|
110
|
+
tokens.pop() # Remove last newline.
|
|
111
|
+
return tokens
|
|
112
|
+
|
|
113
|
+
def get_selection(self):
|
|
114
|
+
return self.choices[self.selected_option_index]
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def question(message, **kwargs):
|
|
118
|
+
# TODO disabled, dict choices
|
|
119
|
+
if not 'choices' in kwargs:
|
|
120
|
+
raise PromptParameterException('choices')
|
|
121
|
+
|
|
122
|
+
choices = kwargs.pop('choices', None)
|
|
123
|
+
default = kwargs.pop('default', None)
|
|
124
|
+
qmark = kwargs.pop('qmark', '?')
|
|
125
|
+
# TODO style defaults on detail level
|
|
126
|
+
style = kwargs.pop('style', default_style)
|
|
127
|
+
|
|
128
|
+
ic = InquirerControl(choices, default)
|
|
129
|
+
|
|
130
|
+
def get_prompt_tokens(cli):
|
|
131
|
+
tokens = []
|
|
132
|
+
|
|
133
|
+
tokens.append((Token.QuestionMark, qmark))
|
|
134
|
+
tokens.append((Token.Question, ' %s ' % message))
|
|
135
|
+
if ic.answered:
|
|
136
|
+
tokens.append((Token.Answer, ' %s' % ic.get_selection()[0]))
|
|
137
|
+
else:
|
|
138
|
+
tokens.append((Token.Instruction, ' (Use arrow keys)'))
|
|
139
|
+
return tokens
|
|
140
|
+
|
|
141
|
+
# assemble layout
|
|
142
|
+
layout = HSplit([
|
|
143
|
+
Window(height=D.exact(1),
|
|
144
|
+
content=TokenListControl(get_prompt_tokens)
|
|
145
|
+
),
|
|
146
|
+
ConditionalContainer(
|
|
147
|
+
Window(ic),
|
|
148
|
+
filter=~IsDone()
|
|
149
|
+
)
|
|
150
|
+
])
|
|
151
|
+
|
|
152
|
+
# key bindings
|
|
153
|
+
manager = KeyBindingManager.for_prompt()
|
|
154
|
+
|
|
155
|
+
@manager.registry.add_binding(Keys.ControlQ, eager=True)
|
|
156
|
+
@manager.registry.add_binding(Keys.ControlC, eager=True)
|
|
157
|
+
def _(event):
|
|
158
|
+
raise KeyboardInterrupt()
|
|
159
|
+
# event.cli.set_return_value(None)
|
|
160
|
+
|
|
161
|
+
@manager.registry.add_binding(Keys.Down, eager=True)
|
|
162
|
+
def move_cursor_down(event):
|
|
163
|
+
def _next():
|
|
164
|
+
ic.selected_option_index = (
|
|
165
|
+
(ic.selected_option_index + 1) % ic.choice_count)
|
|
166
|
+
_next()
|
|
167
|
+
while isinstance(ic.choices[ic.selected_option_index][0], Separator) or\
|
|
168
|
+
ic.choices[ic.selected_option_index][2]:
|
|
169
|
+
_next()
|
|
170
|
+
|
|
171
|
+
@manager.registry.add_binding(Keys.Up, eager=True)
|
|
172
|
+
def move_cursor_up(event):
|
|
173
|
+
def _prev():
|
|
174
|
+
ic.selected_option_index = (
|
|
175
|
+
(ic.selected_option_index - 1) % ic.choice_count)
|
|
176
|
+
_prev()
|
|
177
|
+
while isinstance(ic.choices[ic.selected_option_index][0], Separator) or \
|
|
178
|
+
ic.choices[ic.selected_option_index][2]:
|
|
179
|
+
_prev()
|
|
180
|
+
|
|
181
|
+
@manager.registry.add_binding(Keys.Enter, eager=True)
|
|
182
|
+
def set_answer(event):
|
|
183
|
+
ic.answered = True
|
|
184
|
+
event.cli.set_return_value(ic.get_selection()[1])
|
|
185
|
+
|
|
186
|
+
return Application(
|
|
187
|
+
layout=layout,
|
|
188
|
+
key_bindings_registry=manager.registry,
|
|
189
|
+
mouse_support=True,
|
|
190
|
+
style=style
|
|
191
|
+
)
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""
|
|
3
|
+
`password` type question
|
|
4
|
+
"""
|
|
5
|
+
from __future__ import print_function, unicode_literals
|
|
6
|
+
|
|
7
|
+
from . import input
|
|
8
|
+
|
|
9
|
+
# use std prompt-toolkit control
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def question(message, **kwargs):
|
|
13
|
+
kwargs['is_password'] = True
|
|
14
|
+
return input.question(message, **kwargs)
|