meerschaum.utils.prompt

Functions for interacting with the user.

  1#! /usr/bin/env python
  2# -*- coding: utf-8 -*-
  3# vim:fenc=utf-8
  4
  5"""
  6Functions for interacting with the user.
  7"""
  8
  9from __future__ import annotations
 10
 11import os
 12import meerschaum as mrsm
 13from meerschaum.utils.typing import Any, Union, Optional, Tuple, List
 14
 15
 16def _forwarded_terminal_session():
 17    """Give SDK prompts terminal controls and live dimensions through the shell's pipe."""
 18    import sys
 19    from contextlib import nullcontext
 20    from meerschaum.utils.formatting import _forwarded_terminal
 21
 22    if os.name != 'posix' or not _forwarded_terminal(sys.stdout) or not sys.stdin.isatty():
 23        return nullcontext()
 24
 25    from prompt_toolkit.application import create_app_session, get_app_session
 26    from prompt_toolkit.data_structures import Size
 27    from prompt_toolkit.output.plain_text import PlainTextOutput
 28    from prompt_toolkit.output.vt100 import Vt100_Output
 29    from prompt_toolkit.output.color_depth import ColorDepth
 30    from prompt_toolkit.utils import get_bell_environment_variable
 31
 32    original = get_app_session().output
 33    # Respect an application's explicit output (e.g. a capture or a custom terminal).
 34    if not isinstance(original, PlainTextOutput) or original.stdout is not sys.stdout:
 35        return nullcontext()
 36
 37    def get_size():
 38        try:
 39            columns, rows = os.get_terminal_size(sys.stdin.fileno())
 40            return Size(rows=rows or 24, columns=columns or 80)
 41        except (OSError, ValueError):
 42            return original.get_size()
 43
 44    output = Vt100_Output(
 45        sys.stdout,
 46        get_size,
 47        term=os.environ.get('TERM'),
 48        default_color_depth=ColorDepth.from_env(),
 49        enable_bell=get_bell_environment_variable(),
 50    )
 51    return create_app_session(output=output)
 52
 53
 54def _read_suggested(question: str, items: List[str], prefill: str = '') -> str:
 55    """Read a native action's already-formatted prompt with a filtering dropdown."""
 56    from meerschaum.utils.packages import attempt_import
 57    toolkit = attempt_import('prompt_toolkit', lazy=False)
 58    completion = attempt_import('prompt_toolkit.completion', lazy=False)
 59
 60    def show_suggestions():
 61        toolkit.application.current.get_app().current_buffer.start_completion(select_first=False)
 62
 63    with _forwarded_terminal_session():
 64        return toolkit.prompt(
 65            toolkit.formatted_text.ANSI(question),
 66            default=prefill,
 67            completer=completion.WordCompleter(items, ignore_case=True, match_middle=True),
 68            complete_while_typing=True,
 69            reserve_space_for_menu=min(len(items), 8),
 70            pre_run=show_suggestions,
 71        )
 72
 73
 74def prompt(
 75    question: str = '',
 76    *,
 77    icon: bool = True,
 78    default: Union[str, Tuple[str, str], None] = None,
 79    default_editable: Optional[str] = None,
 80    detect_password: bool = True,
 81    is_password: bool = False,
 82    wrap_lines: bool = True,
 83    noask: bool = False,
 84    silent: bool = False,
 85    **kw: Any
 86) -> str:
 87    """
 88    Ask the user a question and return the answer.
 89    Wrapper around `prompt_toolkit.prompt()` with modified behavior.
 90    For example, an empty string returns default instead of printing it for the user to delete
 91    (`prompt_toolkit` behavior).
 92
 93    Parameters
 94    ----------
 95    question: str
 96        The question to print to the user.
 97
 98    icon: bool, default True
 99        If True, prepend the configured icon.
100
101    default: Union[str, Tuple[str, str], None], default None
102        If the response is '', return the default value.
103
104    default_editable: Optional[str], default None
105        If provided, auto-type this user-editable string in the prompt.
106
107    detect_password: bool, default True
108        If `True`, set the input method to a censored password box if the word `password`
109        appears in the question.
110
111    is_password: default False
112        If `True`, set the input method to a censored password box.
113        May be overridden by `detect_password` unless `detect_password` is set to `False`.
114
115    wrap_lines: bool, default True
116        If `True`, wrap the text across multiple lines.
117        Flag is passed onto `prompt_toolkit`.
118
119    noask: bool, default False
120        If `True`, only print the question and return the default answer.
121
122    silent: bool, default False
123        If `True` do not print anything to the screen, but still block for input.
124
125    Returns
126    -------
127    A `str` of the input provided by the user.
128
129    """
130    from meerschaum.utils.packages import attempt_import
131    from meerschaum.utils.formatting import ANSI, CHARSET, highlight_pipes, fill_ansi
132    from meerschaum.config import get_config
133    from meerschaum.utils.misc import filter_keywords, remove_ansi
134    from meerschaum.utils.daemon import running_in_daemon, get_current_daemon
135    from meerschaum._internal.static import STATIC_CONFIG
136
137    original_kwargs = {
138        'question': question,
139        'icon': icon,
140        'default': default,
141        'default_editable': default_editable,
142        'detect_password': detect_password,
143        'is_password': is_password,
144        'wrap_lines': wrap_lines,
145        'noask': noask,
146        'silent': silent,
147        **kw
148    }
149
150    noask = check_noask(noask)
151    prompt_toolkit = attempt_import('prompt_toolkit')
152    question_config = get_config('formatting', 'question', patch=True)
153
154    ### if a default is provided, append it to the question.
155    default_answer = default
156    if default is not None:
157        question += " (default: "
158        if isinstance(default, tuple) and len(default) > 1:
159            question += f"{default[0]} [{default[1]}]"
160            default_answer = default[0]
161        else:
162            question += f"{default}"
163        question += ")"
164
165    ### detect password
166    if (detect_password and 'password' in question.lower()) or is_password:
167        kw['is_password'] = True
168
169    ### Add the icon and only color the first line.
170    lines = question.split('\n')
171    first_line = lines[0]
172    other_lines = '' if len(lines) <= 1 else '\n'.join(lines[1:])
173
174    if ANSI:
175        first_line = fill_ansi(highlight_pipes(first_line), **question_config['ansi']['rich'])
176        other_lines = highlight_pipes(other_lines)
177
178    _icon = question_config[CHARSET]['icon']
179    question = (' ' + _icon + ' ') if icon and len(_icon) > 0 else ''
180    question += first_line
181    if len(other_lines) > 0:
182        question += '\n' + other_lines
183
184    if not remove_ansi(question).endswith(' '):
185        question += ' '
186
187    prompt_kwargs = {
188        'message': prompt_toolkit.formatted_text.ANSI(question) if not silent else '',
189        'wrap_lines': wrap_lines,
190        'default': default_editable or '',
191        **filter_keywords(prompt_toolkit.prompt, **kw)
192    }
193
194    printed_question = False
195
196    if not running_in_daemon():
197        answer = ''
198        if not noask:
199            with _forwarded_terminal_session():
200                answer = prompt_toolkit.prompt(**prompt_kwargs)
201        printed_question = True
202    else:
203        import json
204        daemon = get_current_daemon()
205        print(STATIC_CONFIG['jobs']['flush_token'], end='', flush=True)
206        wrote_file = False
207        try:
208            with open(daemon.prompt_kwargs_file_path, 'w+', encoding='utf-8') as f:
209                json.dump(original_kwargs, f, separators=(',', ':'))
210            wrote_file = True
211        except Exception:
212            pass
213
214        if not silent and not wrote_file:
215            print(question, end='', flush=True)
216            print(STATIC_CONFIG['jobs']['flush_token'], end='', flush=True)
217            printed_question = True
218
219        ### On Linux the job's supervisor sees the wait; elsewhere announce it for `attach`.
220        announced = _announce_wait(daemon) if not noask else None
221        try:
222            answer = input() if not noask else ''
223        except EOFError:
224            answer = ''
225        finally:
226            if announced is not None:
227                try:
228                    announced.unlink()
229                except OSError:
230                    pass
231
232    if noask and not silent and not printed_question:
233        print(question)
234
235    if answer == '' and default is not None:
236        return default_answer
237
238    return answer
239
240
241def _announce_wait(daemon) -> Optional[pathlib.Path]:
242    """
243    Create the job's `input.stdin.block` marker before reading its input on systems where the
244    job's supervisor cannot observe the wait (anything but Linux). Return the marker to remove.
245    """
246    import sys
247    if sys.platform.startswith('linux') or daemon is None:
248        return None
249    try:
250        marker = daemon.blocking_stdin_file_path
251        marker.touch()
252        return marker
253    except Exception:
254        return None
255
256
257def yes_no(
258    question: str = '',
259    options: Tuple[str, str] = ('y', 'n'),
260    default: str = 'y',
261    wrappers: Tuple[str, str] = ('[', ']'),
262    icon: bool = True,
263    yes: bool = False,
264    noask: bool = False,
265    **kw : Any
266) -> bool:
267    """
268    Print a question and prompt the user with a yes / no input.
269    Returns `True` for `'yes'`, False for `'no'`.
270
271    Parameters
272    ----------
273    question: str, default ''
274        The question to print to the user.
275
276    options: Tuple[str, str], default ('y', 'n')
277        The `y/n` options. The first is considered `True`, and all options must be lower case.
278
279    default: str, default y
280        The default option. Is represented with a capital to distinguish that it's the default.
281
282    wrappers: Tuple[str, str], default ('[', ']')
283        Text to print around the '[y/n]' options.
284
285    icon: bool, default True
286        If True, prepend the configured question icon.
287
288    Returns
289    -------
290    A bool indicating the user's choice.
291
292    Examples
293    --------
294    ```python-repl
295    >>> yes_no("Do you like me?", default='y')
296     ❓ Do you like me? [Y/n]
297    True
298    >>> yes_no("Cats or dogs?", options=('cats', 'dogs'))
299     ❓ Cats or dogs? [cats/dogs]
300     Please enter a valid response.
301     ❓ Cats or dogs? [cats/dogs] dogs
302    False
303    ```
304    """
305    from meerschaum.utils.warnings import error, warn
306
307    default = options[0] if yes else default
308    noask = yes or check_noask(noask)
309
310    ending = f" {wrappers[0]}" + "/".join(
311        [
312            o.upper() if o.lower() == default.lower()
313            else o.lower() for o in options
314        ]
315    ) + f"{wrappers[1]}"
316    while True:
317        try:
318            answer = prompt(question + ending, icon=icon, detect_password=False, noask=noask)
319            success = True
320        except KeyboardInterrupt:
321            success = False
322        
323        if not success:
324            error("Error getting response. Aborting...", stack=False)
325        if answer == "":
326            answer = default
327
328        if answer.lower() in options:
329            break
330        warn('Please enter a valid reponse.', stack=False)
331    
332    return answer.lower() == options[0].lower()
333
334
335def choose(
336    question: str,
337    choices: Union[List[str], List[Tuple[str, str]]],
338    default: Union[str, List[str], None] = None,
339    numeric: bool = True,
340    multiple: bool = False,
341    as_indices: bool = False,
342    delimiter: str = ',',
343    icon: bool = True,
344    warn: bool = True,
345    noask: bool = False,
346    **kw
347) -> Union[str, Tuple[str], None]:
348    """
349    Present a list of options and return the user's choice.
350
351    Parameters
352    ----------
353    question: str
354        The question to be printed.
355
356    choices: List[Union[str, Tuple[str, str]]
357        A list of options.
358        If an option is a tuple of two strings, the first string is treated as the index
359        and not displayed. In this case, set `as_indices` to `True` to return the index.
360
361    default: Union[str, List[str], None], default None
362        If the user declines to enter a choice, return this value.
363
364    numeric: bool, default True
365        If `True`, number the items in the list and ask for a number as input.
366        If `False`, require the user to type the complete string.
367
368    multiple: bool, default False
369        If `True`, allow the user to choose multiple answers separated by `delimiter`.
370
371    as_indices: bool, default False
372        If `True`, return the indices for the choices.
373        If a choice is a tuple of two strings, the first is assumed to be the index.
374        Otherwise the index in the list is returned.
375
376    delimiter: str, default ','
377        If `multiple`, separate answers by this string. Raise a warning if this string is contained
378        in any of the choices.
379
380    icon: bool, default True
381        If `True`, include the question icon.
382
383    warn: bool, default True
384        If `True`, raise warnings when invalid input is entered.
385
386    noask: bool, default False
387        If `True`, skip printing the question and return the default value.
388
389    Returns
390    -------
391    A string for a single answer or a tuple of strings if `multiple` is `True`.
392
393    """
394    from meerschaum.utils.warnings import warn as _warn
395    from meerschaum.utils.packages import attempt_import
396    from meerschaum.utils.misc import print_options
397    noask = check_noask(noask)
398
399    ### Handle empty choices.
400    if not choices:
401        if warn:
402            _warn(f"No available choices. Returning default value '{default}'.", stacklevel=3)
403        return default
404
405    ### If the default case is to include multiple answers, allow for multiple inputs.
406    if isinstance(default, list):
407        multiple = True
408
409    choices_indices = {}
410    for i, c in enumerate(choices, start=1):
411        if isinstance(c, tuple):
412            i, c = c
413        choices_indices[i] = c
414
415    choices_values_indices = {v: k for k, v in choices_indices.items()}
416    ordered_keys = list(choices_indices.keys())
417    numeric_map = {str(i): key for i, key in enumerate(ordered_keys, 1)}
418
419    def _enforce_default(d):
420        if d is None:
421            return True
422        if d not in choices_values_indices and d not in choices_indices:
423            if warn:
424                _warn(
425                    f"Default choice '{d}' is not contained in the choices. "
426                    + "Setting numeric = False.",
427                    stacklevel=3
428                )
429            return False
430        return True
431
432    ### Throw a warning if the default isn't a choice.
433    for d in (default if isinstance(default, list) else [default]):
434        if not _enforce_default(d):
435            numeric = False
436            break
437
438    _choices = (
439        [str(k) for k in choices_indices] if numeric
440        else list(choices_indices.values())
441    )
442    if multiple:
443        question += f"\n    Enter your choices, separated by '{delimiter}'.\n"
444
445    altered_choices = {}
446    if multiple and not numeric:
447        delim_replacement = '_' if delimiter != '_' else '-'
448        ### Check if the choices have the delimiter.
449        for i, c in choices_indices.items():
450            if delimiter not in c:
451                continue
452            if warn:
453                _warn(
454                    f"The delimiter '{delimiter}' is contained within choice '{c}'.\n"
455                    + f"Replacing the string '{delimiter}' with '{delim_replacement}' in "
456                    + "the choice for correctly parsing input (will be replaced upon returning the prompt).",
457                    stacklevel=3,
458                )
459            new_c = c.replace(delimiter, delim_replacement)
460            altered_choices[new_c] = c
461            choices_indices[i] = new_c
462
463    question_options = []
464    default_tuple = None
465    if numeric:
466        _default_prompt_str = ''
467        if default is not None:
468            default_list = default if isinstance(default, list) else [default]
469            if multiple and isinstance(default, str):
470                default_list = default.split(delimiter)
471
472            _default_indices = []
473            for d in default_list:
474                key = None
475                if d in choices_values_indices:  # is a value
476                    key = choices_values_indices[d]
477                elif d in choices_indices:  # is an index
478                    key = d
479
480                if key in ordered_keys:
481                    _default_indices.append(str(ordered_keys.index(key) + 1))
482
483            _default_prompt_str = delimiter.join(_default_indices)
484        
485        choices_digits = len(str(len(choices)))
486        for choice_ix, c in enumerate(choices_indices.values(), start=1):
487            question_options.append(
488                f"  {choice_ix}. "
489                + (" " * (choices_digits - len(str(choice_ix))))
490                + f"{c}\n"
491            )
492        default_tuple = (_default_prompt_str, default) if default is not None else None
493    else:
494        default_tuple = default
495        for c in choices_indices.values():
496            question_options.append(f"  • {c}\n")
497
498    if 'completer' not in kw:
499        WordCompleter = attempt_import('prompt_toolkit.completion', lazy=False).WordCompleter
500        kw['completer'] = WordCompleter(
501            [str(v) for v in choices_indices.values()] + [str(i) for i in choices_indices],
502            sentence=True,
503        )
504
505    answers = []
506    while not answers:
507        print_options(question_options, header='')
508        answer = prompt(
509            question,
510            icon=icon,
511            default=default_tuple,
512            noask=noask,
513            **kw
514        )
515        if not answer and default is not None:
516            answer = default if isinstance(default, str) else delimiter.join(default)
517
518        if not answer:
519            if warn:
520                _warn("Please pick a valid choice.", stack=False)
521            continue
522
523        _answers = [answer] if not multiple else [a.strip() for a in answer.split(delimiter)]
524        _answers = [a for a in _answers if a]
525
526        if numeric:
527            _raw_answers = list(_answers)
528            _answers = []
529            for _a in _raw_answers:
530                if _a in choices_values_indices:
531                    _answers.append(str(choices_values_indices[_a]))
532                elif _a in numeric_map:
533                    _answers.append(str(numeric_map[_a]))
534                else:
535                    _answers.append(_a)
536
537        _processed_answers = [altered_choices.get(a, a) for a in _answers]
538
539        valid_answers = []
540        for a in _processed_answers:
541            if a in _choices:
542                valid_answers.append(a)
543
544        if len(valid_answers) != len(_processed_answers):
545            if warn:
546                _warn("Please pick a valid choice.", stack=False)
547            continue
548        answers = valid_answers
549
550    def get_key(key_str):
551        try:
552            return int(key_str)
553        except (ValueError, TypeError):
554            return key_str
555
556    if not multiple:
557        answer = answers[0]
558        if not numeric:
559            return choices_values_indices.get(answer, answer) if as_indices else answer
560        
561        key = get_key(answer)
562        return key if as_indices else choices_indices[key]
563
564    if not numeric:
565        return [choices_values_indices.get(a, a) for a in answers] if as_indices else answers
566
567    final_answers = []
568    for a in answers:
569        key = get_key(a)
570        final_answers.append(key if as_indices else choices_indices[key])
571    return final_answers
572
573
574
575def get_password(
576    username: Optional[str] = None,
577    minimum_length: Optional[int] = None,
578    confirm: bool = True,
579    **kw: Any
580) -> str:
581    """
582    Prompt the user for a password.
583
584    Parameters
585    ----------
586    username: Optional[str], default None
587        If provided, print the username when asking for a password.
588
589    minimum_length: Optional[int], default None
590        If provided, enforce a password of at least this length.
591
592    confirm: bool, default True
593        If `True`, prompt the user for a password twice.
594
595    Returns
596    -------
597    The password string (censored from terminal output when typing).
598
599    Examples
600    --------
601    ```python-repl
602    >>> get_password()
603     ❓ Password: *******
604     ❓ Confirm password: *******
605    'hunter2'
606    ```
607
608    """
609    from meerschaum.utils.warnings import warn
610    while True:
611        password = prompt(
612            "Password" + (f" for user '{username}':" if username is not None else ":"),
613            is_password=True,
614            **kw
615        )
616        if minimum_length is not None and len(password) < minimum_length:
617            warn(
618                "Password is too short. " +
619                f"Please enter a password that is at least {minimum_length} characters.",
620                stack=False
621            )
622            continue
623
624        if not confirm:
625            return password
626
627        _password = prompt(
628            "Confirm password" + (f" for user '{username}':" if username is not None else ":"),
629            is_password=True,
630            **kw
631        )
632        if password != _password:
633            warn("Passwords do not match! Please try again.", stack=False)
634            continue
635        else:
636            return password
637
638
639def get_email(username: Optional[str] = None, allow_omit: bool = True, **kw: Any) -> str:
640    """
641    Prompt the user for an email and enforce that it's valid.
642
643    Parameters
644    ----------
645    username: Optional[str], default None
646        If provided, print the username in the prompt.
647
648    allow_omit: bool, default True
649        If `True`, allow the user to omit the email.
650
651    Returns
652    -------
653    The provided email string.
654
655    Examples
656    --------
657    ```python-repl
658    >>> get_email()
659     ❓ Email (empty to omit): foo@foo
660     Invalid email! Please try again.
661     ❓ Email (empty to omit): foo@foo.com
662    'foo@foo.com'
663    ```
664    """
665    from meerschaum.utils.warnings import warn
666    from meerschaum.utils.misc import is_valid_email
667    while True:
668        email = prompt(
669            "Email" + (f" for user '{username}'" if username is not None else "") +
670            (" (empty to omit):" if allow_omit else ": "),
671            **kw
672        )
673        if (allow_omit and email == '') or is_valid_email(email):
674            return email
675        warn("Invalid email! Please try again.", stack=False)
676
677
678def check_noask(noask: bool = False) -> bool:
679    """
680    Flip `noask` to `True` if `MRSM_NOASK` is set.
681    """
682    from meerschaum._internal.static import STATIC_CONFIG
683    NOASK = STATIC_CONFIG['environment']['noask']
684    if noask:
685        return True
686
687    return (
688        os.environ.get(NOASK, 'false').lower()
689        in ('1', 'true')
690    )
691
692
693def get_connectors_completer(*types: str):
694    """
695    Return a prompt-toolkit Completer object to pass into `prompt()`.
696    """
697    from meerschaum.utils.misc import get_connector_labels
698    prompt_toolkit_completion = mrsm.attempt_import('prompt_toolkit.completion', lazy=False)
699    Completer = prompt_toolkit_completion.Completer
700    Completion = prompt_toolkit_completion.Completion
701
702    class ConnectorCompleter(Completer):
703        def get_completions(self, document, complete_event):
704            for label in get_connector_labels(*types, search_term=document.text):
705                yield Completion(label, start_position=(-1 * len(document.text)))
706
707    return ConnectorCompleter()
def prompt( question: str = '', *, icon: bool = True, default: str | Tuple[str, str] | None = None, default_editable: str | None = None, detect_password: bool = True, is_password: bool = False, wrap_lines: bool = True, noask: bool = False, silent: bool = False, **kw: Any) -> str:
 75def prompt(
 76    question: str = '',
 77    *,
 78    icon: bool = True,
 79    default: Union[str, Tuple[str, str], None] = None,
 80    default_editable: Optional[str] = None,
 81    detect_password: bool = True,
 82    is_password: bool = False,
 83    wrap_lines: bool = True,
 84    noask: bool = False,
 85    silent: bool = False,
 86    **kw: Any
 87) -> str:
 88    """
 89    Ask the user a question and return the answer.
 90    Wrapper around `prompt_toolkit.prompt()` with modified behavior.
 91    For example, an empty string returns default instead of printing it for the user to delete
 92    (`prompt_toolkit` behavior).
 93
 94    Parameters
 95    ----------
 96    question: str
 97        The question to print to the user.
 98
 99    icon: bool, default True
100        If True, prepend the configured icon.
101
102    default: Union[str, Tuple[str, str], None], default None
103        If the response is '', return the default value.
104
105    default_editable: Optional[str], default None
106        If provided, auto-type this user-editable string in the prompt.
107
108    detect_password: bool, default True
109        If `True`, set the input method to a censored password box if the word `password`
110        appears in the question.
111
112    is_password: default False
113        If `True`, set the input method to a censored password box.
114        May be overridden by `detect_password` unless `detect_password` is set to `False`.
115
116    wrap_lines: bool, default True
117        If `True`, wrap the text across multiple lines.
118        Flag is passed onto `prompt_toolkit`.
119
120    noask: bool, default False
121        If `True`, only print the question and return the default answer.
122
123    silent: bool, default False
124        If `True` do not print anything to the screen, but still block for input.
125
126    Returns
127    -------
128    A `str` of the input provided by the user.
129
130    """
131    from meerschaum.utils.packages import attempt_import
132    from meerschaum.utils.formatting import ANSI, CHARSET, highlight_pipes, fill_ansi
133    from meerschaum.config import get_config
134    from meerschaum.utils.misc import filter_keywords, remove_ansi
135    from meerschaum.utils.daemon import running_in_daemon, get_current_daemon
136    from meerschaum._internal.static import STATIC_CONFIG
137
138    original_kwargs = {
139        'question': question,
140        'icon': icon,
141        'default': default,
142        'default_editable': default_editable,
143        'detect_password': detect_password,
144        'is_password': is_password,
145        'wrap_lines': wrap_lines,
146        'noask': noask,
147        'silent': silent,
148        **kw
149    }
150
151    noask = check_noask(noask)
152    prompt_toolkit = attempt_import('prompt_toolkit')
153    question_config = get_config('formatting', 'question', patch=True)
154
155    ### if a default is provided, append it to the question.
156    default_answer = default
157    if default is not None:
158        question += " (default: "
159        if isinstance(default, tuple) and len(default) > 1:
160            question += f"{default[0]} [{default[1]}]"
161            default_answer = default[0]
162        else:
163            question += f"{default}"
164        question += ")"
165
166    ### detect password
167    if (detect_password and 'password' in question.lower()) or is_password:
168        kw['is_password'] = True
169
170    ### Add the icon and only color the first line.
171    lines = question.split('\n')
172    first_line = lines[0]
173    other_lines = '' if len(lines) <= 1 else '\n'.join(lines[1:])
174
175    if ANSI:
176        first_line = fill_ansi(highlight_pipes(first_line), **question_config['ansi']['rich'])
177        other_lines = highlight_pipes(other_lines)
178
179    _icon = question_config[CHARSET]['icon']
180    question = (' ' + _icon + ' ') if icon and len(_icon) > 0 else ''
181    question += first_line
182    if len(other_lines) > 0:
183        question += '\n' + other_lines
184
185    if not remove_ansi(question).endswith(' '):
186        question += ' '
187
188    prompt_kwargs = {
189        'message': prompt_toolkit.formatted_text.ANSI(question) if not silent else '',
190        'wrap_lines': wrap_lines,
191        'default': default_editable or '',
192        **filter_keywords(prompt_toolkit.prompt, **kw)
193    }
194
195    printed_question = False
196
197    if not running_in_daemon():
198        answer = ''
199        if not noask:
200            with _forwarded_terminal_session():
201                answer = prompt_toolkit.prompt(**prompt_kwargs)
202        printed_question = True
203    else:
204        import json
205        daemon = get_current_daemon()
206        print(STATIC_CONFIG['jobs']['flush_token'], end='', flush=True)
207        wrote_file = False
208        try:
209            with open(daemon.prompt_kwargs_file_path, 'w+', encoding='utf-8') as f:
210                json.dump(original_kwargs, f, separators=(',', ':'))
211            wrote_file = True
212        except Exception:
213            pass
214
215        if not silent and not wrote_file:
216            print(question, end='', flush=True)
217            print(STATIC_CONFIG['jobs']['flush_token'], end='', flush=True)
218            printed_question = True
219
220        ### On Linux the job's supervisor sees the wait; elsewhere announce it for `attach`.
221        announced = _announce_wait(daemon) if not noask else None
222        try:
223            answer = input() if not noask else ''
224        except EOFError:
225            answer = ''
226        finally:
227            if announced is not None:
228                try:
229                    announced.unlink()
230                except OSError:
231                    pass
232
233    if noask and not silent and not printed_question:
234        print(question)
235
236    if answer == '' and default is not None:
237        return default_answer
238
239    return answer

