Ejemplo n.º 1
0
def new(*args, **kwargs):
    project_name = kwargs["project_name"]

    description = click.prompt("description")
    author_name = click.prompt("author_name")
    author_email = click.prompt("author_email")

    license_completer = FuzzyWordCompleter(licenses)
    license = prompt(
        "Select license: ",
        completer=license_completer,
        complete_while_typing=True,
    )

    classifier_completer = FuzzyWordCompleter(classifiers)
    classifier = prompt(
        "Select classifier: ",
        completer=classifier_completer,
        complete_while_typing=True,
    )

    metadata = {
        "name": project_name,
        "description": description,
        "author_name": author_name,
        "author_email": author_email,
        "license": license,
        "classifiers": classifier,
    }

    print()
    pprint(metadata)
Ejemplo n.º 2
0
 def completion(self, document, complete_event=None):
     # complete_event is None when this method is called by complete_input()
     if complete_event == None and len(document.text) == 0:
         return
     t = document.text.split()
     if len(t) == 0 or (len(t) == 1 and document.text[-1] != ' '):
         # command completion
         if self.fuzzy_completion and complete_event:
             c = FuzzyWordCompleter(self.commands())
             for v in c.get_completions(document, complete_event):
                 yield v
         else:
             for cmd in self.commands():
                 if cmd.startswith(document.text):
                     yield Completion(cmd,
                                      start_position=-len(document.text))
     else:
         # argument completion
         # complete command(t[0]) first
         try:
             cmd = self.complete_input([t[0]])[0]
         except InvalidInput:
             return
         v = self._commands.get(cmd)
         if not v:
             return
         c = v['completer']
         if c:
             # do argument completion with text after the command (t[0])
             new_document = Document(document.text[len(t[0]):].lstrip())
             for v in c.get_completions(new_document, complete_event):
                 yield v
    def __init__(self,
                 words: Union[List[str], Callable[[], List[str]]],
                 meta_dict: Optional[Dict[str, str]] = None,
                 WORD: bool = False) -> None:

        self.words = words
        self.meta_dict = meta_dict or {}
        self.WORD = WORD

        self.fuzzy_word_completer = FuzzyWordCompleter(words=self.words,
                                                       WORD=self.WORD)
Ejemplo n.º 4
0
def test_fuzzy_completer():
    collection = [
        "migrations.py",
        "django_migrations.py",
        "django_admin_log.py",
        "api_user.doc",
        "user_group.doc",
        "users.txt",
        "accounts.txt",
        "123.py",
        "test123test.py",
    ]
    completer = FuzzyWordCompleter(collection)
    completions = completer.get_completions(Document("txt"), CompleteEvent())
    assert [c.text for c in completions] == ["users.txt", "accounts.txt"]

    completions = completer.get_completions(Document("djmi"), CompleteEvent())
    assert [c.text for c in completions] == [
        "django_migrations.py",
        "django_admin_log.py",
    ]

    completions = completer.get_completions(Document("mi"), CompleteEvent())
    assert [c.text for c in completions] == [
        "migrations.py",
        "django_migrations.py",
        "django_admin_log.py",
    ]

    completions = completer.get_completions(Document("user"), CompleteEvent())
    assert [c.text for c in completions] == [
        "user_group.doc",
        "users.txt",
        "api_user.doc",
    ]

    completions = completer.get_completions(Document("123"), CompleteEvent())
    assert [c.text for c in completions] == ["123.py", "test123test.py"]

    completions = completer.get_completions(Document("miGr"), CompleteEvent())
    assert [c.text for c in completions] == [
        "migrations.py",
        "django_migrations.py",
    ]

    # Multiple words ending with space. (Accept all options)
    completions = completer.get_completions(Document("test "), CompleteEvent())
    assert [c.text for c in completions] == collection

    # Multiple words. (Check last only.)
    completions = completer.get_completions(Document("test txt"),
                                            CompleteEvent())
    assert [c.text for c in completions] == ["users.txt", "accounts.txt"]
