Skip to content

Commit b79cc69

Browse files
committed
Added a shlex.split() wrapper to have a common way of calling it.
Replaced parse_quoted_string with _get_command_arg_list.
1 parent 04eac4b commit b79cc69

File tree

3 files changed

+58
-49
lines changed

3 files changed

+58
-49
lines changed

cmd2/cmd2.py

Lines changed: 47 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -150,24 +150,6 @@ def categorize(func: Union[Callable, Iterable], category: str) -> None:
150150
setattr(func, HELP_CATEGORY, category)
151151

152152

153-
def parse_quoted_string(string: str, preserve_quotes: bool) -> List[str]:
154-
"""
155-
Parse a quoted string into a list of arguments
156-
:param string: the string being parsed
157-
:param preserve_quotes: if True, then quotes will not be stripped
158-
"""
159-
if isinstance(string, list):
160-
# arguments are already a list, return the list we were passed
161-
lexed_arglist = string
162-
else:
163-
# Use shlex to split the command line into a list of arguments based on shell rules
164-
lexed_arglist = shlex.split(string, comments=False, posix=False)
165-
166-
if not preserve_quotes:
167-
lexed_arglist = [utils.strip_quotes(arg) for arg in lexed_arglist]
168-
return lexed_arglist
169-
170-
171153
def with_category(category: str) -> Callable:
172154
"""A decorator to apply a category to a command function."""
173155
def cat_decorator(func):
@@ -176,10 +158,37 @@ def cat_decorator(func):
176158
return cat_decorator
177159

178160