Ask the user a question and return the answer. Wrapper around prompt_toolkit.prompt() with modified behavior. For example, an empty string returns default instead of printing it for the user to delete (prompt_toolkit behavior).

Parameters
  • question (str): The question to print to the user.
  • icon (bool, default True): If True, prepend the configured icon.
  • default (Union[str, Tuple[str, str], None], default None): If the response is '', return the default value.
  • default_editable (Optional[str], default None): If provided, auto-type this user-editable string in the prompt.
  • detect_password (bool, default True): If True, set the input method to a censored password box if the word password appears in the question.
  • is_password (default False): If True, set the input method to a censored password box. May be overridden by detect_password unless detect_password is set to False.
  • wrap_lines (bool, default True): If True, wrap the text across multiple lines. Flag is passed onto prompt_toolkit.
  • noask (bool, default False): If True, only print the question and return the default answer.
  • silent (bool, default False): If True do not print anything to the screen, but still block for input.
Returns
  • A str of the input provided by the user.
def yes_no( question: str = '', options: Tuple[str, str] = ('y', 'n'), default: str = 'y', wrappers: Tuple[str, str] = ('[', ']'), icon: bool = True, yes: bool = False, noask: bool = False, **kw: Any) -> bool:
258def yes_no(
259    question: str = '',
260    options: Tuple[str, str] = ('y', 'n'),
261    default: str = 'y',
262    wrappers: Tuple[str, str] = ('[', ']'),
263    icon: bool = True,
264    yes: bool = False,
265    noask: bool = False,
266    **kw : Any
267) -> bool:
268    """
269    Print a question and prompt the user with a yes / no input.
270    Returns `True` for `'yes'`, False for `'no'`.
271
272    Parameters
273    ----------
274    question: str, default ''
275        The question to print to the user.
276
277    options: Tuple[str, str], default ('y', 'n')
278        The `y/n` options. The first is considered `True`, and all options must be lower case.
279
280    default: str, default y
281        The default option. Is represented with a capital to distinguish that it's the default.
282
283    wrappers: Tuple[str, str], default ('[', ']')
284        Text to print around the '[y/n]' options.
285
286    icon: bool, default True
287        If True, prepend the configured question icon.
288
289    Returns
290    -------
291    A bool indicating the user's choice.
292
293    Examples
294    --------
295    ```python-repl
296    >>> yes_no("Do you like me?", default='y')
297     ❓ Do you like me? [Y/n]
298    True
299    >>> yes_no("Cats or dogs?", options=('cats', 'dogs'))
300     ❓ Cats or dogs? [cats/dogs]
301     Please enter a valid response.
302     ❓ Cats or dogs? [cats/dogs] dogs
303    False
304    ```
305    """
306    from meerschaum.utils.warnings import error, warn
307
308    default = options[0] if yes else default
309    noask = yes or check_noask(noask)
310
311    ending = f" {wrappers[0]}" + "/".join(
312        [
313            o.upper() if o.lower() == default.lower()
314            else o.lower() for o in options
315        ]
316    ) + f"{wrappers[1]}"
317    while True:
318        try:
319            answer = prompt(question + ending, icon=icon, detect_password=False, noask=noask)
320            success = True
321        except KeyboardInterrupt:
322            success = False
323        
324        if not success:
325            error("Error getting response. Aborting...", stack=False)
326        if answer == "":
327            answer = default
328
329        if answer.lower() in options:
330            break
331        warn('Please enter a valid reponse.', stack=False)
332    
333    return answer.lower() == options[0].lower()

