Пример #1
0
 def get_filepath_validator(self):
     """Return a validator for a existing file path."""
     Validator.from_callable(
         self._is_valid_file_path,
         error_message="Please enter a valid file path.",
         move_cursor_to_end=True,
     )
Пример #2
0
    async def _prompt_time(self) -> datetime.datetime:
        """
        Prompt the client for a time within the week.
        """
        def parse_time(s: str) -> datetime.datetime:
            t = START_DATE.strptime(s, "%H:%M")
            return START_DATE.replace(hour=t.hour, minute=t.minute)

        def validate_time(s: str) -> bool:
            try:
                parse_time(s)
                return True
            except ValueError:
                return False

        validator = Validator.from_callable(
            validate_time, "expecting a time in HH:MM format")

        dt = parse_time(await self._session.prompt_async(
            HTML("<i><b>Time</b> of day (HH:MM)</i>? >>> "),
            validator=validator,
        ))
        dow = await self._prompt_dow(exclude=tuple())
        dt += datetime.timedelta(days=next(iter(dow)).value)

        return dt
Пример #3
0
    def set_due_date(card):
        '''prompt for the date to set this card due as'''
        def validate_date(text):
            return re.match(r'\d{2}\/\d{2}\/\d{4}', text) or re.match(
                r'[A-Z][a-z]{2} \d{2} \d{4}', text)

        validator = Validator.from_callable(
            validate_date,
            error_message=
            'Enter a date in format "Jun 15 2018", "06/15/2018" or "15/06/2018". Ctrl+C to go back',
            move_cursor_to_end=True,
        )
        while True:
            try:
                user_input = prompt('date > ',
                                    validator=validator,
                                    validate_while_typing=True)
            except KeyboardInterrupt:
                return
            result = parse_user_date_input(user_input)
            if result is None:
                print('Invalid date format!')
            else:
                break
        card.set_due(result)
        card.fetch()  # Needed to pick up the new due date
        print('Due date set')
        return result
Пример #4
0
def ask_for_progress() -> str:
    validator = Validator.from_callable(
        is_valid_progress,
        error_message=
        'Must be a whole number (no % sign), F for "Finished", or A for "Abandoned"',
        move_cursor_to_end=True,
    )

    progress = ask.prompt(
        "Progress: ",
        validator=validator,
        default="",
        rprompt=
        'Whole number (no % sign), F for "Finished", or A for "Abandoned"',
    )

    if progress:
        if progress == "F":
            return "Finished"

        if progress == "A":
            return "Abandoned"

        return "{0}%".format(progress)

    return ask_for_progress()
Пример #5
0
 def _reset(self):
     self._answered: bool = False
     self._buffer: Buffer = Buffer(
         validator=Validator.from_callable(self._validate),
         name=DEFAULT_BUFFER,
         accept_handler=self._submit,
     )
Пример #6
0
def __prompt_for_account(account_names):
    print("{}#--------------------------------------------------#".format(
        Colors.lblue))
    print("#     {}To which account would you like to login?{}    #".format(
        Colors.white, Colors.lblue))
    print("#          {}Start typing an account name or{}         #".format(
        Colors.white, Colors.lblue))
    print('#              {}"list" to list accounts{}             #'.format(
        Colors.white, Colors.lblue))
    print("#--------------------------------------------------#{}".format(
        Colors.normal))

    account_names.append("list")

    def is_valid(account):
        return account in account_names

    account_completer = FuzzyWordCompleter(account_names, WORD=True)
    validator = Validator.from_callable(is_valid,
                                        error_message="Not a valid account",
                                        move_cursor_to_end=True)
    while True:
        account = prompt(
            "Account: ",
            completer=account_completer,
            complete_while_typing=True,
            validator=validator,
        )
        if account == "list":
            for account_name in account_names:
                if account_name != "list":
                    print("\t{}{}{}".format(Colors.yellow, account_name,
                                            Colors.normal))
        else:
            return account
