| 1 |
|
| 2 |
"""A simple example demonstrating how to integrate tab completion with argparse-based commands.""" |
| 3 |
|
| 4 |
import argparse |
| 5 |
|
| 6 |
import rich.box |
| 7 |
from rich.style import Style |
| 8 |
from rich.table import Table |
| 9 |
from rich.text import Text |
| 10 |
|
| 11 |
from cmd2 import ( |
| 12 |
Choices, |
| 13 |
Cmd, |
| 14 |
Cmd2ArgumentParser, |
| 15 |
Cmd2Style, |
| 16 |
Color, |
| 17 |
CompletionError, |
| 18 |
CompletionItem, |
| 19 |
with_argparser, |
| 20 |
) |
| 21 |
|
| 22 |
|
| 23 |
food_item_strs = ["Pizza", "Ham", "Ham Sandwich", "Potato"] |
| 24 |
|
| 25 |
|
| 26 |
class ArgparseCompletion(Cmd): |
| 27 |
def __init__(self) -> None: |
| 28 |
super().__init__(include_ipy=True) |
| 29 |
self.sport_item_strs = ["Bat", "Basket", "Basketball", "Football", "Space Ball"] |
| 30 |
|
| 31 |
def choices_provider(self) -> Choices: |
| 32 |
"""A choices provider is useful when the choice list is based on instance data of your application.""" |
| 33 |
return Choices.from_values(self.sport_item_strs) |
| 34 |
|
| 35 |
def choices_completion_error(self) -> Choices: |
| 36 |
"""CompletionErrors can be raised if an error occurs while tab completing. |
| 37 |
|
| 38 |
Example use cases |
| 39 |
- Reading a database to retrieve a tab completion data set failed |
| 40 |
- A previous command line argument that determines the data set being completed is invalid |
| 41 |
""" |
| 42 |
if self.debug: |
| 43 |
return Choices.from_values(self.sport_item_strs) |
| 44 |
raise CompletionError("debug must be true") |
| 45 |
|
| 46 |
def choices_completion_tables(self) -> Choices: |
| 47 |
"""Return CompletionItems with completion tables. These give more context to what's being tab completed.""" |
| 48 |
fancy_item = Text.assemble( |
| 49 |
"These things can\ncontain newlines and\n", |
| 50 |
Text("styled text!!", style=Style(color=Color.BRIGHT_YELLOW, underline=True)), |
| 51 |
) |
| 52 |
|
| 53 |
table_item = Table( |
| 54 |
"Left Column", |
| 55 |
"Right Column", |
| 56 |
box=rich.box.ROUNDED, |
| 57 |
border_style=Cmd2Style.TABLE_BORDER, |
| 58 |
) |
| 59 |
table_item.add_row("Yes, it's true.", "CompletionItems can") |
| 60 |
table_item.add_row("even display description", "data in tables!") |
| 61 |
|
| 62 |
item_dict = { |
| 63 |
1: "My item", |
| 64 |
2: "Another item", |
| 65 |
3: "Yet another item", |
| 66 |
4: fancy_item, |
| 67 |
5: table_item, |
| 68 |
} |
| 69 |
|
| 70 |
completion_items = [CompletionItem(item_id, table_data=[description]) for item_id, description in item_dict.items()] |
| 71 |
return Choices(items=completion_items) |
| 72 |
|
| 73 |
def choices_arg_tokens(self, arg_tokens: dict[str, list[str]]) -> Choices: |
| 74 |
"""If a choices or completer function/method takes a value called arg_tokens, then it will be |
| 75 |
passed a dictionary that maps the command line tokens up through the one being completed |
| 76 |
to their argparse destination name. All values of the arg_tokens dictionary are lists, even if |
| 77 |
a particular argument expects only 1 token. |
| 78 |
""" |
| 79 |
|
| 80 |
values = ["choices_provider", "flag"] |
| 81 |
if "choices_provider" in arg_tokens: |
| 82 |
values.append("is {}".format(arg_tokens["choices_provider"][0])) |
| 83 |
else: |
| 84 |
values.append("not supplied") |
| 85 |
return Choices.from_values(values) |
| 86 |
|
| 87 |
|
| 88 |
example_parser = Cmd2ArgumentParser( |
| 89 |
description="Command demonstrating tab completion with argparse\nNotice even the flags of this command tab complete" |
| 90 |
) |
| 91 |
|
| 92 |
|
| 93 |
|
| 94 |
example_parser.add_argument("--choices", choices=food_item_strs, metavar="CHOICE", help="tab complete using choices") |
| 95 |
|
| 96 |
|
| 97 |
example_parser.add_argument( |
| 98 |
"--choices_provider", choices_provider=choices_provider, help="tab complete using a choices_provider" |
| 99 |
) |
| 100 |
|
| 101 |
|
| 102 |
example_parser.add_argument("--completer", completer=Cmd.path_complete, help="tab complete using a completer") |
| 103 |
|
| 104 |
|
| 105 |
example_parser.add_argument( |
| 106 |
"--completion_error", |
| 107 |
choices_provider=choices_completion_error, |
| 108 |
help="raise a CompletionError while tab completing if debug is False", |
| 109 |
) |
| 110 |
|
| 111 |
|
| 112 |
example_parser.add_argument( |
| 113 |
"--completion_table", |
| 114 |
choices_provider=choices_completion_tables, |
| 115 |
metavar="ITEM_ID", |
| 116 |
table_columns=["Description"], |
| 117 |
help="demonstrate use of completion table", |
| 118 |
) |
| 119 |
|
| 120 |
|
| 121 |
example_parser.add_argument( |
| 122 |
"--arg_tokens", choices_provider=choices_arg_tokens, help="demonstrate use of arg_tokens dictionary" |
| 123 |
) |
| 124 |
|
| 125 |
@with_argparser(example_parser) |
| 126 |
def do_example(self, _: argparse.Namespace) -> None: |
| 127 |
"""The example command.""" |
| 128 |
self.poutput("I do nothing") |
| 129 |
|
| 130 |
|
| 131 |
if __name__ == "__main__": |
| 132 |
import sys |
| 133 |
|
| 134 |
app = ArgparseCompletion() |
| 135 |
sys.exit(app.cmdloop()) |