Ejemplo n.º 5
0
def test_fuzzy_completer():
    collection = [
        'migrations.py', 'django_migrations.py', 'django_admin_log.py',
        'api_user.doc', 'user_group.doc', 'users.txt', 'accounts.txt',
        '123.py', 'test123test.py'
    ]
    completer = FuzzyWordCompleter(collection)
    completions = completer.get_completions(Document('txt'), CompleteEvent())
    assert [c.text for c in completions] == ['users.txt', 'accounts.txt']

    completions = completer.get_completions(Document('djmi'), CompleteEvent())
    assert [c.text for c in completions
            ] == ['django_migrations.py', 'django_admin_log.py']

    completions = completer.get_completions(Document('mi'), CompleteEvent())
    assert [c.text for c in completions] == [
        'migrations.py', 'django_migrations.py', 'django_admin_log.py'
    ]

    completions = completer.get_completions(Document('user'), CompleteEvent())
    assert [c.text for c in completions
            ] == ['user_group.doc', 'users.txt', 'api_user.doc']

    completions = completer.get_completions(Document('123'), CompleteEvent())
    assert [c.text for c in completions] == ['123.py', 'test123test.py']

    completions = completer.get_completions(Document('miGr'), CompleteEvent())
    assert [c.text for c in completions] == [
        'migrations.py',
        'django_migrations.py',
    ]
def edit_values(result) -> Tuple[str, str, str]:
    title = ""
    while title == "":
        if result["main_title"] == result["ext_title"]:
            default = result["main_title"]
        else:
            default = ""
        title = questionary.text(
            "Title:",
            default=default,
            completer=FuzzyWordCompleter([result["main_title"], result["ext_title"]]),
        ).ask()
        if title is None:
            raise AbortCommand
        title = title.strip()

    artist = ""
    while artist == "":
        if result["main_artist"] == result["ext_artist"]:
            default = result["main_artist"]
        else:
            default = ""
        artist = questionary.text(
            "Artist:",
            default=default,
            completer=FuzzyWordCompleter([result["main_artist"], result["ext_artist"]]),
        ).ask()
        if artist is None:
            raise AbortCommand
        artist = artist.strip()

    while True:
        if result["main_album"] == result["ext_album"]:
            default = result["main_album"]
        else:
            default = ""
        album = questionary.text(
            "Album:",
            default=default,
            completer=FuzzyWordCompleter([result["main_album"], result["ext_album"]]),
        ).ask()
        if album is None:
            raise AbortCommand
        album = album.strip()
        if album != "":
            break
        if questionary.confirm("Are you sure?", auto_enter=False).ask():
            break

    return title, artist, album
Ejemplo n.º 7
0
 def move_between_boards(self, card: Card) -> None:
     boards_by_name = self.connection.boards_by_name()
     board_name = prompt('gtd.py > move > board name? ',
                         completer=FuzzyWordCompleter(
                             boards_by_name.keys()))
     board_id = boards_by_name[board_name]['id']
     lists_json = self.connection.trello.fetch_json(
         f'/boards/{board_id}/lists?cards=none&filter=open&fields=name')
     name_to_listid = {l['name']: l['id'] for l in lists_json}
     list_name = prompt(
         f'gtd.py > move > {board_name} > list name? ',
         completer=FuzzyWordCompleter(name_to_listid.keys()),
     )
     card.change_board(board_id, list_id=name_to_listid[list_name])
     click.secho(f'Changed list to {list_name} on {board_name}', fg='green')
Ejemplo n.º 8
0
def manual_input(expense):
    mapping = LabelMapping.create_from_local_copy()
    tags_completer = FuzzyWordCompleter(mapping.tags)
    category_completer = FuzzyWordCompleter(mapping.categories)
    if category := prompt("Enter category: ",
                          completer=category_completer,
                          search_ignore_case=True):
        if tag := prompt("Enter tag: ",
                         completer=tags_completer,
                         search_ignore_case=True):
            logger.info('Updating manual choice')
            update_entry_async(expense['id'],
                               category=category,
                               tag=tag,
                               desc=expense['desc'] + ' 🏷')
