1 ##############################################################################
2 # Copyright (c) 2015 Huawei Technologies Co.,Ltd and others.
4 # All rights reserved. This program and the accompanying materials
5 # are made available under the terms of the Apache License, Version 2.0
6 # which accompanies this distribution, and is available at
7 # http://www.apache.org/licenses/LICENSE-2.0
8 ##############################################################################
14 class VstfHelpFormatter(argparse.HelpFormatter):
16 def start_section(self, heading):
17 # Title-case the headings
18 heading = '%s%s' % (heading[0].upper(), heading[1:])
19 super(VstfHelpFormatter, self).start_section(heading)
22 class VstfParser(argparse.ArgumentParser):
29 formatter_class=VstfHelpFormatter):
31 super(VstfParser, self).__init__(
33 description=description,
36 formatter_class=formatter_class)
39 def _find_actions(self, subparsers, actions_module):
40 for attr in (a for a in dir(actions_module) if a.startswith('do_')):
41 command = attr[3:].replace('_', '-')
42 callback = getattr(actions_module, attr)
43 desc = callback.__doc__ or ''
44 action_help = desc.strip()
45 arguments = getattr(callback, 'arguments', [])
46 subparser = subparsers.add_parser(
51 formatter_class=VstfHelpFormatter)
52 subparser.add_argument('-h', '--help',
54 help=argparse.SUPPRESS)
55 self.subcommands[command] = subparser
56 for (args, kwargs) in arguments:
57 subparser.add_argument(*args, **kwargs)
58 subparser.set_defaults(func=callback)
60 def set_subcommand_parser(self, target, metavar="<subcommand>"):
61 subparsers = self.add_subparsers(metavar=metavar)
62 self._find_actions(subparsers, target)
65 def set_parser_to_subcommand(self, subparser, target):
66 self._find_actions(subparser, target)
69 if __name__ == "__main__":
70 from vstf.common import test_func
71 parser = VstfParser(prog="vstf", description="test parser")
72 parser.set_subcommand_parser(test_func)
73 args = parser.parse_args(sys.argv[1:])