161+
def _get_command_arg_list(to_parse: Union[str, Statement], preserve_quotes: bool) -> List[str]:
162+
"""
163+
Called by the argument_list and argparse wrappers to retrieve just the arguments being
164+
passed to their do_* methods as a list.
165+
166+
:param to_parse: what is being passed to the do_* method. It can be one of two types:
167+
1. An already parsed Statement
168+
2. An argument string in cases where a do_* method is explicitly called
169+
e.g.: Calling do_help('alias create') would cause to_parse to be 'alias create'
170+
171+
:param preserve_quotes: if True, then quotes will not be stripped from the arguments
172+
:return: the arguments in a list
173+
"""
174+
if isinstance(to_parse, Statement):
175+
# In the case of a Statement, we already have what we need
176+
if preserve_quotes:
177+
return to_parse.arg_list
178+
else:
179+
return to_parse.argv[1:]
180+
else:
181+
# We only have the argument string. Use the parser to split this string.
182+
parsed_arglist = StatementParser.shlex_split(to_parse)
183+
if not preserve_quotes:
184+
parsed_arglist = [utils.strip_quotes(arg) for arg in parsed_arglist]
185+
186+
return parsed_arglist
187+
188+
179189
def with_argument_list(*args: List[Callable], preserve_quotes: bool = False) -> Callable[[List], Optional[bool]]:
180190
"""A decorator to alter the arguments passed to a do_* cmd2 method. Default passes a string of whatever the user
181-
typed. With this decorator, the decorated method will receive a list of arguments parsed from user input using
182-
shlex.split().
191+
typed. With this decorator, the decorated method will receive a list of arguments parsed from user input.
183192
184193
:param args: Single-element positional argument list containing do_* method this decorator is wrapping
185194
:param preserve_quotes: if True, then argument quotes will not be stripped
@@ -189,9 +198,9 @@ def with_argument_list(*args: List[Callable], preserve_quotes: bool = False) ->
189198

190199
def arg_decorator(func: Callable):
191200
@functools.wraps(func)
192-
def cmd_wrapper(self, cmdline):
193-
lexed_arglist = parse_quoted_string(cmdline, preserve_quotes)
194-
return func(self, lexed_arglist)
201+
def cmd_wrapper(cmd2_instance, statement: Union[str, Statement]):
202+
parsed_arglist = _get_command_arg_list(statement, preserve_quotes)
203+
return func(cmd2_instance, parsed_arglist)
195204

196205
cmd_wrapper.__doc__ = func.__doc__
197206
return cmd_wrapper
@@ -214,16 +223,17 @@ def with_argparser_and_unknown_args(argparser: argparse.ArgumentParser, preserve
214223
import functools
215224

216225
# noinspection PyProtectedMember
217-
def arg_decorator(func: Callable[[Statement], Optional[bool]]):
226+
def arg_decorator(func: Callable):
218227
@functools.wraps(func)
219-
def cmd_wrapper(instance, cmdline):
220-
lexed_arglist = parse_quoted_string(cmdline, preserve_quotes)
228+
def cmd_wrapper(cmd2_instance, statement: Union[str, Statement]):
229+
parsed_arglist = _get_command_arg_list(statement, preserve_quotes)
230+
221231
try:
222-
args, unknown = argparser.parse_known_args(lexed_arglist)
232+
args, unknown = argparser.parse_known_args(parsed_arglist)
223233
except SystemExit:
224234
return
225235
else:
226-
return func(instance, args, unknown)
236+
return func(cmd2_instance, args, unknown)
227237

228238
# argparser defaults the program name to sys.argv[0]
229239
# we want it to be the name of our command
@@ -256,16 +266,18 @@ def with_argparser(argparser: argparse.ArgumentParser,
256266
import functools
257267

258268
# noinspection PyProtectedMember
259-
def arg_decorator(func: Callable[[Statement], Optional[bool]]):
269+
def arg_decorator(func: Callable):
260270
@functools.wraps(func)
261-
def cmd_wrapper(instance, cmdline):
262-
lexed_arglist = parse_quoted_string(cmdline, preserve_quotes)
271+
def cmd_wrapper(cmd2_instance, statement: Union[str, Statement]):
272+
273+
parsed_arglist = _get_command_arg_list(statement, preserve_quotes)
274+
263275
try:
264-
args = argparser.parse_args(lexed_arglist)
276+
args = argparser.parse_args(parsed_arglist)
265277
except SystemExit:
266278
return
267279
else:
268-
return func(instance, args)
280+
return func(cmd2_instance, args)
269281

270282
# argparser defaults the program name to sys.argv[0]
271283
# we want it to be the name of our command
@@ -742,8 +754,7 @@ def tokens_for_completion(self, line: str, begidx: int, endidx: int) -> Tuple[Li
742754
# Parse the line into tokens
743755
while True:
744756
try:
745-
# Use non-POSIX parsing to keep the quotes around the tokens
746-
initial_tokens = shlex.split(tmp_line[:tmp_endidx], comments=False, posix=False)
757+
initial_tokens = StatementParser.shlex_split(tmp_line[:tmp_endidx])
747758

748759
# If the cursor is at an empty token outside of a quoted string,
749760
# then that is the token being completed. Add it to the list.
@@ -1735,7 +1746,7 @@ def _run_cmdfinalization_hooks(self, stop: bool, statement: Optional[Statement])
17351746
# Fix those annoying problems that occur with terminal programs like "less" when you pipe to them
17361747
if self.stdin.isatty():
17371748
import subprocess
1738-
proc = subprocess.Popen(shlex.split('stty sane'))
1749+
proc = subprocess.Popen(['stty', 'sane'])
17391750
proc.communicate()
17401751

17411752
try:

cmd2/parsing.py

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -349,7 +349,7 @@ def tokenize(self, line: str) -> List[str]:
349349
return []
350350

351351
# split on whitespace
352-
tokens = shlex.split(line, comments=False, posix=False)
352+
tokens = StatementParser.shlex_split(line)
353353

354354
# custom lexing
355355
tokens = self._split_on_punctuation(tokens)
@@ -607,6 +607,16 @@ def _command_and_args(tokens: List[str]) -> Tuple[str, str]:
607607

608608
return command, args
609609

610+
@staticmethod
611+
def shlex_split(str_to_split: str) -> List[str]:
612+
"""
613+
A wrapper around shlex.split() that uses cmd2's preferred arguments
614+
This allows other classes to easily call split() the same way StatementParser does
615+
:param str_to_split: the string being split
616+
:return: A list of tokens
617+
"""
618+
return shlex.split(str_to_split, comments=False, posix=False)
619+
610620
def _split_on_punctuation(self, tokens: List[str]) -> List[str]:
611621
"""Further splits tokens from a command line using punctuation characters
612622

tests/test_argparse.py

Lines changed: 0 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -72,14 +72,6 @@ def do_arglist(self, arglist):
7272
def do_preservelist(self, arglist):
7373
self.stdout.write('{}'.format(arglist))
7474

75-
@cmd2.with_argument_list
76-
@cmd2.with_argument_list
77-
def do_arglisttwice(self, arglist):
78-
if isinstance(arglist, list):
79-
self.stdout.write(' '.join(arglist))
80-
else:
81-
self.stdout.write('False')
82-
8375
known_parser = argparse.ArgumentParser()
8476
known_parser.add_argument('-p', '--piglatin', action='store_true', help='atinLay')
8577
known_parser.add_argument('-s', '--shout', action='store_true', help='N00B EMULATION MODE')
@@ -178,10 +170,6 @@ def test_preservelist(argparse_app):
178170
out = run_cmd(argparse_app, 'preservelist foo "bar baz"')
179171
assert out[0] == "['foo', '\"bar baz\"']"
180172

181-
def test_arglist_decorator_twice(argparse_app):
182-
out = run_cmd(argparse_app, 'arglisttwice "we should" get these')
183-
assert out[0] == 'we should get these'
184-
185173

186174
class SubcommandApp(cmd2.Cmd):
187175
""" Example cmd2 application where we a base command which has a couple sub-commands."""

0 commit comments

Comments
 (0)