Ejemplo n.º 9
0
def course_selection_prompt():
    # COURSE LIST URLs
    # https://www.khanacademy.org/math/
    # https://www.khanacademy.org/science/
    # https://www.khanacademy.org/computing
    # https://www.khanacademy.org/humanities
    # https://www.khanacademy.org/economics-finance-domain

    # Choose a Course Domain
    course_domain_completer = FuzzyWordCompleter([
        "Math", "Science", "Computing", "Humanities",
        "Economics-Finance-Domain"
    ])
    selected_course_domain = prompt("Course Domain: ",
                                    completer=course_domain_completer)
    print("Selected Course Domain: %s" % selected_course_domain)

    # Get a list of all the courses in the domain
    course_list = []
    course_url_list = []
    course_list_page_url = ("https://www.khanacademy.org/" +
                            selected_course_domain.lower())

    print("\nDownloading Course List...\n")
    # Download Selected Course Domain Page HTML
    course_list_page_source = requests.get(course_list_page_url).text
    course_list_page_html = BeautifulSoup(course_list_page_source, "lxml")

    for courses_header_section in course_list_page_html.find_all(
            "h2", class_="_158q6at"):
        course_header_tag = courses_header_section.find("a", class_="_dwmetq")

        course_header = courses_header_section.find("a", class_="_dwmetq").text
        course_header_slug = course_header_tag["href"]

        course_url_list.append("https://www.khanacademy.org" +
                               course_header_slug)
        course_list.append(course_header)

    # Choose a Course
    course_list_completer = FuzzyWordCompleter(course_list)
    selected_course = prompt("Course: ", completer=course_list_completer)
    print("\nSelected Course Domain: %s\n" % selected_course)

    # Find the selected course index and match the Course URL
    selected_course_index = course_list.index(selected_course)
    selected_course_url = course_url_list[selected_course_index]
    return selected_course_url
Ejemplo n.º 10
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
Ejemplo n.º 11
0
def allocate_datafile_prompt(context):
    # Todo consider getting datafile at runtime to allow
    # For one configuration to apply to multiple data files
    datafile = data_filepath_prompt(context)
    output_dir = output_dir_prompt(context)

    # TODO test documents for mappings

    column = False
    header = context['datafile'].header

    while not column:
        print("Column choices are: " + ', '.join(header) + "\n")
        column_completer = FuzzyWordCompleter(header)
        column = prompt("Enter a Column to filter on: ",
                        completer=column_completer)
        if column in header:
            break
        column = False
        print("Invalid entry, try again (must choose an item from the list).")

    writer = csv.writer
    nobody = allocate(datafile, context['documents'], column)
    nobody.save_buffer(output_dir, writer)
    # TODO iterate on documents, not documents.values
    [
        doc.save_buffer(output_dir, writer, header)
        for doc in context['documents'].values()
    ]

    print("Done.  Files saved to {}".format(output_dir))
Ejemplo n.º 12
0
    def add_labels(self, label_choices):
        '''Give the user a way to toggle labels on this card by their
        name rather than by a numeric selection interface. Using
        prompt_toolkit, we have automatic completion which makes
        things substantially faster without having to do a visual
        lookup against numeric IDs

        Options:
            label_choices: str->trello.Label, the names and objects of labels on this board
        '''
        print('Enter a tag name to toggle it, <TAB> completes. Ctrl+D to exit')
        while True:
            label_completer = FuzzyWordCompleter(label_choices.keys())
            userinput = prompt('gtd.py > tag > ',
                               completer=label_completer).strip()
            if userinput not in label_choices.keys():
                if prompt_for_confirmation(
                        f'Unrecognized tag name {userinput}, would you like to create it?',
                        False):
                    label = self.connection.main_board().add_label(
                        userinput, 'green')
                    self.add_label(label.id)
                    click.echo(
                        f'Added tag {label.name} to board {self.connection.main_board().name} and to the card {self}'
                    )
                    label_choices[userinput] = label
            else:
                label_obj = label_choices[userinput]
                try:
                    self.add_label(label_obj.id)
                    click.secho(f'Added tag {userinput}', fg='green')
                except trello.exceptions.ResourceUnavailable:
                    # This label already exists on the card so remove it
                    self.remove_label(label_obj.id)
                    click.secho(f'Removed tag {userinput}', fg='red')
Ejemplo n.º 13
0
    def __init__(self, commands):
        Thread.__init__(self)
        self.setName("BazookaPrompt")

        self.commands = commands
        completer = FuzzyWordCompleter(self.commands.keys())
        self.session = PromptSession(completer=completer)
