How to use the cmd2.argparse_completer.AutoCompleter function in cmd2

To help you get started, we’ve selected a few cmd2 examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github python-cmd2 / cmd2 / tests / test_argparse_completer.py View on Github external
def test_complete_command_help_no_tokens(ac_app):
    from cmd2.argparse_completer import AutoCompleter

    parser = Cmd2ArgumentParser()
    ac = AutoCompleter(parser, ac_app)

    completions = ac.complete_subcommand_help(tokens=[], text='', line='', begidx=0, endidx=0)
    assert not completions
github python-cmd2 / cmd2 / tests / test_bashcompletion.py View on Github external
def test_bash_nocomplete(parser1):
    completer = CompletionFinder()
    result = completer(parser1, AutoCompleter(parser1))
    assert result is None
github python-cmd2 / cmd2 / tests / test_bashcompletion.py View on Github external
exp_out = '\013\013 '
    exp_err = '''
Hint:
  TITLE                   Movie Title'''

    mock.patch.dict(os.environ, {'_ARGCOMPLETE': '1',
                                 '_ARGCOMPLETE_IFS': '\013',
                                 'COMP_TYPE': '63',
                                 'COMP_LINE': comp_line,
                                 'COMP_POINT': str(len(comp_line))})
    mock.patch.object(os, 'fdopen', fdopen_fail_9)

    with pytest.raises(SystemExit):
        choices = {'actor': query_actors,  # function
                   }
        autocompleter = AutoCompleter(parser1, arg_choices=choices)
        completer(parser1, autocompleter, exit_method=sys.exit)

    out, err = capfd.readouterr()
    assert out == exp_out
    assert err == exp_err
github python-cmd2 / cmd2 / tests / test_argparse_completer.py View on Github external
def test_complete_command_no_tokens(ac_app):
    from cmd2.argparse_completer import AutoCompleter

    parser = Cmd2ArgumentParser()
    ac = AutoCompleter(parser, ac_app)

    completions = ac.complete_command(tokens=[], text='', line='', begidx=0, endidx=0)
    assert not completions
github python-cmd2 / cmd2 / cmd2 / argparse_completer.py View on Github external
if pos_arg_state is None:
                    # Make sure we are still have positional arguments to parse
                    if remaining_positionals:
                        action = remaining_positionals.popleft()

                        # Are we at a subcommand? If so, forward to the matching completer
                        if action == self._subcommand_action:
                            if token in self._subcommand_action.choices:
                                # Merge self._parent_tokens and consumed_arg_values
                                parent_tokens = {**self._parent_tokens, **consumed_arg_values}

                                # Include the subcommand name if its destination was set
                                if action.dest != argparse.SUPPRESS:
                                    parent_tokens[action.dest] = [token]

                                completer = AutoCompleter(self._subcommand_action.choices[token], self._cmd2_app,
                                                          parent_tokens=parent_tokens)
                                return completer.complete_command(tokens[token_index:], text, line, begidx, endidx)
                            else:
                                # Invalid subcommand entered, so no way to complete remaining tokens
                                return []

                        # Otherwise keep track of the argument
                        else:
                            pos_arg_state = AutoCompleter._ArgumentState(action)

                # Check if we have a positional to consume this token
                if pos_arg_state is not None:
                    # No need to check for an error since we remove a completed group's positional from
                    # remaining_positionals which means this action can't belong to a completed mutex group
                    update_mutex_groups(pos_arg_state.action)
github python-cmd2 / cmd2 / cmd2 / argparse_completer.py View on Github external
parent_tokens = {**self._parent_tokens, **consumed_arg_values}

                                # Include the subcommand name if its destination was set
                                if action.dest != argparse.SUPPRESS:
                                    parent_tokens[action.dest] = [token]

                                completer = AutoCompleter(self._subcommand_action.choices[token], self._cmd2_app,
                                                          parent_tokens=parent_tokens)
                                return completer.complete_command(tokens[token_index:], text, line, begidx, endidx)
                            else:
                                # Invalid subcommand entered, so no way to complete remaining tokens
                                return []

                        # Otherwise keep track of the argument
                        else:
                            pos_arg_state = AutoCompleter._ArgumentState(action)

                # Check if we have a positional to consume this token
                if pos_arg_state is not None:
                    # No need to check for an error since we remove a completed group's positional from
                    # remaining_positionals which means this action can't belong to a completed mutex group
                    update_mutex_groups(pos_arg_state.action)

                    consume_argument(pos_arg_state)

                    # No more flags are allowed if this is a REMAINDER argument
                    if pos_arg_state.is_remainder:
                        skip_remaining_flags = True

                    # Check if we have finished with this positional
                    elif pos_arg_state.count >= pos_arg_state.max:
                        pos_arg_state = None
github python-cmd2 / cmd2 / examples / bash_completion.py View on Github external
# Handle bash completion if it's installed
# This early check allows the script to bail out early to provide tab-completion results
# to the argcomplete library. Putting this at the end of the file would cause the full application
# to load fulfill every tab-completion request coming from bash.  This can cause a notable delay
# on the bash prompt.
try:
    # only move forward if we can import CompletionFinder and AutoCompleter
    from cmd2.argcomplete_bridge import CompletionFinder
    from cmd2.argparse_completer import AutoCompleter
    import sys
    if __name__ == '__main__':
        completer = CompletionFinder()

        # completer will return results to argcomplete and exit the script
        completer(bash_parser, AutoCompleter(bash_parser))
except ImportError:
    pass

# Intentionally below the bash completion code to reduce tab completion lag
import cmd2  # noqa: E402


class DummyApp(cmd2.Cmd):
    """
    Dummy cmd2 app
    """

    def __init__(self):
        super().__init__()
github Den1al / JSShell / shell / plugins / clients.py View on Github external
def complete_clients(self, text: str, line: str, begin_index: int, end_index: int) -> List[str]:
        """ Handles the auto completion for this command """

        choices = dict(
            id=Client.unique_client_ids,
            kill=Client.unique_client_ids
        )

        completer = argparse_completer.AutoCompleter(
            ClientsPlugin.clients_plugin_parser,
            arg_choices=choices
        )

        tokens, _ = self.tokens_for_completion(line, begin_index, end_index)

        return completer.complete_command(tokens, text, line, begin_index, end_index)
github python-cmd2 / cmd2 / cmd2 / argparse_completer.py View on Github external
def complete_subcommand_help(self, tokens: List[str], text: str, line: str, begidx: int, endidx: int) -> List[str]:
        """
        Supports cmd2's help command in the completion of subcommand names
        :param tokens: command line tokens
        :param text: the string prefix we are attempting to match (all matches must begin with it)
        :param line: the current input line with leading whitespace removed
        :param begidx: the beginning index of the prefix text
        :param endidx: the ending index of the prefix text
        :return: List of subcommand completions
        """
        # If our parser has subcommands, we must examine the tokens and check if they are subcommands
        # If so, we will let the subcommand's parser handle the rest of the tokens via another AutoCompleter.
        if self._subcommand_action is not None:
            for token_index, token in enumerate(tokens[1:], start=1):
                if token in self._subcommand_action.choices:
                    completer = AutoCompleter(self._subcommand_action.choices[token], self._cmd2_app)
                    return completer.complete_subcommand_help(tokens[token_index:], text, line, begidx, endidx)
                elif token_index == len(tokens) - 1:
                    # Since this is the last token, we will attempt to complete it
                    return utils.basic_complete(text, line, begidx, endidx, self._subcommand_action.choices)
                else:
                    break
        return []