PyInquirer 1.0.3__tar.gz → 1.0.4__tar.gz

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.
Files changed (62) hide show
  1. pyinquirer-1.0.4/MANIFEST.in +1 -0
  2. pyinquirer-1.0.4/PKG-INFO +403 -0
  3. {PyInquirer-1.0.3 → pyinquirer-1.0.4}/PyInquirer/__init__.py +1 -1
  4. {PyInquirer-1.0.3 → pyinquirer-1.0.4}/PyInquirer/prompt.py +10 -2
  5. {PyInquirer-1.0.3 → pyinquirer-1.0.4}/PyInquirer/prompts/checkbox.py +29 -6
  6. {PyInquirer-1.0.3 → pyinquirer-1.0.4}/PyInquirer/prompts/common.py +8 -8
  7. {PyInquirer-1.0.3 → pyinquirer-1.0.4}/PyInquirer/prompts/confirm.py +4 -0
  8. {PyInquirer-1.0.3 → pyinquirer-1.0.4}/PyInquirer/prompts/editor.py +2 -17
  9. {PyInquirer-1.0.3 → pyinquirer-1.0.4}/PyInquirer/prompts/input.py +11 -0
  10. {PyInquirer-1.0.3 → pyinquirer-1.0.4}/PyInquirer/prompts/list.py +24 -17
  11. {PyInquirer-1.0.3 → pyinquirer-1.0.4}/PyInquirer/prompts/rawlist.py +23 -6
  12. {PyInquirer-1.0.3 → pyinquirer-1.0.4}/PyInquirer/utils.py +1 -2
  13. pyinquirer-1.0.4/PyInquirer.egg-info/PKG-INFO +403 -0
  14. {PyInquirer-1.0.3 → pyinquirer-1.0.4}/PyInquirer.egg-info/SOURCES.txt +17 -1
  15. pyinquirer-1.0.4/PyInquirer.egg-info/dependency_links.txt +1 -0
  16. pyinquirer-1.0.4/PyInquirer.egg-info/requires.txt +2 -0
  17. {PyInquirer-1.0.3 → pyinquirer-1.0.4}/README.rst +62 -70
  18. {PyInquirer-1.0.3 → pyinquirer-1.0.4}/examples/confirm.py +1 -1
  19. {PyInquirer-1.0.3 → pyinquirer-1.0.4}/examples/input.py +2 -2
  20. {PyInquirer-1.0.3 → pyinquirer-1.0.4}/examples/pizza.py +2 -2
  21. pyinquirer-1.0.4/requirements.txt +3 -0
  22. pyinquirer-1.0.4/setup.cfg +7 -0
  23. {PyInquirer-1.0.3 → pyinquirer-1.0.4}/setup.py +5 -7
  24. pyinquirer-1.0.4/tests/test_example_checkbox.py +42 -0
  25. pyinquirer-1.0.4/tests/test_example_expand.py +52 -0
  26. pyinquirer-1.0.4/tests/test_example_hierachical.py +59 -0
  27. pyinquirer-1.0.4/tests/test_example_input.py +32 -0
  28. pyinquirer-1.0.4/tests/test_example_list.py +43 -0
  29. pyinquirer-1.0.4/tests/test_example_password.py +21 -0
  30. pyinquirer-1.0.4/tests/test_example_pizza.py +61 -0
  31. pyinquirer-1.0.4/tests/test_example_rawlist.py +43 -0
  32. pyinquirer-1.0.4/tests/test_example_when.py +71 -0
  33. pyinquirer-1.0.4/tests/test_helpers.py +58 -0
  34. pyinquirer-1.0.4/tests/test_prompt.py +174 -0
  35. pyinquirer-1.0.4/tests/test_prompts_checkbox.py +0 -0
  36. pyinquirer-1.0.4/tests/test_prompts_common.py +0 -0
  37. pyinquirer-1.0.4/tests/test_prompts_input.py +1 -0
  38. pyinquirer-1.0.4/tests/test_prompts_list.py +66 -0
  39. pyinquirer-1.0.4/tests/test_utils.py +1 -0
  40. PyInquirer-1.0.3/MANIFEST.in +0 -1
  41. PyInquirer-1.0.3/PKG-INFO +0 -396
  42. PyInquirer-1.0.3/PyInquirer.egg-info/PKG-INFO +0 -396
  43. PyInquirer-1.0.3/PyInquirer.egg-info/dependency_links.txt +0 -5
  44. PyInquirer-1.0.3/PyInquirer.egg-info/requires.txt +0 -3
  45. PyInquirer-1.0.3/requirements.txt +0 -4
  46. PyInquirer-1.0.3/setup.cfg +0 -7
  47. {PyInquirer-1.0.3 → pyinquirer-1.0.4}/LICENSE +0 -0
  48. {PyInquirer-1.0.3 → pyinquirer-1.0.4}/PyInquirer/color_print.py +0 -0
  49. {PyInquirer-1.0.3 → pyinquirer-1.0.4}/PyInquirer/prompts/__init__.py +0 -0
  50. {PyInquirer-1.0.3 → pyinquirer-1.0.4}/PyInquirer/prompts/expand.py +0 -0
  51. {PyInquirer-1.0.3 → pyinquirer-1.0.4}/PyInquirer/prompts/password.py +0 -0
  52. {PyInquirer-1.0.3 → pyinquirer-1.0.4}/PyInquirer/separator.py +0 -0
  53. {PyInquirer-1.0.3 → pyinquirer-1.0.4}/PyInquirer.egg-info/top_level.txt +0 -0
  54. {PyInquirer-1.0.3 → pyinquirer-1.0.4}/examples/__init__.py +0 -0
  55. {PyInquirer-1.0.3 → pyinquirer-1.0.4}/examples/checkbox.py +0 -0
  56. {PyInquirer-1.0.3 → pyinquirer-1.0.4}/examples/editor.py +0 -0
  57. {PyInquirer-1.0.3 → pyinquirer-1.0.4}/examples/expand.py +0 -0
  58. {PyInquirer-1.0.3 → pyinquirer-1.0.4}/examples/hierarchical.py +0 -0
  59. {PyInquirer-1.0.3 → pyinquirer-1.0.4}/examples/list.py +0 -0
  60. {PyInquirer-1.0.3 → pyinquirer-1.0.4}/examples/password.py +0 -0
  61. {PyInquirer-1.0.3 → pyinquirer-1.0.4}/examples/rawlist.py +0 -0
  62. {PyInquirer-1.0.3 → pyinquirer-1.0.4}/examples/when.py +0 -0
