fdstools.py 3.9 KB
Newer Older
jhoogenboom's avatar
jhoogenboom committed
1
2
#!/usr/bin/env python

jhoogenboom's avatar
jhoogenboom committed
3
import argparse, pkgutil, os, re, textwrap
jhoogenboom's avatar
jhoogenboom committed
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
import tools

from . import usage, version


# Map tool names to argument parsers.
__tools__ = {}


class _HelpAction(argparse.Action):
    def __call__(self, parser, namespace, values, option_string=None):
        # If valid 'tool' argument is given, call that tool's help.
        if values and values[0] in __tools__:
            __tools__[values[0]].print_help()
            __tools__[values[0]].exit()
        else:
            parser.print_help()
            parser.exit()
    #__call__
#_HelpAction


class _VersionAction(argparse.Action):
    def __call__(self, parser, namespace, values, option_string=None):
        # If valid 'tool' argument is given, print that tool's version.
        if values and values[0] in __tools__:
            parser = __tools__[values[0]]
        formatter = parser._get_formatter()
        formatter.add_text(parser.version)
        parser.exit(message=formatter.format_help())
    #__call__
#_VersionAction


jhoogenboom's avatar
jhoogenboom committed
38
39
40
41
42
43
44
45
46
47
48
49
class _HelpFormatter(argparse.HelpFormatter):
    _pat_paragraph_delim = re.compile("\n\n+")
    def _fill_text(self, text, width, indent):
        # Reflow (wrap) description text, but maintain paragraphs.
        return "\n\n".join(
            textwrap.fill(self._whitespace_matcher.sub(" ", p).strip(), width,
                          initial_indent=indent, subsequent_indent=indent)
            for p in self._pat_paragraph_delim.split(text))
    #_fill_text
#_HelpFormatter


jhoogenboom's avatar
jhoogenboom committed
50
51
52
53
def main():
    """
    Main entry point.
    """
jhoogenboom's avatar
jhoogenboom committed
54
55
    parser = argparse.ArgumentParser(formatter_class=_HelpFormatter,
                                     add_help=False, description=usage[0])
jhoogenboom's avatar
jhoogenboom committed
56
57
58
59
60
    parser.version = version(parser.prog)
    parser.add_argument('-h', '--help', action=_HelpAction,
                        default=argparse.SUPPRESS, nargs=argparse.REMAINDER,
                        help="show this help message, or help for the "
                             "specified TOOL, and exit")
61
62
63
64
65
    parser.add_argument('-v', "--version", action=_VersionAction,
                        default=argparse.SUPPRESS, nargs=argparse.REMAINDER,
                        help="show version number and exit")
    parser.add_argument('-d', "--debug", action="store_true",
                        help="if specified, debug output is printed to stdout")
jhoogenboom's avatar
jhoogenboom committed
66
67
68
69
70
71
72
73
74
75
76
77
    subparsers = parser.add_subparsers(title='available tools', dest='tool',
                                       metavar='TOOL', help="specify which "
                                       "tool to run")
    subparsers.required = True

    prefix = tools.__name__ + "."
    for importer, name, ispkg in pkgutil.iter_modules(
            path=[os.path.join(
                os.path.dirname(os.path.abspath(__file__)),
                "tools")]):
        module = importer.find_module(prefix + name).load_module(prefix + name)
        subparser = subparsers.add_parser(
jhoogenboom's avatar
jhoogenboom committed
78
79
80
            name,
            formatter_class=_HelpFormatter,
            help=module.__doc__.split("\n\n", 1)[0],
81
            description=module.__doc__,
jhoogenboom's avatar
jhoogenboom committed
82
83
            version=version(parser.prog, name, module.__version__))
        __tools__[name] = subparser
jhoogenboom's avatar
jhoogenboom committed
84
85
        subparser.add_argument('-d', "--debug", action="store_true",
            help="if specified, debug output is printed to stdout")
86
87
        module.add_arguments(subparser)
        subparser.set_defaults(func=module.run)
jhoogenboom's avatar
jhoogenboom committed
88
    try:
89
        args, unknowns = parser.parse_known_args()
jhoogenboom's avatar
jhoogenboom committed
90
    except Exception as error:
jhoogenboom's avatar
jhoogenboom committed
91
        parser.error(error)
jhoogenboom's avatar
jhoogenboom committed
92
    try:
jhoogenboom's avatar
jhoogenboom committed
93
94
95
96
97
        if unknowns:
            # Politely inform the user about unknown arguments.
            __tools__[args.tool].error(
                "The following arguments are not known. Please check spelling "
                "and argument order: '%s'." % "', '".join(unknowns))
jhoogenboom's avatar
jhoogenboom committed
98
99
100
101
102
        args.func(args)
    except Exception as error:
        if args.debug:
            raise
        __tools__[args.tool].error(error)
jhoogenboom's avatar
jhoogenboom committed
103
104
105
106
107
#main


if __name__ == "__main__":
    main()