Skip to content

Commit de320b6

Browse files
committed
Fix a nasty bug in @with_argument_parser
second argument of do_* methods was getting mangled when we strip quotes
1 parent 0a03ab8 commit de320b6

File tree

2 files changed

+19
-3
lines changed

2 files changed

+19
-3
lines changed

cmd2.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -248,17 +248,17 @@ def with_argument_parser(argparser):
248248
argparse.ArgumentParser.
249249
"""
250250
def arg_decorator(func):
251-
def cmd_wrapper(instance, arg):
251+
def cmd_wrapper(instance, cmdline):
252252
# Use shlex to split the command line into a list of arguments based on shell rules
253-
lexed_arglist = shlex.split(arg, posix=POSIX_SHLEX)
253+
lexed_arglist = shlex.split(cmdline, posix=POSIX_SHLEX)
254254
# If not using POSIX shlex, make sure to strip off outer quotes for convenience
255255
if not POSIX_SHLEX and STRIP_QUOTES_FOR_NON_POSIX:
256256
temp_arglist = []
257257
for arg in lexed_arglist:
258258
temp_arglist.append(strip_quotes(arg))
259259
lexed_arglist = temp_arglist
260260
opts = argparser.parse_args(lexed_arglist)
261-
func(instance, arg, opts)
261+
func(instance, cmdline, opts)
262262

263263
# argparser defaults the program name to sys.argv[0]
264264
# we want it to be the name of our command

tests/test_argparse.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
"""
33
Cmd2 testing for argument parsing
44
"""
5+
import re
56
import argparse
67
import pytest
78

@@ -43,6 +44,16 @@ def do_tag(self, cmdline, args=None):
4344
self.stdout.write('<{0}>{1}</{0}>'.format(args.tag[0], ' '.join(args.content)))
4445
self.stdout.write('\n')
4546

47+
argparser = argparse.ArgumentParser()
48+
argparser.add_argument('args', nargs='*')
49+
@cmd2.with_argument_parser(argparser)
50+
def do_compare(self, cmdline, args=None):
51+
cmdline_str = re.sub('\s+', ' ', cmdline)
52+
args_str = re.sub('\s+', ' ', ' '.join(args.args))
53+
if cmdline_str == args_str:
54+
self.stdout.write('True')
55+
else:
56+
self.stdout.write('False')
4657

4758
@pytest.fixture
4859
def argparse_app():
@@ -88,4 +99,9 @@ def test_argparse_prog(argparse_app):
8899
out = run_cmd(argparse_app, 'help tag')
89100
progname = out[0].split(' ')[1]
90101
assert progname == 'tag'
102+
103+
def test_argparse_cmdline(argparse_app):
104+
out = run_cmd(argparse_app, 'compare this is a test')
105+
assert out[0] == 'True'
106+
91107

0 commit comments

Comments
 (0)