def test_fuzzy_completer():
    collection = [
            'migrations.py',
            'django_migrations.py',
            'django_admin_log.py',
            'api_user.doc',
            'user_group.doc',
            'users.txt',
            'accounts.txt',
            '123.py',
            'test123test.py'
            ]
    completer = FuzzyWordCompleter(collection)
    completions = completer.get_completions(Document('txt'), CompleteEvent())
    assert [c.text for c in completions] == ['users.txt', 'accounts.txt']

    completions = completer.get_completions(Document('djmi'), CompleteEvent())
    assert [c.text for c in completions] == ['django_migrations.py', 'django_admin_log.py']

    completions = completer.get_completions(Document('mi'), CompleteEvent())
    assert [c.text for c in completions] == ['migrations.py', 'django_migrations.py', 'django_admin_log.py']

    completions = completer.get_completions(Document('user'), CompleteEvent())
    assert [c.text for c in completions] == ['user_group.doc', 'users.txt', 'api_user.doc']

    completions = completer.get_completions(Document('123'), CompleteEvent())
    assert [c.text for c in completions] == ['123.py', 'test123test.py']

    completions = completer.get_completions(Document('miGr'), CompleteEvent())
    assert [c.text for c in completions] == ['migrations.py', 'django_migrations.py',]
Ejemplo n.º 15
0
def default_input(prompt, default, options=[], ignore_case=False, retry=False):
    if options:
        completer = FuzzyWordCompleter(options)
        return prompt_toolkit.prompt(prompt,
                                     default=default,
                                     completer=completer,
                                     complete_while_typing=True,
                                     validator=YNValidator(options))
    return prompt_toolkit.prompt(prompt, default=default)
Ejemplo n.º 16
0
 def add_labels(card, label_choices=None):
     '''Give the user a way to toggle labels on this card by their
     name rather than by a numeric selection interface. Using
     prompt_toolkit, we have automatic completion which makes
     things substantially faster without having to do a visual
     lookup against numeric IDs
     :param trello.Card card: the card to modify
     :param dict label_choices: str->trello.Label, the names and objects of labels on this board
     '''
     print(
         'Enter a tag name to toggle it, <TAB> completes. Give "ls" to list tags, Enter to exit'
     )
     label_choices = label_choices or BoardTool.label_lookup(card.board)
     label_completer = FuzzyWordCompleter(label_choices.keys())
     while True:
         userinput = prompt('tag > ', completer=label_completer).strip()
         if userinput == '':
             break
         elif userinput == 'ls':
             triple_column_print(label_choices.keys())
         elif userinput not in label_choices.keys():
             if prompt_for_confirmation(
                     'Unrecognized tag name {0}, would you like to create it?'
                     .format(userinput), False):
                 label = card.board.add_label(userinput, 'black')
                 card.add_label(label)
                 click.echo(
                     'Successfully added tag {0} to board {1} and card {2}!'
                     .format(label.name, card.board.name, card.name))
                 label_choices = BoardTool.label_lookup(card.board)
                 label_completer = FuzzyWordCompleter(label_choices.keys())
         else:
             label_obj = label_choices[userinput]
             try:
                 card.add_label(label_obj)
                 print('Added tag {0}'.format(Colors.green + userinput +
                                              Colors.reset))
             except trello.exceptions.ResourceUnavailable:
                 # This label already exists on the card so remove it
                 card.remove_label(label_obj)
                 print('Removed tag {0}'.format(Colors.red + userinput +
                                                Colors.reset))
Ejemplo n.º 17
0
def select_document_prompt(docs):
    while True:
        print("Documents to choose from: ")
        [print(doc) for doc in docs]
        document_completer = FuzzyWordCompleter(docs)
        selected_document = prompt("Select Document: ",
                                   completer=document_completer)
        if selected_document in docs:
            return selected_document
        else:
            print("Invalid choice, try again.")
 def get_completions(self, document: Document,
                     complete_event: CompleteEvent) -> Iterable[Completion]:
     pattern = re.compile(r"^\w*$")
     if not pattern.match(document.text.strip()):
         return []
     words = [
         x.replace(self.path, "")
         for x in glob.glob(self.path + document.text.strip() + self.glob)
     ]
     return FuzzyWordCompleter(words=words, WORD=self.WORD).get_completions(
         document, complete_event)