Print a question and prompt the user with a yes / no input. Returns True for 'yes', False for 'no'.

Parameters
  • question (str, default ''): The question to print to the user.
  • options (Tuple[str, str], default ('y', 'n')): The y/n options. The first is considered True, and all options must be lower case.
  • default (str, default y): The default option. Is represented with a capital to distinguish that it's the default.
  • wrappers (Tuple[str, str], default ('[', ']')): Text to print around the '[y/n]' options.
  • icon (bool, default True): If True, prepend the configured question icon.
Returns
  • A bool indicating the user's choice.
Examples
>>> yes_no("Do you like me?", default='y')
 ❓ Do you like me? [Y/n]
True
>>> yes_no("Cats or dogs?", options=('cats', 'dogs'))
 ❓ Cats or dogs? [cats/dogs]
 Please enter a valid response.
 ❓ Cats or dogs? [cats/dogs] dogs
False
def choose( question: str, choices: List[str] | List[Tuple[str, str]], default: str | List[str] | None = None, numeric: bool = True, multiple: bool = False, as_indices: bool = False, delimiter: str = ',', icon: bool = True, warn: bool = True, noask: bool = False, **kw) -> str | Tuple[str] | None:
336def choose(
337    question: str,
338    choices: Union[List[str], List[Tuple[str, str]]],
339    default: Union[str, List[str], None] = None,
340    numeric: bool = True,
341    multiple: bool = False,
342    as_indices: bool = False,
343    delimiter: str = ',',
344    icon: bool = True,
345    warn: bool = True,
346    noask: bool = False,
347    **kw
348) -> Union[str, Tuple[str], None]:
349    """
350    Present a list of options and return the user's choice.
351
352    Parameters
353    ----------
354    question: str
355        The question to be printed.
356
357    choices: List[Union[str, Tuple[str, str]]
358        A list of options.
359        If an option is a tuple of two strings, the first string is treated as the index
360        and not displayed. In this case, set `as_indices` to `True` to return the index.
361
362    default: Union[str, List[str], None], default None
363        If the user declines to enter a choice, return this value.
364
365    numeric: bool, default True
366        If `True`, number the items in the list and ask for a number as input.
367        If `False`, require the user to type the complete string.
368
369    multiple: bool, default False
370        If `True`, allow the user to choose multiple answers separated by `delimiter`.
371
372    as_indices: bool, default False
373        If `True`, return the indices for the choices.
374        If a choice is a tuple of two strings, the first is assumed to be the index.
375        Otherwise the index in the list is returned.
376
377    delimiter: str, default ','
378        If `multiple`, separate answers by this string. Raise a warning if this string is contained
379        in any of the choices.
380
381    icon: bool, default True
382        If `True`, include the question icon.
383
384    warn: bool, default True
385        If `True`, raise warnings when invalid input is entered.
386
387    noask: bool, default False
388        If `True`, skip printing the question and return the default value.
389
390    Returns
391    -------
392    A string for a single answer or a tuple of strings if `multiple` is `True`.
393
394    """
395    from meerschaum.utils.warnings import warn as _warn
396    from meerschaum.utils.packages import attempt_import
397    from meerschaum.utils.misc import print_options
398    noask = check_noask(noask)
399
400    ### Handle empty choices.
401    if not choices:
402        if warn:
403            _warn(f"No available choices. Returning default value '{default}'.", stacklevel=3)
404        return default
405
406    ### If the default case is to include multiple answers, allow for multiple inputs.
407    if isinstance(default, list):
408        multiple = True
409
410    choices_indices = {}
411    for i, c in enumerate(choices, start=1):
412        if isinstance(c, tuple):
413            i, c = c
414        choices_indices[i] = c
415
416    choices_values_indices = {v: k for k, v in choices_indices.items()}
417    ordered_keys = list(choices_indices.keys())
418    numeric_map = {str(i): key for i, key in enumerate(ordered_keys, 1)}
419
420    def _enforce_default(d):
421        if d is None:
422            return True
423        if d not in choices_values_indices and d not in choices_indices:
424            if warn:
425                _warn(
426                    f"Default choice '{d}' is not contained in the choices. "
427                    + "Setting numeric = False.",
428                    stacklevel=3
429                )
430            return False
431        return True
432
433    ### Throw a warning if the default isn't a choice.
434    for d in (default if isinstance(default, list) else [default]):
435        if not _enforce_default(d):
436            numeric = False
437            break
438
439    _choices = (
440        [str(k) for k in choices_indices] if numeric
441        else list(choices_indices.values())
442    )
443    if multiple:
444        question += f"\n    Enter your choices, separated by '{delimiter}'.\n"
445
446    altered_choices = {}
447    if multiple and not numeric:
448        delim_replacement = '_' if delimiter != '_' else '-'
449        ### Check if the choices have the delimiter.
450        for i, c in choices_indices.items():
451            if delimiter not in c:
452                continue
453            if warn:
454                _warn(
455                    f"The delimiter '{delimiter}' is contained within choice '{c}'.\n"
456                    + f"Replacing the string '{delimiter}' with '{delim_replacement}' in "
457                    + "the choice for correctly parsing input (will be replaced upon returning the prompt).",
458                    stacklevel=3,
459                )
460            new_c = c.replace(delimiter, delim_replacement)
461            altered_choices[new_c] = c
462            choices_indices[i] = new_c
463
464    question_options = []
465    default_tuple = None
466    if numeric:
467        _default_prompt_str = ''
468        if default is not None:
469            default_list = default if isinstance(default, list) else [default]
470            if multiple and isinstance(default, str):
471                default_list = default.split(delimiter)
472
473            _default_indices = []
474            for d in default_list:
475                key = None
476                if d in choices_values_indices:  # is a value
477                    key = choices_values_indices[d]
478                elif d in choices_indices:  # is an index
479                    key = d
480
481                if key in ordered_keys:
482                    _default_indices.append(str(ordered_keys.index(key) + 1))
483
484            _default_prompt_str = delimiter.join(_default_indices)
485        
486        choices_digits = len(str(len(choices)))
487        for choice_ix, c in enumerate(choices_indices.values(), start=1):
488            question_options.append(
489                f"  {choice_ix}. "
490                + (" " * (choices_digits - len(str(choice_ix))))
491                + f"{c}\n"
492            )
493        default_tuple = (_default_prompt_str, default) if default is not None else None
494    else:
495        default_tuple = default
496        for c in choices_indices.values():
497            question_options.append(f"  • {c}\n")
498
499    if 'completer' not in kw:
500        WordCompleter = attempt_import('prompt_toolkit.completion', lazy=False).WordCompleter
501        kw['completer'] = WordCompleter(
502            [str(v) for v in choices_indices.values()] + [str(i) for i in choices_indices],
503            sentence=True,
504        )
505
506    answers = []
507    while not answers:
508        print_options(question_options, header='')
509        answer = prompt(
510            question,
511            icon=icon,
512            default=default_tuple,
513            noask=noask,
514            **kw
515        )
516        if not answer and default is not None:
517            answer = default if isinstance(default, str) else delimiter.join(default)
518
519        if not answer:
520            if warn:
521                _warn("Please pick a valid choice.", stack=False)
522            continue
523
524        _answers = [answer] if not multiple else [a.strip() for a in answer.split(delimiter)]
525        _answers = [a for a in _answers if a]
526
527        if numeric:
528            _raw_answers = list(_answers)
529            _answers = []
530            for _a in _raw_answers:
531                if _a in choices_values_indices:
532                    _answers.append(str(choices_values_indices[_a]))
533                elif _a in numeric_map:
534                    _answers.append(str(numeric_map[_a]))
535                else:
536                    _answers.append(_a)
537
538        _processed_answers = [altered_choices.get(a, a) for a in _answers]
539
540        valid_answers = []
541        for a in _processed_answers:
542            if a in _choices:
543                valid_answers.append(a)
544
545        if len(valid_answers) != len(_processed_answers):
546            if warn:
547                _warn("Please pick a valid choice.", stack=False)
548            continue
549        answers = valid_answers
550
551    def get_key(key_str):
552        try:
553            return int(key_str)
554        except (ValueError, TypeError):
555            return key_str
556
557    if not multiple:
558        answer = answers[0]
559        if not numeric:
560            return choices_values_indices.get(answer, answer) if as_indices else answer
561        
562        key = get_key(answer)
563        return key if as_indices else choices_indices[key]
564
565    if not numeric:
566        return [choices_values_indices.get(a, a) for a in answers] if as_indices else answers
567
568    final_answers = []
569    for a in answers:
570        key = get_key(a)
571        final_answers.append(key if as_indices else choices_indices[key])
572    return final_answers