@@ -0,0 +1 @@
1
+ include LICENSE README.rst requirements.txt
@@ -0,0 +1,403 @@
1
+ Metadata-Version: 2.4
2
+ Name: PyInquirer
3
+ Version: 1.0.4
4
+ Summary: A Python module for collection of common interactive command line user interfaces, based on Inquirer.js
5
+ Home-page: https://github.com/CITGuru/PyInquirer/
6
+ Download-URL: https://github.com/CITGuru/PyInquirer/archive/1.0.4.tar.gz
7
+ Author: Oyetoke Toby
8
+ Author-email: oyetoketoby80@gmail.com
9
+ License: MIT
10
+ Keywords: click,prompt-toolkit,cli,command-line,commandline,command-line-interface,python-inquiry,inquirer
11
+ Classifier: Development Status :: 1 - Planning
12
+ Classifier: Natural Language :: English
13
+ Classifier: Programming Language :: Python :: 2.7
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Environment :: Console
16
+ Classifier: Intended Audience :: Developers
17
+ Classifier: License :: OSI Approved :: MIT License
18
+ Classifier: Operating System :: OS Independent
19
+ Classifier: Topic :: Software Development :: User Interfaces
20
+ Classifier: Topic :: Software Development :: Libraries :: Application Frameworks
21
+ Description-Content-Type: text/x-rst
22
+ License-File: LICENSE
23
+ Requires-Dist: prompt_toolkit<2.0,>=1.0.18
24
+ Requires-Dist: Pygments>=2.2.0
25
+ Dynamic: author
26
+ Dynamic: author-email
27
+ Dynamic: classifier
28
+ Dynamic: description
29
+ Dynamic: description-content-type
30
+ Dynamic: download-url
31
+ Dynamic: home-page
32
+ Dynamic: keywords
33
+ Dynamic: license
34
+ Dynamic: license-file
35
+ Dynamic: requires-dist
36
+ Dynamic: summary
37
+
38
+ PyInquirer
39
+ ==========
40
+
41
+ PyInquirer is a collection of common interactive command line prompts for
42
+ Python, based on `Inquirer.js <https://github.com/SBoudrias/Inquirer.js>`__:
43
+ lists, checkboxes, confirmations, text and password input, and more.
44
+
45
+ Table of Contents
46
+ -----------------
47
+
48
+ 1. `Documentation <#documentation>`__
49
+
50
+ 1. `Installation <#installation>`__
51
+ 2. `Examples <#examples>`__
52
+ 3. `Quickstart <#quickstart>`__
53
+ 4. `Question Types <#types>`__
54
+ 5. `Question Properties <#properties>`__
55
+ 6. `Prompt Options <#prompt-options>`__
56
+ 7. `User Interfaces and Styles <#styles>`__
57
+
58
+ 2. `Windows Platform <#windows>`__
59
+ 3. `Support <#support>`__
60
+ 4. `Contribution <#contribution>`__
61
+ 5. `License <#license>`__
62
+
63
+ Goal and Philosophy
64
+ -------------------
65
+
66
+ **PyInquirer** strives to be an easily embeddable and beautiful
67
+ command line interface for `Python <https://python.org/>`__.
68
+ **PyInquirer** wants to make it easy for existing Inquirer.js users
69
+ to write immersive command line applications in Python. We are convinced
70
+ that its feature-set is the most complete for building immersive CLI
71
+ applications. We also hope that **PyInquirer** proves itself useful
72
+ to Python users.
73
+
74
+ **PyInquirer** should ease the process of
75
+
76
+ - providing *error feedback*
77
+ - *asking questions*
78
+ - *parsing* input
79
+ - *validating* answers
80
+ - managing *hierarchical prompts*
81
+
82
+ **Note:** **PyInquirer** provides the user interface and the inquiry
83
+ session flow.
84
+
85
+ Documentation
86
+ -------------
87
+
88
+ Installation
89
+ ~~~~~~~~~~~~
90
+
91
+ Like most Python packages PyInquirer is available on `PyPI <https://pypi.org/project/PyInquirer/>`__.
92
+ Simply use pip to install the PyInquirer package
93
+
94
+ .. code:: shell
95
+
96
+ pip install PyInquirer
97
+
98
+ PyInquirer 1.0.x requires prompt\_toolkit 1.0.18, which is installed automatically.
99
+
100
+ Quickstart
101
+ ~~~~~~~~~~
102
+
103
+ Like Inquirer.js, using inquirer is structured into two simple steps:
104
+
105
+ - you define a **list of questions** and hand them to **prompt**
106
+ - prompt returns a **dictionary of answers**
107
+
108
+ .. code:: python
109
+
110
+ from __future__ import print_function, unicode_literals
111
+ from PyInquirer import prompt, print_json
112
+
113
+ questions = [
114
+ {
115
+ 'type': 'input',
116
+ 'name': 'first_name',
117
+ 'message': 'What\'s your first name',
118
+ }
119
+ ]
120
+
121
+ answers = prompt(questions)
122
+ print_json(answers) # use the answers as input for your app
123
+
124
+ A good starting point from here is probably the examples section.
125
+
126
+ Examples
127
+ ~~~~~~~~
128
+
129
+ Most of the examples intend to demonstrate a single question type or
130
+ feature:
131
+
132
+ - `editor.py <./examples/editor.py>`_
133
+ - `expand.py <./examples/expand.py>`_
134
+ - `list.py <./examples/list.py>`_
135
+ - `password.py <./examples/password.py>`_
136
+ - `when.py <./examples/when.py>`_
137
+ - `checkbox.py <./examples/checkbox.py>`_
138
+ - `confirm.py <./examples/confirm.py>`_
139
+ - `hierarchical.py <./examples/hierarchical.py>`_
140
+ - `pizza.py <./examples/pizza.py>`_ - demonstrate using different question types
141
+ - `editor.py <./examples/editor.py>`_
142
+ - `input.py <./examples/input.py>`_
143
+ - `rawlist.py <./examples/rawlist.py>`_
144
+
145
+ If you want to launch examples with the code from repository instead of
146
+ installing a package you need to execute ``pip install -e .`` within project
147
+ directory.
148
+
149
+ Question Types
150
+ ~~~~~~~~~~~~~~
151
+
152
+ ``questions`` is a list of questions. Each question has a type.
153
+
154
+ List - ``{type: 'list'}``
155
+ ^^^^^^^^^^^^^^^^^^^^^^^^^
156
+
157
+ Take ``type``, ``name``, ``message``, ``choices``\ [, ``default``,
158
+ ``filter``] properties. (Note that default must be the ``value``,
159
+ ``name`` or ``index`` of a choice)
160
+
161
+ --------------
162
+
163
+ Raw List - ``{type: 'rawlist'}``
164
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
165
+
166
+ Take ``type``, ``name``, ``message``, ``choices``\ [, ``default``,
167
+ ``filter``] properties. (Note that default must be the ``value`` or
168
+ ``index`` of a choice)
169
+
170
+ .. figure:: https://raw.githubusercontent.com/citguru/PyInquirer/master/docs/images/raw-list.png
171
+ :alt: Raw list prompt
172
+
173
+ Raw list prompt
174
+
175
+ --------------
176
+
177
+ Expand - ``{type: 'expand'}``
178
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
179
+
180
+ Take ``type``, ``name``, ``message``, ``choices``\ [, ``default``]
181
+ properties. (Note that default must be the ``key`` of a choice. If
182
+ ``default`` is not provided, the first choice is selected)
183
+
184
+ Note that the ``choices`` object will take an extra parameter called
185
+ ``key`` for the ``expand`` prompt. This parameter must be a single
186
+ (lowercased) character. The ``h`` option is added by the prompt and
187
+ shouldn't be defined by the user.
188
+
189
+ See ``examples/expand.py`` for a running example.
190
+
191
+ |Expand prompt closed| |Expand prompt expanded|
192
+
193
+ --------------
194
+
195
+ Checkbox - ``{type: 'checkbox'}``
196
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
197
+
198
+ Take ``type``, ``name``, ``message``, ``choices``\ [, ``filter``,
199
+ ``validate``] properties.
200
+
201
+ Choices marked as ``{checked: true}`` will be checked by default.
202
+
203
+ Choices whose property ``disabled`` is truthy will be unselectable. If
204
+ ``disabled`` is a string, then the string will be outputted next to the
205
+ disabled choice.
206
+
207
+ .. figure:: https://raw.githubusercontent.com/citguru/PyInquirer/master/docs/images/checkbox-prompt.png
208
+ :alt: Checkbox prompt
209
+
210
+ Checkbox prompt
211
+
212
+ --------------
213
+
214
+ Confirm - ``{type: 'confirm'}``
215
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
216
+
217
+ Take ``type``, ``name``, ``message``\ [, ``default``] properties.
218
+ ``default`` is expected to be a boolean if used.
219
+
220
+ .. figure:: https://raw.githubusercontent.com/citguru/PyInquirer/master/docs/images/confirm-prompt.png
221
+ :alt: Confirm prompt
222
+
223
+ Confirm prompt
224
+
225
+ --------------
226
+
227
+ Input - ``{type: 'input'}``
228
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^
229
+
230
+ Take ``type``, ``name``, ``message``\ [, ``default``, ``filter``,
231
+ ``validate``] properties.
232
+
233
+ .. figure:: https://raw.githubusercontent.com/citguru/PyInquirer/master/docs/images/input-prompt.png
234
+ :alt: Input prompt
235
+
236
+ Input prompt
237
+
238
+ --------------
239
+
240
+ Password - ``{type: 'password'}``
241
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
242
+
243
+ Take ``type``, ``name``, ``message``\ [, ``default``, ``filter``,
244
+ ``validate``] properties.
245
+
246
+ .. figure:: https://raw.githubusercontent.com/citguru/PyInquirer/master/docs/images/password-prompt.png
247
+ :alt: Password prompt
248
+
249
+ Password prompt
250
+
251
+ --------------
252
+
253
+ Editor - ``{type: 'editor'}``
254
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
255
+
256
+ Take ``type``, ``name``, ``message``\ [, ``default``, ``filter``,
257
+ ``validate``, ``eargs``] properties
258
+
259
+ **Editor Arguments -** ``eargs``
260
+
261
+ Opens an empty or edits the default text in the defined editor. If an editor is given
262
+ (should be the full path to the executable but the regular operating
263
+ system search path is used for finding the executable) it overrides
264
+ the detected editor. Optionally, some environment variables can be
265
+ used. If the editor is closed without changes, ``None`` is returned. In
266
+ case a file is edited directly the return value is always ``None`` and
267
+ ``save`` and ``ext`` are ignored.
268
+
269
+ Takes:
270
+
271
+ - editor: accepts ``default`` to get the default platform editor. But
272
+ you can also provide the path to an editor e.g ``vi``.
273
+ - ext: the extension to tell the editor about. This defaults to `.txt`
274
+ but changing this might change syntax highlighting e.g ".py"
275
+ - save: accepts ``True`` or ``False`` to determine to save a file.
276
+ - filename: accepts the path of a file you'd like to edit.
277
+ - env: accepts any given environment variables to pass to the editor
278
+
279
+ Launches an instance of the users preferred editor on a temporary file.
280
+ Once the user exits their editor, the contents of the temporary file are
281
+ read in as the result. The editor to use is determined by reading the
282
+ ``VISUAL`` or ``EDITOR`` environment variables. If neither of those
283
+ are present, notepad (on Windows) or vim (Linux or Mac) is used.
284
+
285
+ Question Properties
286
+ ~~~~~~~~~~~~~~~~~~~
287
+
288
+ A question is a dictionary containing question related values:
289
+
290
+ - ``type``: (String) Type of the prompt. Possible values:
291
+ input, confirm, list, rawlist, expand, checkbox, password, editor
292
+ - ``name``: (String) The name to use when storing the answer in the answers
293
+ hash.
294
+ - ``message``: (String\|Function) The question to print. If defined as a
295
+ function, the first parameter will be the current inquirer session
296
+ answers.
297
+ - ``default``: (String\|Number\|Array\|Function) Default value(s) to use if
298
+ nothing is entered, or a function that returns the default value(s).
299
+ If defined as a function, the first parameter will be the current
300
+ inquirer session answers.
301
+ - ``choices``: (Array\|Function) Choices array or a function returning a
302
+ choices array. If defined as a function, the first parameter will be
303
+ the current inquirer session answers. Array values can be simple
304
+ strings, or objects containing a name (to display in list) and a value
305
+ (to save in the answers hash) property. The choices array can also contain a
306
+ Separator.
307
+ - ``validate``: (Function) Receive the user input and should return true if
308
+ the value is valid, and an error message (String) otherwise. If false
309
+ is returned, a default error message is provided.
310
+ - ``filter``: (Function) Receive the user input and return the filtered
311
+ value to be used inside the program. The value returned will be added
312
+ to the Answers hash.
313
+ - ``when``: (Function, Boolean) Receive the current user answers hash and
314
+ should return true or false depending on whether or not this question
315
+ should be asked. The value can also be a simple boolean.
316
+
317
+ Prompt Options
318
+ ~~~~~~~~~~~~~~
319
+
320
+ ``prompt(questions, answers=None, **options)`` takes the answers of a previous
321
+ prompt and the following options:
322
+
323
+ - ``style``: the style to use.
324
+ - ``raise_keyboard_interrupt``: with ``True`` pressing Ctrl-C raises
325
+ ``KeyboardInterrupt``. By default a message is printed and ``prompt``
326
+ returns an empty dictionary.
327
+ - ``keyboard_interrupt_msg``: the message for Ctrl-C. Defaults to
328
+ ``Cancelled by user``.
329
+
330
+ User Interfaces and Styles
331
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~
332
+
333
+ The colors are set by a style:
334
+
335
+ .. code:: python
336
+
337
+ from PyInquirer import prompt, style_from_dict, Token
338
+
339
+ style = style_from_dict({
340
+ Token.QuestionMark: '#E91E63 bold',
341
+ Token.Selected: '#673AB7 bold',
342
+ Token.Answer: '#2196f3 bold',
343
+ })
344
+
345
+ answers = prompt(questions, style=style)
346
+
347
+ Windows Platform
348
+ ----------------
349
+
350
+ **``PyInquirer``** is build on prompt\_toolkit which is cross platform,
351
+ and everything that you build on top should run fine on both Unix and
352
+ Windows systems. On Windows, it uses a different event loop
353
+ (WaitForMultipleObjects instead of select), and another input and output
354
+ system. (Win32 APIs instead of pseudo-terminals and VT100.)
355
+
356
+ It's worth noting that the implementation is a "best effort of what is
357
+ possible". Both Unix and Windows terminals have their limitations. But
358
+ in general, the Unix experience will still be a little better.
359
+
360
+ For Windows, it's recommended to use either cmder or conemu.
361
+
362
+ Support
363
+ -------
364
+
365
+ Most of the questions are probably related to using a question type or
366
+ feature. Please lookup and study the appropriate examples.
367
+
368
+ You can also open an `issue on GitHub <https://github.com/CITGuru/PyInquirer/issues>`__.
369
+
370
+ For many issues like for example common Python programming issues
371
+ stackoverflow might be a good place to search for an answer.
372
+
373
+ Contribution
374
+ ------------
375
+
376
+ .. code:: shell
377
+
378
+ $ git clone git@github.com:CITGuru/PyInquirer.git
379
+ $ cd PyInquirer
380
+ $ python -m venv venv
381
+ $ source venv/bin/activate
382
+ $ pip install --upgrade pip
383
+ $ pip install -r requirements.txt
384
+ $ pip install -r requirements_dev.txt
385
+
386
+ With an environment ready you can add new feature and check everything works
387
+ just fine
388
+
389
+ .. code:: shell
390
+
391
+ $ pytest -sv tests/
392
+
393
+ That's it, now you can fork a project and submit PR with your change!
394
+
395
+ License
396
+ -------
397
+
398
+ Copyright (c) 2018 Oyetoke Toby (twitter: @oyetokeT)
399
+
400
+ Licensed under the MIT license.
401
+
402
+ .. |Expand prompt closed| image:: https://raw.githubusercontent.com/citguru/PyInquirer/master/docs/images/expand-prompt-1.png
403
+ .. |Expand prompt expanded| image:: https://raw.githubusercontent.com/citguru/PyInquirer/master/docs/images/expand-prompt-2.png
@@ -10,7 +10,7 @@ from prompt_toolkit.validation import Validator, ValidationError
10
10
  from .utils import print_json, format_json
