File: main.py

package info (click to toggle)
python-asdf 2.14.3-1%2Bdeb12u1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 2,280 kB
  • sloc: python: 16,612; makefile: 124
file content (80 lines) | stat: -rw-r--r-- 1,894 bytes parent folder | download
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import argparse
import logging
import sys

from .. import util

# This list is ordered in order of average workflow
command_order = ["Explode", "Implode"]


class Command:
    @classmethod
    def setup_arguments(cls, subparsers):
        raise NotImplementedError()

    @classmethod
    def run(cls, args):
        raise NotImplementedError()


def make_argparser():
    """
    Most of the real work is handled by the subcommands in the
    commands subpackage.
    """

    def help(args):
        parser.print_help()
        return 0

    parser = argparse.ArgumentParser("asdftool", description="Commandline utilities for managing ASDF files.")

    parser.add_argument("--verbose", "-v", action="store_true", help="Increase verbosity")

    subparsers = parser.add_subparsers(title="subcommands", description="valid subcommands")

    help_parser = subparsers.add_parser("help", help="Display usage information")
    help_parser.set_defaults(func=help)

    commands = {x.__name__: x for x in util.iter_subclasses(Command)}

    for command in command_order:
        commands[str(command)].setup_arguments(subparsers)
        del commands[command]

    for name, command in sorted(commands.items()):
        command.setup_arguments(subparsers)

    return parser, subparsers


def main_from_args(args):
    parser, subparsers = make_argparser()

    args = parser.parse_args(args)

    # Only needed for Python 3, apparently, but can't hurt
    if not hasattr(args, "func"):
        parser.print_help()
        return 2

    try:
        result = args.func(args)
    except RuntimeError as e:
        logging.error(str(e))
        return 1
    except OSError as e:
        logging.error(str(e))
        return e.errno

    if result is None:
        result = 0

    return result


def main(args=None):
    if args is None:
        args = sys.argv[1:]
    sys.exit(main_from_args(args))