Пример #7
0
def chose_install_dir(json_file):
    validator = Validator.from_callable(
        lambda x: os.path.isdir(x) or x == '',
        error_message="Not a directory!",
        move_cursor_to_end=True,
    )
    path_completer = PathCompleter(only_directories=True)

    default_dir = json_file['install_dir'] or './'

    question = "\nPath to install datasets [empty to default " + \
        default_dir + "] "
    install_dir = prompt(question,
                         validator=validator,
                         completer=path_completer)
    if not install_dir:
        if not os.path.isdir(default_dir):
            os.mkdir(default_dir)
        install_dir = default_dir

    if install_dir.endswith('/'):
        install_dir = install_dir[:-1]

    json_file['install_dir'] = install_dir
    return install_dir
Пример #8
0
 def get_confirm_validator(self):
     """Return a validator for confirmation y or n."""
     return Validator.from_callable(
         self._is_valid_confirm,
         error_message="Please enter 'y' or 'n' to continue.",
         move_cursor_to_end=True,
     )
Пример #9
0
    def _make_integer_validator(self, allow_empty=False):
        """
        Create a validator for integer fields.

        This private method creates a validator for a field
        with ``data_type`` of "integers".

        Parameters
        ----------
        allow_empty : bool, optional
            If ``True``, it will allow the user to also just press
            enter (i.e., input a blank string)
            Defaults to ``False``.

        Returns
        -------
        validator : prompt_toolkit.validation.Validator
            A ``Validator`` instance that makes sure that the
            final user input is a string representation of a
            fixed-point number or integer. Blank strings may
            also be allowed if ``allow_empty`` is ``True``.
        """
        integer_regex = r'^[0-9]+$'
        if allow_empty:
            integer_regex += r'|^$'
        validator = Validator.from_callable(
            lambda answer: re.match(integer_regex, answer),
            error_message="invalid integer")
        return validator
Пример #10
0
 def get_path_validator(self):
     """Return a validator for a valid path."""
     return Validator.from_callable(
         self._is_valid_path,
         error_message="Please enter a valid path.",
         move_cursor_to_end=True,
     )
Пример #11
0
def play(rows_to_win: int, starting_rows: int, columns: int) -> None:
    """Play the game.

    Args:
        columns: The number of columns in the grid. Increasing this makes the game more difficult.
        starting_rows: The number of rows in the grid when the game starts. Increasing this makes the game more
            difficult.
        rows_to_win: The total number of rows that must be in the grid to win the game. Increasing this makes the game
            more difficult.
    """
    char_grid = create_grid(starting_rows, columns)
    usernames = random.sample(USERNAMES, rows_to_win)
    pad_width = len(max(usernames, key=len))

    # Format and print the initial grid.
    starting_grid = "\n".join(
        format_line(usernames.pop(), pad_width, line)
        for line in char_grid.format().splitlines())
    print(starting_grid)

    # Create the prompt session.
    validator = Validator.from_callable(char_grid.check_row,
                                        error_message="Invalid row",
                                        move_cursor_to_end=True)
    session = PromptSession(validator=validator,
                            validate_while_typing=False,
                            mouse_support=True,
                            style=GUI_STYLE)

    # Prompt the user until they complete enough lines.
    while len(char_grid.rows) < rows_to_win:
        session.prompt(format_line(usernames.pop(), pad_width, ""))

    print_correct_message()
Пример #12
0
    def set_due_date(self):
        def validate_date(text):
            return re.match(r'\d{2}\/\d{2}\/\d{4}', text) or re.match(
                r'[A-Z][a-z]{2} \d{2} \d{4}', text)

        validator = Validator.from_callable(
            validate_date,
            error_message=
            'Enter a date in format "Jun 15 2018", "06/15/2018" or "15/06/2018". Ctrl+D to go back',
            move_cursor_to_end=True,
        )
        while True:
            user_input = prompt('gtd.py > duedate > ',
                                validator=validator,
                                validate_while_typing=True)
            result = parse_user_date_input(user_input)
            if result is None:
                print('Invalid date format!')
            else:
                break
        # Set the due daet
        self.connection.trello.fetch_json(
            '/cards/' + self.id + '/due',
            http_method='PUT',
            post_args={'value': result.isoformat()})
        # Pick it up
        self.fetch()
        print('Due date set')
        return result