11
11
 
12
12
 
13
- __version__ = '1.0.2'
13
+ __version__ = '1.0.4'
14
14
 
15
15
 
16
16
  def here(p):
@@ -18,6 +18,7 @@ def prompt(questions, answers=None, **kwargs):
18
18
  true_color = kwargs.pop('true_color', False)
19
19
  refresh_interval = kwargs.pop('refresh_interval', 0)
20
20
  eventloop = kwargs.pop('eventloop', None)
21
+ raise_kbi = kwargs.pop('raise_keyboard_interrupt', False)
21
22
  kbi_msg = kwargs.pop('keyboard_interrupt_msg', 'Cancelled by user')
22
23
 
23
24
  for question in questions:
@@ -42,7 +43,7 @@ def prompt(questions, answers=None, **kwargs):
42
43
  when = _kwargs.pop('when', None)
43
44
  filter = _kwargs.pop('filter', None)
44
45
 
45
- if when:
46
+ if when is not None:
46
47
  # at least a little sanity check!
47
48
  if callable(question['when']):
48
49
  try:
@@ -52,7 +53,9 @@ def prompt(questions, answers=None, **kwargs):
52
53
  raise ValueError(
53
54
  'Problem in \'when\' check of %s question: %s' %
54
55
  (name, e))
55
- else:
56
+ elif when is False:
57
+ continue
58
+ elif when and when is not True:
56
59
  raise ValueError('\'when\' needs to be function that ' \
57
60
  'accepts a dict argument')