Present a list of options and return the user's choice.

Parameters
  • question (str): The question to be printed.
  • choices (List[Union[str, Tuple[str, str]]): A list of options. If an option is a tuple of two strings, the first string is treated as the index and not displayed. In this case, set as_indices to True to return the index.
  • default (Union[str, List[str], None], default None): If the user declines to enter a choice, return this value.
  • numeric (bool, default True): If True, number the items in the list and ask for a number as input. If False, require the user to type the complete string.
  • multiple (bool, default False): If True, allow the user to choose multiple answers separated by delimiter.
  • as_indices (bool, default False): If True, return the indices for the choices. If a choice is a tuple of two strings, the first is assumed to be the index. Otherwise the index in the list is returned.
  • delimiter (str, default ','): If multiple, separate answers by this string. Raise a warning if this string is contained in any of the choices.
  • icon (bool, default True): If True, include the question icon.
  • warn (bool, default True): If True, raise warnings when invalid input is entered.
  • noask (bool, default False): If True, skip printing the question and return the default value.
Returns
  • A string for a single answer or a tuple of strings if multiple is True.
def get_password( username: str | None = None, minimum_length: int | None = None, confirm: bool = True, **kw: Any) -> str:
576def get_password(
577    username: Optional[str] = None,
578    minimum_length: Optional[int] = None,
579    confirm: bool = True,
580    **kw: Any
581) -> str:
582    """
583    Prompt the user for a password.
584
585    Parameters
586    ----------
587    username: Optional[str], default None
588        If provided, print the username when asking for a password.
589
590    minimum_length: Optional[int], default None
591        If provided, enforce a password of at least this length.
592
593    confirm: bool, default True
594        If `True`, prompt the user for a password twice.
595
596    Returns
597    -------
598    The password string (censored from terminal output when typing).
599
600    Examples
601    --------
602    ```python-repl
603    >>> get_password()
604     ❓ Password: *******
605     ❓ Confirm password: *******
606    'hunter2'
607    ```
608
609    """
610    from meerschaum.utils.warnings import warn
611    while True:
612        password = prompt(
613            "Password" + (f" for user '{username}':" if username is not None else ":"),
614            is_password=True,
615            **kw
616        )
617        if minimum_length is not None and len(password) < minimum_length:
618            warn(
619                "Password is too short. " +
620                f"Please enter a password that is at least {minimum_length} characters.",
621                stack=False
622            )
623            continue
624
625        if not confirm:
626            return password
627
628        _password = prompt(
629            "Confirm password" + (f" for user '{username}':" if username is not None else ":"),
630            is_password=True,
631            **kw
632        )
633        if password != _password:
634            warn("Passwords do not match! Please try again.", stack=False)
635            continue
636        else:
637            return password

Prompt the user for a password.

Parameters
  • username (Optional[str], default None): If provided, print the username when asking for a password.
  • minimum_length (Optional[int], default None): If provided, enforce a password of at least this length.
  • confirm (bool, default True): If True, prompt the user for a password twice.
Returns
  • The password string (censored from terminal output when typing).
Examples
>>> get_password()
 ❓ Password: *******
 ❓ Confirm password: *******
'hunter2'
def get_email(username: str | None = None, allow_omit: bool = True, **kw: Any) -> str:
640def get_email(username: Optional[str] = None, allow_omit: bool = True, **kw: Any) -> str:
641    """
642    Prompt the user for an email and enforce that it's valid.
643
644    Parameters
645    ----------
646    username: Optional[str], default None
647        If provided, print the username in the prompt.
648
649    allow_omit: bool, default True
650        If `True`, allow the user to omit the email.
651
652    Returns
653    -------
654    The provided email string.
655
656    Examples
657    --------
658    ```python-repl
659    >>> get_email()
660     ❓ Email (empty to omit): foo@foo
661     Invalid email! Please try again.
662     ❓ Email (empty to omit): foo@foo.com
663    'foo@foo.com'
664    ```
665    """
666    from meerschaum.utils.warnings import warn
667    from meerschaum.utils.misc import is_valid_email
668    while True:
669        email = prompt(
670            "Email" + (f" for user '{username}'" if username is not None else "") +
671            (" (empty to omit):" if allow_omit else ": "),
672            **kw
673        )
674        if (allow_omit and email == '') or is_valid_email(email):
675            return email
676        warn("Invalid email! Please try again.", stack=False)

Prompt the user for an email and enforce that it's valid.

Parameters
  • username (Optional[str], default None): If provided, print the username in the prompt.
  • allow_omit (bool, default True): If True, allow the user to omit the email.
Returns
  • The provided email string.
Examples
>>> get_email()
 ❓ Email (empty to omit): foo@foo
 Invalid email! Please try again.
 ❓ Email (empty to omit): foo@foo.com
'foo@foo.com'
def check_noask(noask: bool = False) -> bool:
679def check_noask(noask: bool = False) -> bool:
680    """
681    Flip `noask` to `True` if `MRSM_NOASK` is set.
682    """
683    from meerschaum._internal.static import STATIC_CONFIG
684    NOASK = STATIC_CONFIG['environment']['noask']
685    if noask:
686        return True
687
688    return (
689        os.environ.get(NOASK, 'false').lower()
690        in ('1', 'true')
691    )

Flip noask to True if MRSM_NOASK is set.

def get_connectors_completer(*types: str):
694def get_connectors_completer(*types: str):
695    """
696    Return a prompt-toolkit Completer object to pass into `prompt()`.
697    """
698    from meerschaum.utils.misc import get_connector_labels
699    prompt_toolkit_completion = mrsm.attempt_import('prompt_toolkit.completion', lazy=False)
700    Completer = prompt_toolkit_completion.Completer
701    Completion = prompt_toolkit_completion.Completion
702
703    class ConnectorCompleter(Completer):
704        def get_completions(self, document, complete_event):
705            for label in get_connector_labels(*types, search_term=document.text):
706                yield Completion(label, start_position=(-1 * len(document.text)))
707
708    return ConnectorCompleter()

Return a prompt-toolkit Completer object to pass into prompt().