Пример #13
0
    def _make_boolean_validator(self, allow_empty=False):
        """
        Create a validator for boolean fields.

        This private method creates a validator for a field with
        ``data_type`` of "boolean".

        Parameters
        ----------
        allow_empty : bool, optional
            If ``True``, it will allow the user to also just press
            enter (i.e., input a blank string), in addition to "true"
            or "false".
            Defaults to ``False``.

        Returns
        -------
        validator : prompt_toolkit.validation.Validator
            A ``Validator`` instance that ensures that the user
            input for the field is "true" / "false", or possibly
            the empty string, if ``allow_empty`` is ``True``.
        """
        correct_choices = ["true", "false"]
        if allow_empty:
            correct_choices.append("")
        validator = Validator.from_callable(
            lambda answer: answer in correct_choices,
            error_message="invalid answer")
        return validator
Пример #14
0
 def set_validator(s):
     options_str = ', '.join(sorted(list(s)))
     return Validator.from_callable(
         lambda i: i in s,
         error_message=
         "Sorry, that's not a valid option.  Try one of these: " +
         options_str + ".  Tab complete may help!",
         move_cursor_to_end=True)
Пример #15
0
 def number_validator(lbound=None, ubound=None):
     return Validator.from_callable(
         lambda s: s == "" or
         (is_number(s) and in_bounds(s, lbound, ubound)),
         error_message='This input may only contain numeric characters' +
         ('' if lbound is None else ' and it must be >= %d' % lbound) +
         ('' if ubound is None else ' and it must be < %d' % ubound),
         move_cursor_to_end=True)
Пример #16
0
def get_list_prompt(lists, error_message='the input is not in list'):
    completer = WordCompleter(lists)
    validator = Validator.from_callable(
        lambda x: x in lists,
        error_message='This verb is not in this book. ',
        move_cursor_to_end=True)

    return completer, validator
Пример #17
0
 def existing_config(self):
     path_exist_validator = Validator.from_callable(os.path.exists,
                                                    error_message='Path does not exist, choose existing path',
                                                    move_cursor_to_end=True)
     config_directory = prompt('%s: ' % 'Existing config directory name',
                               completer=PathCompleter(only_directories=True, expanduser=True),
                               validator=path_exist_validator)
     return self.read_existing_config(config_directory)
Пример #18
0
 def get_type_validator(self):
     """Return a validator for a valid type."""
     return Validator.from_callable(
         self._is_valid_class_name,
         error_message="Please only enter a number [0-%s]. " %
         (len(self._valid_types) - 1),
         move_cursor_to_end=True,
     )
Пример #19
0
 def get_class_name_validator(self):
     """Return a validator for a valid identifier."""
     return Validator.from_callable(
         self._is_valid_class_name,
         error_message=
         "Please enter a valid name (only contain digits and letters).",
         move_cursor_to_end=True,
     )
Пример #20
0
def test_validator_instance():
    def validate(t):
        return len(t) == 3

    validator = Validator.from_callable(validate)

    validator = build_validator(validator)
    assert validator.validate(Document("foo")) is None  # should not raise
Пример #21
0
def test_validator_instance_fails():
    def validate(t):
        return len(t) == 3

    validator = Validator.from_callable(validate, error_message="invalid input")
    with pytest.raises(ValidationError) as e:
        validator.validate(Document("fooooo"))

    assert e.value.message == "invalid input"
Пример #22
0
 async def _prompt_facility(self) -> str:
     """
     Prompt the client for a facility name.
     """
     return await self._session.prompt_async(
         HTML("<i>Facility <b>name</b></i>? >>> "),
         validator=Validator.from_callable(lambda v: True),
         completer=WordCompleter(list(self._known_facilities)),
     )
Пример #23
0
 def ask(self):
     self.answer = questionary.text(
         "Please provide the name for instance profile",
         validate=Validator.from_callable(
             lambda x: 0 < len(x) < 64,
             error_message=
             "Instance profile name shouldn't be empty or longer than 64 chars"
         ),
         style=custom_style).ask()
     return self.answer
Пример #24
0
def file_validation():
    files = []
    for f in os.listdir('./'):
        file_name, file_extension = os.path.splitext(f)
        if file_extension in {'.csv', '.CSV'}:
            files.append(f)
    is_valid = lambda text: text in files
    return Validator.from_callable(
        is_valid,
        error_message=
        'Please enter the name of a CSV file in the working directory.')
