How to use the cmd2.utils 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_cmd2.py View on Github external
monkeypatch.setattr("cmd2.Cmd.do_shell", shell_mock)

    base_app.editor = 'fooedit'
    file_name = utils.quote_string('nothingweird.py')
    out, err = run_cmd(base_app, "edit {}".format(file_name))
    shell_mock.assert_called_once_with('"fooedit" "nothingweird.py"')
    shell_mock.reset_mock()

    base_app.editor = 'foo edit'
    file_name = utils.quote_string('has   spaces.py')
    out, err = run_cmd(base_app, "edit {}".format(file_name))
    shell_mock.assert_called_once_with('"foo edit" "has   spaces.py"')
    shell_mock.reset_mock()

    base_app.editor = '"fooedit"'
    file_name = utils.quote_string('"is_double_quoted.py"')
    out, err = run_cmd(base_app, "edit {}".format(file_name))
    shell_mock.assert_called_once_with('\'"fooedit"\' \'"is_double_quoted.py"\'')
    shell_mock.reset_mock()

    base_app.editor = "'fooedit'"
    file_name = utils.quote_string("'is_single_quoted.py'")
    out, err = run_cmd(base_app, "edit {}".format(file_name))
    shell_mock.assert_called_once_with('"\'fooedit\'" "\'is_single_quoted.py\'"')
    shell_mock.reset_mock()
github python-cmd2 / cmd2 / tests / test_utils.py View on Github external
def test_strip_quotes_no_quotes():
    base_str = HELLO_WORLD
    stripped = cu.strip_quotes(base_str)
    assert base_str == stripped
github python-cmd2 / cmd2 / tests / test_run_pyscript.py View on Github external
def test_run_pyscript_with_odd_file_names(base_app, python_script):
    """
    Pass in file names with various patterns. Since these files don't exist, we will rely
    on the error text to make sure the file names were processed correctly.
    """
    # Mock input to get us passed the warning about not ending in .py
    input_mock = mock.MagicMock(name='input', return_value='1')
    builtins.input = input_mock

    out, err = run_cmd(base_app, "run_pyscript {}".format(utils.quote_string(python_script)))
    err = ''.join(err)
    assert "Error reading script file '{}'".format(python_script) in err
github python-cmd2 / cmd2 / tests / test_utils.py View on Github external
def test_natural_keys():
    my_list = ['café', 'µ', 'A', 'micro', 'unity', 'x1', 'X2', 'X11', 'X0', 'x22']
    my_list.sort(key=cu.natural_keys)
    assert my_list == ['A', 'café', 'micro', 'unity', 'X0', 'x1', 'X2', 'X11', 'x22', 'µ']
    my_list = ['a3', 'a22', 'A2', 'A11', 'a1']
    my_list.sort(key=cu.natural_keys)
    assert my_list == ['a1', 'A2', 'a3', 'A11', 'a22']
github python-cmd2 / cmd2 / tests / test_completion.py View on Github external
def complete_test_multiline(self, text, line, begidx, endidx):
        return utils.basic_complete(text, line, begidx, endidx, sport_item_strs)
github python-cmd2 / cmd2 / cmd2 / transcript.py View on Github external
def setUp(self):
        if self.cmdapp:
            self._fetchTranscripts()

            # Trap stdout
            self._orig_stdout = self.cmdapp.stdout
            self.cmdapp.stdout = utils.StdSim(self.cmdapp.stdout)
github python-cmd2 / cmd2 / examples / tab_autocompletion.py View on Github external
def instance_query_movie_ids(self) -> List[str]:
        """Demonstrates showing tabular hinting of tab completion information"""
        completions_with_desc = []

        # Sort the movie id strings with a natural sort since they contain numbers
        for movie_id in utils.natural_sort(self.MOVIE_DATABASE_IDS):
            if movie_id in self.MOVIE_DATABASE:
                movie_entry = self.MOVIE_DATABASE[movie_id]
                completions_with_desc.append(CompletionItem(movie_id, movie_entry['title']))

        # Mark that we already sorted the matches
        self.matches_sorted = True
        return completions_with_desc
github python-cmd2 / cmd2 / cmd2 / argcomplete_bridge.py View on Github external
# is causing the parsing error. Return None since
                    # this means the line is malformed.
                    return None, None, None, None

                # Add a closing quote and try to parse again
                unclosed_quote = quotes_to_try[0]
                quotes_to_try = quotes_to_try[1:]

                tmp_line = line[:endidx]
                tmp_line += unclosed_quote
                tmp_endidx = endidx + 1

        raw_tokens = initial_tokens

        # Save the unquoted tokens
        tokens = [utils.strip_quotes(cur_token) for cur_token in raw_tokens]

        # If the token being completed had an unclosed quote, we need
        # to remove the closing quote that was added in order for it
        # to match what was on the command line.
        if unclosed_quote:
            raw_tokens[-1] = raw_tokens[-1][:-1]

        return tokens, raw_tokens, begidx, endidx
github python-cmd2 / cmd2 / cmd2 / parsing.py View on Github external
# remove all the tokens after the pipe
            tokens = tokens[:pipe_index]

        # Check for output redirect/append
        elif redir_index != append_index:
            if redir_index < append_index:
                output = constants.REDIRECTION_OUTPUT
                output_index = redir_index
            else:
                output = constants.REDIRECTION_APPEND
                output_index = append_index

            # Check if we are redirecting to a file
            if len(tokens) > output_index + 1:
                unquoted_path = utils.strip_quotes(tokens[output_index + 1])
                if unquoted_path:
                    output_to = utils.expand_user(tokens[output_index + 1])

            # remove all the tokens after the output redirect
            tokens = tokens[:output_index]

        if terminator:
            # whatever is left is the suffix
            suffix = ' '.join(tokens)
        else:
            # no terminator, so whatever is left is the command and the args
            suffix = ''
            if not command:
                # command could already have been set, if so, don't set it again
                (command, args) = self._command_and_args(tokens)
                arg_list = tokens[1:]
github python-cmd2 / cmd2 / cmd2 / argparse_completer.py View on Github external
: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 []