summaryrefslogtreecommitdiffstats
path: root/vstf/vstf/common/vstfcli.py
blob: 9dc9977904afc262d846c01d467cf09edf999344 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import argparse
import sys


class VstfHelpFormatter(argparse.HelpFormatter):
    def start_section(self, heading):
        # Title-case the headings
        heading = '%s%s' % (heading[0].upper(), heading[1:])
        super(VstfHelpFormatter, self).start_section(heading)


class VstfParser(argparse.ArgumentParser):
    def __init__(self,
                 prog='vstf',
                 description="",
                 epilog='',
                 add_help=True,
                 formatter_class=VstfHelpFormatter):

        super(VstfParser, self).__init__(
            prog=prog,
            description=description,
            epilog=epilog,
            add_help=add_help,
            formatter_class=formatter_class)
        self.subcommands = {}

    def _find_actions(self, subparsers, actions_module):
        for attr in (a for a in dir(actions_module) if a.startswith('do_')):
            command = attr[3:].replace('_', '-')
            callback = getattr(actions_module, attr)
            desc = callback.__doc__ or ''
            action_help = desc.strip()
            arguments = getattr(callback, 'arguments', [])
            subparser = subparsers.add_parser(command,
                                              help=action_help,
                                              description=desc,
                                              add_help=False,
                                              formatter_class=VstfHelpFormatter)
            subparser.add_argument('-h', '--help',
                                   action='help',
                                   help=argparse.SUPPRESS)
            self.subcommands[command] = subparser
            for (args, kwargs) in arguments:
                subparser.add_argument(*args, **kwargs)
            subparser.set_defaults(func=callback)

    def set_subcommand_parser(self, target, metavar="<subcommand>"):
        subparsers = self.add_subparsers(metavar=metavar)
        self._find_actions(subparsers, target)
        return subparsers

    def set_parser_to_subcommand(self, subparser, target):
        self._find_actions(subparser, target)


if __name__ == "__main__":
    from vstf.common import test_func
    parser = VstfParser(prog="vstf", description="test parser")
    parser.set_subcommand_parser(test_func)
    args = parser.parse_args(sys.argv[1:])
    args.func(args)