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

3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
#
# Copyright (C) 2016 Jerry Hoogenboom
#
# This file is part of FDSTools, data analysis tools for Next
# Generation Sequencing of forensic DNA markers.
#
# FDSTools is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation, either version 3 of the License, or (at
# your option) any later version.
#
# FDSTools is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with FDSTools.  If not, see <http://www.gnu.org/licenses/>.
#

jhoogenboom's avatar
jhoogenboom committed
23
import argparse, pkgutil, os, re, textwrap
24
#import cProfile  # Imported only if the -d/--debug option is specified
jhoogenboom's avatar
jhoogenboom committed
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
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
59 60 61 62 63 64 65 66 67 68 69 70
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
71 72 73 74
def main():
    """
    Main entry point.
    """
jhoogenboom's avatar
jhoogenboom committed
75 76
    parser = argparse.ArgumentParser(formatter_class=_HelpFormatter,
                                     add_help=False, description=usage[0])
jhoogenboom's avatar
jhoogenboom committed
77 78 79 80 81
    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")
82 83 84 85
    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",
86
                        help="if specified, additional debug output is given")
jhoogenboom's avatar
jhoogenboom committed
87 88 89 90 91 92 93 94 95 96 97 98
    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
99 100 101
            name,
            formatter_class=_HelpFormatter,
            help=module.__doc__.split("\n\n", 1)[0],
102
            description=module.__doc__,
jhoogenboom's avatar
jhoogenboom committed
103 104
            version=version(parser.prog, name, module.__version__))
        __tools__[name] = subparser
jhoogenboom's avatar
jhoogenboom committed
105
        subparser.add_argument('-d', "--debug", action="store_true",
106
            help="if specified, additional debug output is given")
107 108
        module.add_arguments(subparser)
        subparser.set_defaults(func=module.run)
jhoogenboom's avatar
jhoogenboom committed
109
    try:
110
        args, unknowns = parser.parse_known_args()
jhoogenboom's avatar
jhoogenboom committed
111
    except Exception as error:
jhoogenboom's avatar
jhoogenboom committed
112
        parser.error(error)
jhoogenboom's avatar
jhoogenboom committed
113
    try:
jhoogenboom's avatar
jhoogenboom committed
114 115 116 117 118
        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))
119 120 121 122 123 124
        if args.debug:
            import cProfile
            cProfile.runctx(
                "args.func(args)", globals(), locals(), sort="tottime")
        else:
            args.func(args)
jhoogenboom's avatar
jhoogenboom committed
125 126 127 128
    except Exception as error:
        if args.debug:
            raise
        __tools__[args.tool].error(error)
jhoogenboom's avatar
jhoogenboom committed
129 130 131 132 133
#main


if __name__ == "__main__":
    main()