Ejemplo n.º 19
0
Archivo: ui.py Proyecto: 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)
Ejemplo n.º 20
0
def select_msm(client: InfluxDBClient):
    rs: ResultSet = client.query('SHOW measurements')
    msms = resp_list(list(rs.get_points()))
    found_print('measurements', msms)

    comp = FuzzyWordCompleter(msms)
    msm = prompt(HTML(
        'And what <ansicyan>measurement</ansicyan> contains crap (you can only choose one)?\n'
    ),
                 completer=comp,
                 complete_while_typing=True)
    return msm
Ejemplo n.º 21
0
def test_fuzzy_completer():
    collection = [
        'migrations.py', 'django_migrations.py', 'django_admin_log.py',
        'api_user.doc', 'user_group.doc', 'users.txt', 'accounts.txt',
        '123.py', 'test123test.py'
    ]
    completer = FuzzyWordCompleter(collection)
    completions = completer.get_completions(Document('txt'), CompleteEvent())
    assert [c.text for c in completions] == ['users.txt', 'accounts.txt']

    completions = completer.get_completions(Document('djmi'), CompleteEvent())
    assert [c.text for c in completions
            ] == ['django_migrations.py', 'django_admin_log.py']

    completions = completer.get_completions(Document('mi'), CompleteEvent())
    assert [c.text for c in completions] == [
        'migrations.py', 'django_migrations.py', 'django_admin_log.py'
    ]

    completions = completer.get_completions(Document('user'), CompleteEvent())
    assert [c.text for c in completions
            ] == ['user_group.doc', 'users.txt', 'api_user.doc']

    completions = completer.get_completions(Document('123'), CompleteEvent())
    assert [c.text for c in completions] == ['123.py', 'test123test.py']

    completions = completer.get_completions(Document('miGr'), CompleteEvent())
    assert [c.text for c in completions] == [
        'migrations.py',
        'django_migrations.py',
    ]

    # Multiple words ending with space. (Accept all options)
    completions = completer.get_completions(Document('test '), CompleteEvent())
    assert [c.text for c in completions] == collection

    # Multiple words. (Check last only.)
    completions = completer.get_completions(Document('test txt'),
                                            CompleteEvent())
    assert [c.text for c in completions] == ['users.txt', 'accounts.txt']
Ejemplo n.º 22
0
def find_project_by_name(config):
    """
    Implements search prompt to find project by name entered
    by user. Uses fuzzy logic to match search with project names.

    Parameters
    ----------
    config : dict
        Contains settings.

    Returns
    -------
    str
        Path to project selected by user based on his search.
    """
    def get_possible_project_directories(config):
        possible_directories = []
        for projects_path in config['default_projects_paths']:
            for root, dirs, files in os.walk(projects_path):
                # modifying dirs directly to prune search tree
                dirs[:] = filter_directories(dirs, config)
                possible_directories.append(root)
        return possible_directories

    possible_directories = get_possible_project_directories(config)
    parts = [os.path.split(d) for d in possible_directories]
    projects_paths_dict = {project: path for path, project in parts}

    completer = FuzzyWordCompleter(projects_paths_dict.keys(),
                                   meta_dict=projects_paths_dict)
    validator = Validator.from_callable(
        lambda text: ' ' not in text,
        error_message=('Spaces in project name? Really?'),
    )
    message = [('class:brackets', '['), ('class:question_mark', '?'),
               ('class:brackets', ']'), ('', ' Select project by name: ')]
    try:
        project = prompt(message,
                         completer=completer,
                         validator=validator,
                         validate_while_typing=True,
                         style=CustomTheme.get_prompt_style(),
                         color_depth=ColorDepth.ANSI_COLORS_ONLY)
    except KeyboardInterrupt:
        print('\nCancelled by user\n')
        exit(0)

    return os.path.join(projects_paths_dict[project], project)
Ejemplo n.º 23
0
def get_condition_session(client: InfluxDBClient, msm: str):
    # TODO mode for mutli measurements
    rs: ResultSet = client.query(f'SHOW TAG KEYS FROM {msm}')
    tags = resp_list(list(rs.get_points()), 'tagKey')
    found_print('tags', tags)
    rs: ResultSet = client.query(f'SHOW FIELD KEYS FROM {msm}')
    fields = resp_list(list(rs.get_points()), 'fieldKey')
    found_print('fields', fields)

    comp = FuzzyWordCompleter(['time'] + tags + fields)
    session = PromptSession(HTML(
        'Please choose a <ansicyan>condition WHERE</ansicyan> it is wrong:\n'),
                            completer=comp,
                            complete_while_typing=True,
                            auto_suggest=AutoSuggestFromHistory())
    return session
