diff --git a/sphinxarg/parser.py b/sphinxarg/parser.py index aa3ef09..b86da3d 100644 --- a/sphinxarg/parser.py +++ b/sphinxarg/parser.py @@ -20,7 +20,9 @@ def parser_navigate(parser_result, path, current_path=None): ' '.join(current_path)) next_hop = path.pop(0) for child in parser_result['children']: - if child['name'] == next_hop: + # identifer is only used for aliased subcommands + identifier = child['identifier'] if 'identifier' in child else child['name'] + if identifier == next_hop: current_path.append(next_hop) return parser_navigate(child, path, current_path) raise NavigationException( @@ -88,6 +90,8 @@ def parse_parser(parser, data=None, **kwargs): 'usage': subaction.format_usage().strip(), 'bare_usage': _format_usage_without_prefix(subaction), } + if subalias: + subdata['identifier'] = name parse_parser(subaction, subdata, **kwargs) data.setdefault('children', []).append(subdata) diff --git a/test/test_parser.py b/test/test_parser.py index 075888b..26a7481 100755 --- a/test/test_parser.py +++ b/test/test_parser.py @@ -1,5 +1,6 @@ import argparse from sphinxarg.parser import parse_parser, parser_navigate +import six def test_parse_options(): @@ -187,6 +188,84 @@ def test_parse_nested(): ] +if six.PY3: + def test_parse_nested_with_alias(): + parser = argparse.ArgumentParser() + parser.add_argument('foo', default=False, help='foo help') + parser.add_argument('bar', default=False) + + subparsers = parser.add_subparsers() + + subparser = subparsers.add_parser('install', aliases=['i'], help='install help') + subparser.add_argument('ref', type=str, help='foo1 help') + subparser.add_argument('--upgrade', action='store_true', default=False, help='foo2 help') + + data = parse_parser(parser) + + assert data['action_groups'][0]['options'] == [ + { + 'name': ['foo'], + 'help': 'foo help', + 'default': False + }, { + 'name': ['bar'], + 'help': '', + 'default': False + } + ] + + assert data['children'] == [ + { + 'name': 'install (i)', + 'identifier': 'install', + 'help': 'install help', + 'usage': 'usage: py.test install [-h] [--upgrade] ref', + 'bare_usage': 'py.test install [-h] [--upgrade] ref', + 'action_groups': [ + { + 'title': 'Positional Arguments', + 'description': None, + 'options': [ + { + 'name': ['ref'], + 'help': 'foo1 help', + 'default': None + } + ] + }, + { + 'description': None, + 'title': 'Named Arguments', + 'options': [ + { + 'name': ['--upgrade'], + 'default': False, + 'help': 'foo2 help' + } + ] + } + ] + } + ] + + def test_aliased_traversal(): + parser = argparse.ArgumentParser() + + subparsers1 = parser.add_subparsers() + subparsers1.add_parser('level1', aliases=['l1']) + + data = parse_parser(parser) + + data2 = parser_navigate(data, 'level1') + + assert(data2 == { + 'bare_usage': 'py.test level1 [-h]', + 'help': '', + 'usage': 'usage: py.test level1 [-h]', + 'name': 'level1 (l1)', + 'identifier': 'level1'}) + + def test_parse_nested_traversal(): parser = argparse.ArgumentParser()