58
61
  if filter:
@@ -64,6 +67,9 @@ def prompt(questions, answers=None, **kwargs):
64
67
  if callable(question.get('default')):
65
68
  _kwargs['default'] = question['default'](answers)
66
69
 
70
+ if callable(message):
71
+ message = message(answers)
72
+
67
73
  application = getattr(prompts, type).question(message, **_kwargs)
68
74
 
69
75
  answer = run_application(
@@ -87,6 +93,8 @@ def prompt(questions, answers=None, **kwargs):
87
93
  print(e)
88
94
  raise ValueError('No question type \'%s\'' % type)
89
95
  except KeyboardInterrupt:
96
+ if raise_kbi:
97
+ raise
90
98
  print('')
91
99
  print(kbi_msg)
92
100
  print('')
@@ -7,12 +7,13 @@ from prompt_toolkit.application import Application
7
7
  from prompt_toolkit.key_binding.manager import KeyBindingManager
8
8
  from prompt_toolkit.keys import Keys
9
9
  from prompt_toolkit.layout.containers import Window
10
- from prompt_toolkit.filters import IsDone
10
+ from prompt_toolkit.filters import Condition, IsDone
11
11
  from prompt_toolkit.layout.controls import TokenListControl
12
12
  from prompt_toolkit.layout.containers import ConditionalContainer, \
13
13
  ScrollOffsets, HSplit
14
14
  from prompt_toolkit.layout.dimension import LayoutDimension as D
15
15
  from prompt_toolkit.token import Token
16
+ from prompt_toolkit.validation import ValidationError
16
17
 
17
18
  from .. import PromptParameterException
18
19
  from ..separator import Separator
@@ -27,6 +28,7 @@ class InquirerControl(TokenListControl):
27
28
  self.pointer_index = 0
28
29
  self.selected_options = [] # list of names
29
30
  self.answered = False
31
+ self.error_message = None
30
32
  self._init_choices(choices)
31
33
  super(InquirerControl, self).__init__(self._get_choice_tokens,
32
34
  **kwargs)
@@ -39,11 +41,13 @@ class InquirerControl(TokenListControl):
39
41
  if isinstance(c, Separator):
40
42
  self.choices.append(c)
41
43
  else:
44
+ if not hasattr(c, 'get'): # not a dict
45
+ c = {'name': c}
42
46
  name = c['name']
43
47
  value = c.get('value', name)
44
48
  disabled = c.get('disabled', None)
45
49
  if 'checked' in c and c['checked'] and not disabled:
46
- self.selected_options.append(c['name'])
50
+ self.selected_options.append(value)
47
51
  self.choices.append((name, value, disabled))
48
52
  if searching_first_choice and not disabled: # find the first (available) choice
49
53
  self.pointer_index = i
@@ -69,6 +73,7 @@ class InquirerControl(TokenListControl):
69
73
  @if_mousedown
70
74
  def select_item(cli, mouse_event):
71
75
  # bind option with this index to mouse event
76
+ self.error_message = None
72
77
  if line_value in self.selected_options:
73
78
  self.selected_options.remove(line_value)
74
79
  else:
@@ -90,7 +95,7 @@ class InquirerControl(TokenListControl):
90
95
  if pointed_at:
91
96
  tokens.append((Token.SetCursorPosition, ''))
92
97
 
93
- tokens.append((T, line_name, select_item))
98
+ tokens.append((T, '%s' % line_name, select_item))
94
99
  tokens.append((T, '\n'))
95
100
 
96
101
  # prepare the select choices
@@ -112,7 +117,6 @@ class InquirerControl(TokenListControl):
112
117
  def question(message, **kwargs):
113
118
  # TODO add bottom-bar (Move up and down to reveal more choices)
114
119
  # TODO extract common parts for list, checkbox, rawlist, expand
115
- # TODO validate
116
120
  if not 'choices' in kwargs:
117
121
  raise PromptParameterException('choices')
118
122
  # this does not implement default, use checked...
@@ -149,6 +153,9 @@ def question(message, **kwargs):
149
153
  'to toggle, <i> to invert)'))