Пример #25
0
    def validator(self):
        """
        """
        def service_is_valid(service):
            return service.title() in self.available_services

        error_message = f"Service must be one of: {self.available_services}"
        validator = Validator.from_callable(service_is_valid,
                                            error_message=error_message,
                                            move_cursor_to_end=True)
        return validator
Пример #26
0
def input(
        title, 
        default="", 
        bottom_toolbar=None, 
        multiline=False,
        validator_function=None, 
        default_message=""
    ):
    """Prompt user for input

    :param title: Title of the pager
    :type  title: str

    :param default: Default value to give if the user does not input anything
    :type  default: str

    :param validator_function: User's input has to fulfill validator functions
    :type  validator_function: function

    :param default_message: Default message to prompt
    :type  default_message: str

    :return: User input or default
    :rtype :  bool

    """
    import prompt_toolkit
    from prompt_toolkit.validation import Validator

    validator = None
    if validator_function is not None:
        validator = Validator.from_callable(
            validator_function,
            error_message=default_message,
            move_cursor_to_end=True
        )    
    
    fragments = title
    if isinstance(title, str):
        fragments = [
            ('', title),
            ('fg:red', ' ({0})'.format(default)),
            ('', ': '),
        ]

    result = prompt_toolkit.prompt(
        fragments,
        validator=validator,
        multiline=multiline,
        bottom_toolbar=bottom_toolbar,
        validate_while_typing=True
    )

    return result if result else default
Пример #27
0
Файл: ui.py Проект: czinn/ebb
def prompt_options(message, options, strict=False, history=None):
    completer = FuzzyWordCompleter(options, WORD=True)
    if strict:
        validator = Validator.from_callable(lambda s: s in options,
                                            error_message='',
                                            move_cursor_to_end=False)
        return p(message + ' ',
                 completer=completer,
                 vi_mode=True,
                 validator=validator,
                 history=history)
    return prompt(message, completer=completer, history=history)
Пример #28
0
def main():
    args = get_args()
    session = PromptSession(
        history=FileHistory('/tmp/sctp-injector-inter.history'))
    SCRIPT_PATH = os.path.abspath(os.path.dirname(__file__))
    script_file = session.prompt(
        'Choose a Python sub-script to run inside > ',
        completer=PathCompleter(),
        validator=Validator.from_callable(
            lambda p: os.path.exists(p) and p.endswith(".py")),
        complete_while_typing=True)
    print('You said: %s' % script_file)
Пример #29
0
 def __get_commond_attr(self):
     msg = self.answer['msg']
     default = '' if not "default" in self.answer else self.answer["default"]
     validator_dict = None if not "validator" in self.answer else self.answer[
         "validator"]
     validator = None
     if validator_dict:
         validator = Validator.from_callable(
             validator_dict['callback'],
             error_message=validator_dict['error_msg'],
             move_cursor_to_end=True)
     return msg, default, validator
Пример #30
0
def qa_input(movie: Dict[str, Any]) -> str:
    print('Title: {[title]} dir. '.format(movie), end='')
    for name in movie['directors'][:-1]:
        print(f'{name}, ')
    print(movie['directors'][-1]['name'])

    return session.prompt(
        'Release Year> ',
        validator=Validator.from_callable(
            lambda x: x.isdigit(),
            error_message='Not a valid year',
            move_cursor_to_end=True
        ))
#!/usr/bin/env python
"""
Simple example of input validation.
"""
from prompt_toolkit import prompt
from prompt_toolkit.validation import Validator


def is_valid_email(text):
    return '@' in text


validator = Validator.from_callable(
    is_valid_email,
    error_message='Not a valid e-mail address (Does not contain an @).',
    move_cursor_to_end=True)


def main():
    # Validate when pressing ENTER.
    text = prompt('Enter e-mail address: ', validator=validator,
                  validate_while_typing=False)
    print('You said: %s' % text)

    # While typing
    text = prompt('Enter e-mail address: ', validator=validator,
                  validate_while_typing=True)
    print('You said: %s' % text)


if __name__ == '__main__':