Skip to content

Commit d80b27f

Browse files
committed
Made CompletionError exception available to non-argparse tab completion
1 parent 878601b commit d80b27f

File tree

8 files changed

+139
-149
lines changed

8 files changed

+139
-149
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
* `__name__`: __main__
1414
* `__file__`: script path (as typed, ~ will be expanded)
1515
* Only tab complete after redirection tokens if redirection is allowed
16+
* Made `CompletionError` exception available to non-argparse tab completion
1617
* Other
1718
* Removed undocumented `py run` command since it was replaced by `run_pyscript` a while ago
1819
* Renamed `AutoCompleter` to `ArgparseCompleter` for clarity

cmd2/__init__.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
pass
1212

1313
from .ansi import style, fg, bg
14-
from .argparse_custom import Cmd2ArgumentParser, CompletionError, CompletionItem, set_default_argument_parser
14+
from .argparse_custom import Cmd2ArgumentParser, CompletionItem, set_default_argument_parser
1515

1616
# Check if user has defined a module that sets a custom value for argparse_custom.DEFAULT_ARGUMENT_PARSER
1717
import argparse
@@ -27,4 +27,4 @@
2727
from .decorators import categorize, with_argument_list, with_argparser, with_argparser_and_unknown_args, with_category
2828
from .parsing import Statement
2929
from .py_bridge import CommandResult
30-
from .utils import Settable
30+
from .utils import CompletionError, Settable

cmd2/argparse_completer.py

Lines changed: 113 additions & 123 deletions
Large diffs are not rendered by default.

cmd2/argparse_custom.py

Lines changed: 0 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -117,13 +117,6 @@ def my_completer_method(self, text, line, begidx, endidx, arg_tokens)
117117
their values. All tokens are stored in the dictionary as the raw strings provided on the command line. It is up to
118118
the developer to determine if the user entered the correct argument type (e.g. int) and validate their values.
119119
120-
CompletionError Class:
121-
Raised during tab completion operations to report any sort of error you want printed by the ArgparseCompleter
122-
123-
Example use cases
124-
- Reading a database to retrieve a tab completion data set failed
125-
- A previous command line argument that determines the data set being completed is invalid
126-
127120
CompletionItem Class:
128121
This class was added to help in cases where uninformative data is being tab completed. For instance,
129122
tab completing ID numbers isn't very helpful to a user without context. Returning a list of CompletionItems
@@ -229,17 +222,6 @@ def generate_range_error(range_min: int, range_max: Union[int, float]) -> str:
229222
return err_str
230223

231224

232-
class CompletionError(Exception):
233-
"""
234-
Raised during tab completion operations to report any sort of error you want printed by the ArgparseCompleter
235-
236-
Example use cases
237-
- Reading a database to retrieve a tab completion data set failed
238-
- A previous command line argument that determines the data set being completed is invalid
239-
"""
240-
pass
241-
242-
243225
class CompletionItem(str):
244226
"""
245227
Completion item with descriptive text attached

cmd2/cmd2.py

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -47,13 +47,13 @@
4747
from . import constants
4848
from . import plugin
4949
from . import utils
50-
from .argparse_custom import CompletionError, CompletionItem, DEFAULT_ARGUMENT_PARSER
50+
from .argparse_custom import CompletionItem, DEFAULT_ARGUMENT_PARSER
5151
from .clipboard import can_clip, get_paste_buffer, write_to_paste_buffer
5252
from .decorators import with_argparser
5353
from .history import History, HistoryItem
5454
from .parsing import StatementParser, Statement, Macro, MacroArg, shlex_split
5555
from .rl_utils import rl_type, RlType, rl_get_point, rl_set_prompt, vt100_support, rl_make_safe_prompt, rl_warning
56-
from .utils import Settable
56+
from .utils import CompletionError, Settable
5757

5858
# Set up readline
5959
if rl_type == RlType.NONE: # pragma: no cover
@@ -1416,6 +1416,12 @@ def complete(self, text: str, state: int) -> Optional[str]:
14161416
except IndexError:
14171417
return None
14181418

1419+
except CompletionError as e:
1420+
err_str = str(e)
1421+
if err_str:
1422+
ansi.style_aware_write(sys.stdout, err_str + '\n')
1423+
rl_force_redisplay()
1424+
return None
14191425
except Exception as e:
14201426
# Insert a newline so the exception doesn't print in the middle of the command line being tab completed
14211427
self.perror()

cmd2/utils.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,17 @@ def str_to_bool(val: str) -> bool:
7272
raise ValueError("must be True or False (case-insensitive)")
7373

7474

75+
class CompletionError(Exception):
76+
"""
77+
Raised during tab completion operations to report any sort of error you want printed by the ArgparseCompleter
78+
79+
Example use cases
80+
- Reading a database to retrieve a tab completion data set failed
81+
- A previous command line argument that determines the data set being completed is invalid
82+
"""
83+
pass
84+
85+
7586
class Settable:
7687
"""Used to configure a cmd2 instance member to be settable via the set command in the CLI"""
7788
def __init__(self, name: str, val_type: Callable, description: str, *,

examples/argparse_completion.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,8 @@
66
import argparse
77
from typing import Dict, List
88

9-
from cmd2 import Cmd, Cmd2ArgumentParser, with_argparser, CompletionError, CompletionItem
10-
from cmd2.utils import basic_complete
9+
from cmd2 import Cmd, Cmd2ArgumentParser, with_argparser, CompletionItem
10+
from cmd2.utils import basic_complete, CompletionError
1111

1212
# Data source for argparse.choices
1313
food_item_strs = ['Pizza', 'Ham', 'Ham Sandwich', 'Potato']

tests/test_argparse_completer.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,8 @@
99
import pytest
1010

1111
import cmd2
12-
from cmd2 import with_argparser, Cmd2ArgumentParser, CompletionError, CompletionItem
13-
from cmd2.utils import StdSim, basic_complete
12+
from cmd2 import with_argparser, Cmd2ArgumentParser, CompletionItem
13+
from cmd2.utils import CompletionError, StdSim, basic_complete
1414
from .conftest import run_cmd, complete_tester
1515

1616
# Lists used in our tests (there is a mix of sorted and unsorted on purpose)

0 commit comments

Comments
 (0)