150
154
  return tokens
151
155
 
156
+ def get_error_tokens(cli):
157
+ return [(Token.Toolbar.Validation, ic.error_message or '')]
158
+
152
159
  # assemble layout
153
160
  layout = HSplit([
154
161
  Window(height=D.exact(1),
@@ -162,6 +169,14 @@ def question(message, **kwargs):
162
169
  scroll_offsets=ScrollOffsets(top=1, bottom=1)
163
170
  ),
164
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))
165
180
  )
166
181
  ])
167
182
 
@@ -176,6 +191,7 @@ def question(message, **kwargs):
176
191
 
177
192
  @manager.registry.add_binding(' ', eager=True)
178
193
  def toggle(event):
194
+ ic.error_message = None
179
195
  pointed_choice = ic.choices[ic.pointer_index][1] # value
180
196
  if pointed_choice in ic.selected_options:
181
197
  ic.selected_options.remove(pointed_choice)
@@ -184,6 +200,7 @@ def question(message, **kwargs):
184
200
 
185
201
  @manager.registry.add_binding('i', eager=True)
186
202
  def invert(event):
203
+ ic.error_message = None
187
204
  inverted_selection = [c[1] for c in ic.choices if
188
205
  not isinstance(c, Separator) and
189
206
  c[1] not in ic.selected_options and
@@ -192,6 +209,7 @@ def question(message, **kwargs):
192
209
 
193
210
  @manager.registry.add_binding('a', eager=True)
194
211
  def all(event):
212
+ ic.error_message = None
195
213
  all_selected = True # all choices have been selected
196
214
  for c in ic.choices:
197
215
  if not isinstance(c, Separator) and c[1] not in ic.selected_options and not c[2]:
@@ -221,9 +239,14 @@ def question(message, **kwargs):
221
239
 
222
240
  @manager.registry.add_binding(Keys.Enter, eager=True)
223
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
224
248
  ic.answered = True
225
- # TODO use validator
226
- event.cli.set_return_value(ic.get_selected_values())
249
+ event.cli.set_return_value(answer)
227
250
 
228
251
  return Application(
229
252
  layout=layout,
@@ -3,6 +3,7 @@
3
3
  common prompt functionality
4
4
  """
5
5
 
6
+ import inspect
6
7
  import sys
7
8
 
8
9
  from prompt_toolkit.validation import Validator, ValidationError
@@ -33,8 +34,10 @@ def setup_validator(kwargs):
33
34
  # note this works on a dictionary
34
35
  validate_prompt = kwargs.pop('validate', None)
35
36
  if validate_prompt:
36
- if issubclass(validate_prompt, Validator):
37
+ if inspect.isclass(validate_prompt) and issubclass(validate_prompt, Validator):
37
38
  kwargs['validator'] = validate_prompt()
39
+ elif isinstance(validate_prompt, Validator):
40
+ kwargs['validator'] = validate_prompt
38
41
  elif callable(validate_prompt):
39
42
  class _InputValidator(Validator):
40
43
  def validate(self, document):
@@ -44,23 +47,20 @@ def setup_validator(kwargs):
44
47
  raise ValidationError(
45
48
  message=verdict,
46
49
  cursor_position=len(document.text))
47
- elif verdict is not True:
50
+ elif not verdict == True:
48
51
  raise ValidationError(
49
52
  message='invalid input',
50
53
  cursor_position=len(document.text))
51
54
  kwargs['validator'] = _InputValidator()
52
- return kwargs['validator']
53
55
 
54
56
 
55
57
  def setup_simple_validator(kwargs):
56
58
  # this is an internal helper not meant for public consumption!
57
59
  # note this works on a dictionary
58
60
  # this validates the answer not a buffer
59
- # TODO
60
- # not sure yet how to deal with the validation result:
61
- # https://github.com/jonathanslenders/python-prompt-toolkit/issues/430
62
61
  validate = kwargs.pop('validate', None)
63
- if validate is None:
62
+ # Validator classes validate a buffer, they can't be used here
63
+ if validate is None or inspect.isclass(validate):
64
64
  def _always(answer):
65
65
  return True
66
66
  return _always
@@ -73,7 +73,7 @@ def setup_simple_validator(kwargs):
73
73
  raise ValidationError(
74
74
  message=verdict
75
75
  )
76
- elif verdict is not True:
76
+ elif not verdict == True:
77
77
  raise ValidationError(
78
78
  message='invalid input'
79
79
  )
@@ -56,6 +56,10 @@ def question(message, **kwargs):
56
56
  def _(event):
57
57
  raise KeyboardInterrupt()
58
58
 
59
+ @manager.registry.add_binding(Keys.Any)
60
+ def ignore_other_keys(event):
61
+ pass
62
+
59
63
  @manager.registry.add_binding('n')
60
64
  @manager.registry.add_binding('N')
61
65
  def key_n(event):
@@ -7,10 +7,9 @@ import os
7
7
  import sys
8
8
  from prompt_toolkit.token import Token
9
9
  from prompt_toolkit.shortcuts import create_prompt_application
10
- from prompt_toolkit.validation import Validator, ValidationError
11
10
  from prompt_toolkit.layout.lexers import SimpleLexer
12
11
 
13
- from .common import default_style
12
+ from .common import default_style, setup_validator
14
13
 
15
14
 
16
15
  # use std prompt-toolkit control
@@ -134,21 +133,7 @@ def edit(text=None, editor=None, env=None, require_save=True,
134
133
  def question(message, **kwargs):
135
134
  default = kwargs.pop('default', '')
136
135
  eargs = kwargs.pop('eargs', {})
137
- validate_prompt = kwargs.pop('validate', None)
138
- if validate_prompt:
139
- if issubclass(validate_prompt, Validator):
140
- kwargs['validator'] = validate_prompt()
141
- elif callable(validate_prompt):
142
- class _InputValidator(Validator):
143
- def validate(self, document):
144
- verdict = validate_prompt(document.text)
145
- if not verdict == True:
146
- if verdict == False:
147
- verdict = 'invalid input'
148
- raise ValidationError(
149
- message=verdict,
150
- cursor_position=len(document.text))
151
- kwargs['validator'] = _InputValidator()
136
+ setup_validator(kwargs)
152
137
 
153
138
  for k, v in eargs.items():
154
139
  if v == "" or v == " ":