Ejemplo n.º 24
0
def select_db(client: InfluxDBClient):
    databases = resp_list(client.get_list_database())
    found_print('databases', databases)

    comp = FuzzyWordCompleter(databases)
    db = prompt(HTML(
        'Which <ansicyan>database</ansicyan> do you want to work on today?\n'),
                completer=comp,
                complete_while_typing=True)
    if (db not in databases):
        color_print(f'DB "{db}" does not exist, try to remember! (or hit TAB)',
                    'ansired')
        return False

    client.switch_database(db)
    return True
Ejemplo n.º 25
0
    def input_option(self, history_path, default="") -> str:
        options = [option.value for option in list(AWSLogsOption)]
        completer = FuzzyWordCompleter(options, WORD=True)

        history = FileHistory(history_path)
        session = PromptSession(history=history)

        default = self.find_default_from_history(default, history)
        option_str = session.prompt(
            "Option : ",
            completer=completer,
            complete_while_typing=True,
            default=default,
        )

        return option_str
Ejemplo n.º 26
0
    def input_group(self, groups, history_path) -> str:
        completer = FuzzyWordCompleter(groups, WORD=True)
        history = FileHistory(history_path)
        session = PromptSession(history=history)
        default = self.find_recent_history(history)

        group_name = session.prompt(
            "Group  : ",
            completer=completer,
            complete_while_typing=True,
            default=default,
        )

        if group_name not in groups:
            return ""

        return group_name
def test_fuzzy_completer():
    collection = [
            'migrations.py',
            'django_migrations.py',
            'django_admin_log.py',
            'api_user.doc',
            'user_group.doc',
            'users.txt',
            'accounts.txt',
            '123.py',
            'test123test.py'
            ]
    completer = FuzzyWordCompleter(collection)
    completions = completer.get_completions(Document('txt'), CompleteEvent())
    assert [c.text for c in completions] == ['users.txt', 'accounts.txt']

    completions = completer.get_completions(Document('djmi'), CompleteEvent())
    assert [c.text for c in completions] == ['django_migrations.py', 'django_admin_log.py']

    completions = completer.get_completions(Document('mi'), CompleteEvent())
    assert [c.text for c in completions] == ['migrations.py', 'django_migrations.py', 'django_admin_log.py']

    completions = completer.get_completions(Document('user'), CompleteEvent())
    assert [c.text for c in completions] == ['user_group.doc', 'users.txt', 'api_user.doc']

    completions = completer.get_completions(Document('123'), CompleteEvent())
    assert [c.text for c in completions] == ['123.py', 'test123test.py']

    completions = completer.get_completions(Document('miGr'), CompleteEvent())
    assert [c.text for c in completions] == ['migrations.py', 'django_migrations.py',]

    # Multiple words ending with space. (Accept all options)
    completions = completer.get_completions(Document('test '), CompleteEvent())
    assert [c.text for c in completions] == collection

    # Multiple words. (Check last only.)
    completions = completer.get_completions(Document('test txt'), CompleteEvent())
    assert [c.text for c in completions] == ['users.txt', 'accounts.txt']
Ejemplo n.º 28
0
def prompt_enum(
    enum_cls: Type[Enum],
    for_attr: Optional[str] = None,
    prompt_msg: Optional[str] = None,
    dialog_title: str = "===",
) -> Enum:
    m: str = create_prompt_string(str, for_attr, prompt_msg)
    enum_mapping: Dict[str, Enum] = enum_attribute_dict(enum_cls)

    enum_desc_map = _create_enum_word_targets(enum_mapping)

    class EnumClosureValidator(Validator):
        def __init__(self):
            self.text = ""

        def validate(self, document: Document) -> None:
            # hmm; don't strip here since spaces might be part of the enum?
            self.text = document.text
            if self.text in enum_desc_map:
                return
            raise ValidationError(
                message=f"{self.text} is not part of the {enum_cls} enum")

        def toolbar(self):
            if self.text in enum_desc_map:
                return str(enum_desc_map[self.text])
            else:
                return "..."

    validator = EnumClosureValidator()

    # prompt using a repl prompt with autocompletion/validation
    resp = prompt(
        m,
        completer=FuzzyWordCompleter(words=list(enum_desc_map)),
        validator=validator,
        bottom_toolbar=validator.toolbar,
    )

    # use what the user typed
    if resp in enum_desc_map:
        return enum_desc_map[resp]

    # else lowercase
    return enum_desc_map[resp.casefold()]
