diff options
-rwxr-xr-x | cmd2/argparse_completer.py | 22 | ||||
-rwxr-xr-x | cmd2/cmd2.py | 42 | ||||
-rwxr-xr-x | examples/subcommands.py | 15 | ||||
-rwxr-xr-x | examples/tab_autocompletion.py | 98 | ||||
-rw-r--r-- | tests/test_autocompletion.py | 23 | ||||
-rw-r--r-- | tests/test_cmd2.py | 8 |
6 files changed, 182 insertions, 26 deletions
diff --git a/cmd2/argparse_completer.py b/cmd2/argparse_completer.py index 35f9342b..6c291e86 100755 --- a/cmd2/argparse_completer.py +++ b/cmd2/argparse_completer.py @@ -70,6 +70,8 @@ import re as _re from .rl_utils import rl_force_redisplay +ACTION_ARG_CHOICES = 'arg_choices' + class _RangeAction(object): def __init__(self, nargs: Union[int, str, Tuple[int, int], None]): @@ -220,6 +222,9 @@ class AutoCompleter(object): # if there are choices defined, record them in the arguments dictionary if action.choices is not None: self._arg_choices[action.dest] = action.choices + elif hasattr(action, ACTION_ARG_CHOICES): + action_arg_choices = getattr(action, ACTION_ARG_CHOICES) + self._arg_choices[action.dest] = action_arg_choices # if the parameter is flag based, it will have option_strings if action.option_strings: @@ -406,6 +411,22 @@ class AutoCompleter(object): return completion_results + def complete_command_help(self, tokens: List[str], text: str, line: str, begidx: int, endidx: int) -> List[str]: + for idx, token in enumerate(tokens): + is_last_token = idx > len(tokens) - 1 + + if idx >= self._token_start_index: + if self._positional_completers: + # For now argparse only allows 1 sub-command group per level + # so this will only loop once. + for completers in self._positional_completers.values(): + if token in completers: + return completers[token].complete_command_help(tokens, text, line, begidx, endidx) + else: + return self.basic_complete(text, line, begidx, endidx, completers.keys()) + return [] + + @staticmethod def _process_action_nargs(action: argparse.Action, arg_state: _ArgumentState) -> None: if isinstance(action, _RangeAction): @@ -467,6 +488,7 @@ class AutoCompleter(object): def _resolve_choices_for_arg(self, action: argparse.Action, used_values=()) -> List[str]: if action.dest in self._arg_choices: args = self._arg_choices[action.dest] + if callable(args): args = args() diff --git a/cmd2/cmd2.py b/cmd2/cmd2.py index 60d1dbf8..23e56f19 100755 --- a/cmd2/cmd2.py +++ b/cmd2/cmd2.py @@ -51,6 +51,7 @@ import pyperclip # Set up readline from .rl_utils import rl_force_redisplay, readline, rl_type, RlType +from .argparse_completer import AutoCompleter, ACArgumentParser if rl_type == RlType.PYREADLINE: @@ -268,6 +269,7 @@ def with_argparser_and_unknown_args(argparser: argparse.ArgumentParser) -> Calla # Mark this function as having an argparse ArgumentParser (used by do_help) cmd_wrapper.__dict__['has_parser'] = True + setattr(cmd_wrapper, 'argparser', argparser) # If there are subcommands, store their names in a list to support tab-completion of subcommand names if argparser._subparsers is not None: @@ -320,6 +322,7 @@ def with_argparser(argparser: argparse.ArgumentParser) -> Callable: # Mark this function as having an argparse ArgumentParser (used by do_help) cmd_wrapper.__dict__['has_parser'] = True + setattr(cmd_wrapper, 'argparser', argparser) # If there are subcommands, store their names in a list to support tab-completion of subcommand names if argparser._subparsers is not None: @@ -1794,16 +1797,15 @@ class Cmd(cmd.Cmd): try: compfunc = getattr(self, 'complete_' + command) except AttributeError: - compfunc = self.completedefault - subcommands = self.get_subcommands(command) - if subcommands is not None: - # Since there are subcommands, then try completing those if the cursor is in - # the token at index 1, otherwise default to using compfunc - index_dict = {1: subcommands} - compfunc = functools.partial(self.index_based_complete, - index_dict=index_dict, - all_else=compfunc) + cmd_func = getattr(self, 'do_' + command) + if hasattr(cmd_func, 'has_parser') and hasattr(cmd_func, 'argparser') and \ + getattr(cmd_func, 'has_parser'): + argparser = getattr(cmd_func, 'argparser') + compfunc = functools.partial(self._autocomplete_default, + argparser=argparser) + else: + compfunc = self.completedefault # A valid command was not entered else: @@ -1910,6 +1912,15 @@ class Cmd(cmd.Cmd): except IndexError: return None + def _autocomplete_default(self, text: str, line: str, begidx: int, endidx: int, + argparser: argparse.ArgumentParser) -> List[str]: + completer = AutoCompleter(argparser) + + tokens, _ = self.tokens_for_completion(line, begidx, endidx) + results = completer.complete_command(tokens, text, line, begidx, endidx) + + return results + def get_all_commands(self): """ Returns a list of all commands @@ -1964,6 +1975,15 @@ class Cmd(cmd.Cmd): strs_to_match = list(topics | visible_commands) matches = self.basic_complete(text, line, begidx, endidx, strs_to_match) + elif index >= subcmd_index and hasattr(self, 'do_' + tokens[cmd_index]) and\ + hasattr(getattr(self, 'do_' + tokens[cmd_index]), 'has_parser'): + command = tokens[cmd_index] + cmd_func = getattr(self, 'do_' + command) + parser = getattr(cmd_func, 'argparser') + completer = AutoCompleter(parser) + matches = completer.complete_command_help(tokens[1:], text, line, begidx, endidx) + + # Check if we are completing a subcommand elif index == subcmd_index: @@ -2843,10 +2863,10 @@ Usage: Usage: unalias [-a] name [name ...] else: raise LookupError("Parameter '%s' not supported (type 'show' for list of parameters)." % param) - set_parser = argparse.ArgumentParser(formatter_class=argparse.RawTextHelpFormatter) + set_parser = ACArgumentParser(formatter_class=argparse.RawTextHelpFormatter) set_parser.add_argument('-a', '--all', action='store_true', help='display read-only settings as well') set_parser.add_argument('-l', '--long', action='store_true', help='describe function of parameter') - set_parser.add_argument('settable', nargs='*', help='[param_name] [value]') + set_parser.add_argument('settable', nargs=(0,2), help='[param_name] [value]') @with_argparser(set_parser) def do_set(self, args): diff --git a/examples/subcommands.py b/examples/subcommands.py index 031b17b2..03088c93 100755 --- a/examples/subcommands.py +++ b/examples/subcommands.py @@ -53,15 +53,22 @@ class SubcommandsExample(cmd2.Cmd): # create the parser for the "bar" subcommand parser_bar = base_subparsers.add_parser('bar', help='bar help') - parser_bar.add_argument('z', help='string') parser_bar.set_defaults(func=base_bar) + bar_subparsers = parser_bar.add_subparsers(title='layer3', help='help for 3rd layer of commands') + parser_bar.add_argument('z', help='string') + + bar_subparsers.add_parser('apple', help='apple help') + bar_subparsers.add_parser('artichoke', help='artichoke help') + bar_subparsers.add_parser('cranberries', help='cranberries help') + # create the parser for the "sport" subcommand parser_sport = base_subparsers.add_parser('sport', help='sport help') - parser_sport.add_argument('sport', help='Enter name of a sport') + sport_arg = parser_sport.add_argument('sport', help='Enter name of a sport') + setattr(sport_arg, 'arg_choices', sport_item_strs) # Set both a function and tab completer for the "sport" subcommand - parser_sport.set_defaults(func=base_sport, completer=complete_base_sport) + parser_sport.set_defaults(func=base_sport) @with_argparser(base_parser) def do_base(self, args): @@ -75,7 +82,7 @@ class SubcommandsExample(cmd2.Cmd): self.do_help('base') # Enable tab completion of base to make sure the subcommands' completers get called. - complete_base = cmd2.Cmd.cmd_with_subs_completer + # complete_base = cmd2.Cmd.cmd_with_subs_completer if __name__ == '__main__': diff --git a/examples/tab_autocompletion.py b/examples/tab_autocompletion.py index c704908f..2c200757 100755 --- a/examples/tab_autocompletion.py +++ b/examples/tab_autocompletion.py @@ -13,6 +13,15 @@ from typing import List import cmd2 from cmd2 import with_argparser, with_category, argparse_completer +actors = ['Mark Hamill', 'Harrison Ford', 'Carrie Fisher', 'Alec Guinness', 'Peter Mayhew', + 'Anthony Daniels', 'Adam Driver', 'Daisy Ridley', 'John Boyega', 'Oscar Isaac', + 'Lupita Nyong\'o', 'Andy Serkis', 'Liam Neeson', 'Ewan McGregor', 'Natalie Portman', + 'Jake Lloyd', 'Hayden Christensen', 'Christopher Lee'] + +def query_actors() -> List[str]: + """Simulating a function that queries and returns a completion values""" + return actors + class TabCompleteExample(cmd2.Cmd): """ Example cmd2 application where we a base command which has a couple subcommands.""" @@ -27,10 +36,6 @@ class TabCompleteExample(cmd2.Cmd): show_ratings = ['TV-Y', 'TV-Y7', 'TV-G', 'TV-PG', 'TV-14', 'TV-MA'] static_list_directors = ['J. J. Abrams', 'Irvin Kershner', 'George Lucas', 'Richard Marquand', 'Rian Johnson', 'Gareth Edwards'] - actors = ['Mark Hamill', 'Harrison Ford', 'Carrie Fisher', 'Alec Guinness', 'Peter Mayhew', - 'Anthony Daniels', 'Adam Driver', 'Daisy Ridley', 'John Boyega', 'Oscar Isaac', - 'Lupita Nyong\'o', 'Andy Serkis', 'Liam Neeson', 'Ewan McGregor', 'Natalie Portman', - 'Jake Lloyd', 'Hayden Christensen', 'Christopher Lee'] USER_MOVIE_LIBRARY = ['ROGUE1', 'SW_EP04', 'SW_EP05'] MOVIE_DATABASE_IDS = ['SW_EP01', 'SW_EP02', 'SW_EP03', 'ROGUE1', 'SW_EP04', 'SW_EP05', 'SW_EP06', 'SW_EP07', 'SW_EP08', 'SW_EP09'] @@ -183,10 +188,6 @@ class TabCompleteExample(cmd2.Cmd): # The media command demonstrates a completer with multiple layers of subcommands # - This example uses a flat completion lookup dictionary - def query_actors(self) -> List[str]: - """Simulating a function that queries and returns a completion values""" - return TabCompleteExample.actors - def _do_media_movies(self, args) -> None: if not args.command: self.do_help('media movies') @@ -264,7 +265,7 @@ class TabCompleteExample(cmd2.Cmd): # name collisions. def complete_media(self, text, line, begidx, endidx): """ Adds tab completion to media""" - choices = {'actor': self.query_actors, # function + choices = {'actor': query_actors, # function 'director': TabCompleteExample.static_list_directors # static list } completer = argparse_completer.AutoCompleter(TabCompleteExample.media_parser, arg_choices=choices) @@ -275,6 +276,85 @@ class TabCompleteExample(cmd2.Cmd): return results ################################################################################### + # The media command demonstrates a completer with multiple layers of subcommands + # - This example tags a completion attribute on each action + + def _do_vid_media_movies(self, args) -> None: + if not args.command: + self.do_help('media movies') + elif args.command == 'list': + for movie_id in TabCompleteExample.MOVIE_DATABASE: + movie = TabCompleteExample.MOVIE_DATABASE[movie_id] + print('{}\n-----------------------------\n{} ID: {}\nDirector: {}\nCast:\n {}\n\n' + .format(movie['title'], movie['rating'], movie_id, + ', '.join(movie['director']), + '\n '.join(movie['actor']))) + + def _do_vid_media_shows(self, args) -> None: + if not args.command: + self.do_help('media shows') + + elif args.command == 'list': + for show_id in TabCompleteExample.SHOW_DATABASE: + show = TabCompleteExample.SHOW_DATABASE[show_id] + print('{}\n-----------------------------\n{} ID: {}' + .format(show['title'], show['rating'], show_id)) + for season in show['seasons']: + ep_list = show['seasons'][season] + print(' Season {}:\n {}' + .format(season, + '\n '.join(ep_list))) + print() + + video_parser = argparse_completer.ACArgumentParser(prog='media') + + video_types_subparsers = video_parser.add_subparsers(title='Media Types', dest='type') + + vid_movies_parser = video_types_subparsers.add_parser('movies') + vid_movies_parser.set_defaults(func=_do_vid_media_movies) + + vid_movies_commands_subparsers = vid_movies_parser.add_subparsers(title='Commands', dest='command') + + vid_movies_list_parser = vid_movies_commands_subparsers.add_parser('list') + + vid_movies_list_parser.add_argument('-t', '--title', help='Title Filter') + vid_movies_list_parser.add_argument('-r', '--rating', help='Rating Filter', nargs='+', + choices=ratings_types) + director_action = vid_movies_list_parser.add_argument('-d', '--director', help='Director Filter') + actor_action = vid_movies_list_parser.add_argument('-a', '--actor', help='Actor Filter', action='append') + setattr(director_action, argparse_completer.ACTION_ARG_CHOICES, static_list_directors) + setattr(actor_action, argparse_completer.ACTION_ARG_CHOICES, query_actors) + + vid_movies_add_parser = vid_movies_commands_subparsers.add_parser('add') + vid_movies_add_parser.add_argument('title', help='Movie Title') + vid_movies_add_parser.add_argument('rating', help='Movie Rating', choices=ratings_types) + director_action = vid_movies_add_parser.add_argument('-d', '--director', help='Director', nargs=(1, 2), required=True) + actor_action = vid_movies_add_parser.add_argument('actor', help='Actors', nargs='*') + setattr(director_action, argparse_completer.ACTION_ARG_CHOICES, static_list_directors) + setattr(actor_action, argparse_completer.ACTION_ARG_CHOICES, query_actors) + + vid_movies_delete_parser = vid_movies_commands_subparsers.add_parser('delete') + + vid_shows_parser = video_types_subparsers.add_parser('shows') + vid_shows_parser.set_defaults(func=_do_vid_media_shows) + + vid_shows_commands_subparsers = vid_shows_parser.add_subparsers(title='Commands', dest='command') + + vid_shows_list_parser = vid_shows_commands_subparsers.add_parser('list') + + @with_category(CAT_AUTOCOMPLETE) + @with_argparser(video_parser) + def do_video(self, args): + """Video management command demonstrates multiple layers of subcommands being handled by AutoCompleter""" + func = getattr(args, 'func', None) + if func is not None: + # Call whatever subcommand function was selected + func(self, args) + else: + # No subcommand was provided, so call help + self.do_help('video') + + ################################################################################### # The library command demonstrates a completer with multiple layers of subcommands # with different completion results per sub-command # - This demonstrates how to build a tree of completion lookups to pass down diff --git a/tests/test_autocompletion.py b/tests/test_autocompletion.py index e68bc104..1d0c9678 100644 --- a/tests/test_autocompletion.py +++ b/tests/test_autocompletion.py @@ -213,6 +213,27 @@ def test_autocomp_subcmd_flag_comp_list(cmd2_app): assert first_match is not None and first_match == '"Gareth Edwards' +def test_autocomp_subcmd_flag_comp_func_attr(cmd2_app): + text = 'A' + line = 'video movies list -a "{}'.format(text) + endidx = len(line) + begidx = endidx - len(text) + + first_match = complete_tester(text, line, begidx, endidx, cmd2_app) + assert first_match is not None and \ + cmd2_app.completion_matches == ['Adam Driver', 'Alec Guinness', 'Andy Serkis', 'Anthony Daniels'] + + +def test_autocomp_subcmd_flag_comp_list_attr(cmd2_app): + text = 'G' + line = 'video movies list -d {}'.format(text) + endidx = len(line) + begidx = endidx - len(text) + + first_match = complete_tester(text, line, begidx, endidx, cmd2_app) + assert first_match is not None and first_match == '"Gareth Edwards' + + def test_autcomp_pos_consumed(cmd2_app): text = '' line = 'library movie add SW_EP01 {}'.format(text) @@ -254,3 +275,5 @@ def test_autcomp_custom_func_list_and_dict_arg(cmd2_app): first_match = complete_tester(text, line, begidx, endidx, cmd2_app) assert first_match is not None and \ cmd2_app.completion_matches == ['S01E02', 'S01E03', 'S02E01', 'S02E03'] + + diff --git a/tests/test_cmd2.py b/tests/test_cmd2.py index 35ef4c0f..48f50bdc 100644 --- a/tests/test_cmd2.py +++ b/tests/test_cmd2.py @@ -68,8 +68,12 @@ def test_base_argparse_help(base_app, capsys): def test_base_invalid_option(base_app, capsys): run_cmd(base_app, 'set -z') out, err = capsys.readouterr() - expected = ['usage: set [-h] [-a] [-l] [settable [settable ...]]', 'set: error: unrecognized arguments: -z'] - assert normalize(str(err)) == expected + out = normalize(out) + err = normalize(err) + assert len(err) == 3 + assert len(out) == 15 + assert 'Error: unrecognized arguments: -z' in err[0] + assert out[0] == 'usage: set [-h] [-a] [-l] [settable [settable ...]]' def test_base_shortcuts(base_app): out = run_cmd(base_app, 'shortcuts') |