Ejemplo n.º 29
0
def _runConfigurationWizard(setups, defaultSetup):
    """The implementation of the configuration wizard"""
    from prompt_toolkit import prompt, print_formatted_text, HTML
    from prompt_toolkit.completion import FuzzyWordCompleter

    # It makes no sense to have suggestions if there is no default so adjust the message accordingly
    msg = ""
    if setups:
        msg = "press tab for suggestions"
        if defaultSetup:
            msg = "default</b> <green>%s</green><b>, %s" % (defaultSetup, msg)
        msg = " (%s)" % msg
    # Get the Setup
    setup = prompt(
        HTML("<b>Choose a DIRAC Setup%s:</b>\n" % msg),
        completer=FuzzyWordCompleter(list(setups)),
    )
    if defaultSetup and not setup:
        setup = defaultSetup
    if setup not in setups:
        print_formatted_text(
            HTML("Unknown setup <yellow>%s</yellow> chosen" % setup))
        confirm = prompt(HTML("<b>Are you sure you want to continue?</b> "),
                         default="n")
        if confirm.lower() not in ["y", "yes"]:
            return None

    # Get the URL to the master CS
    csURL = prompt(
        HTML(
            "<b>Choose a configuration server URL (leave blank for default):</b>\n"
        ))
    if not csURL:
        csURL = setups[setup]

    # Confirm
    print_formatted_text(
        HTML("<b>Configuration is:</b>\n" +
             "  * <b>Setup:</b> <green>%s</green>\n" % setup +
             "  * <b>Configuration server:</b> <green>%s</green>\n" % csURL))
    confirm = prompt(HTML("<b>Are you sure you want to continue?</b> "),
                     default="y")
    if confirm.lower() in ["y", "yes"]:
        return setup, csURL
Ejemplo n.º 30
0
    def input_command(self) -> str:
        commands = [command.name for command in list(AWSLogsCommand)]
        completer = FuzzyWordCompleter(commands)
        history = FileHistory(
            self.alw_path.create_filepath(self.COMMAND_HISTORY_NAME))
        session = PromptSession(history=history)
        default = self.find_recent_history(history)

        command_str = session.prompt(
            "Command: ",
            completer=completer,
            complete_while_typing=True,
            default=default,
        )

        if command_str not in commands:
            return ""

        return command_str
Ejemplo n.º 31
0
    def input_profile(self, default="") -> str:
        profiles = ProfileConfig.load_profiles(self.AWS_CRED_PATH)
        completer = FuzzyWordCompleter(profiles, WORD=True)
        history = FileHistory(
            self.alw_path.create_filepath(self.PROFILE_HISTORY_NAME))

        session = PromptSession(history=history)
        default = self.find_default_from_history(default, history)

        profile = session.prompt(
            "Profile: ",
            completer=completer,
            complete_while_typing=True,
            default=default,
        )

        if profile not in profiles:
            return ""

        return profile
class FirstWordFuzzyWordCompleter(Completer):
    def __init__(self,
                 words: Union[List[str], Callable[[], List[str]]],
                 meta_dict: Optional[Dict[str, str]] = None,
                 WORD: bool = False) -> None:

        self.words = words
        self.meta_dict = meta_dict or {}
        self.WORD = WORD

        self.fuzzy_word_completer = FuzzyWordCompleter(words=self.words,
                                                       WORD=self.WORD)

    def get_completions(self, document: Document,
                        complete_event: CompleteEvent) -> Iterable[Completion]:
        pattern = re.compile(r"^\w*$")
        if not pattern.match(document.text.strip()):
            return []
        return self.fuzzy_word_completer.get_completions(
            document, complete_event)