~brenns10/subc

fb16a06f2e6c4ab4f489ef7ac52390a0819c3b66 — Stephen Brennan 2 years ago abf9c7d v0.3.0
Allow a default subcommand to be set, v0.3.0
2 files changed, 12 insertions(+), 7 deletions(-)

M setup.py
M subc.py
M setup.py => setup.py +1 -1
@@ 4,7 4,7 @@ long_description = open('README.rst').read()

setup(
    name='subc',
    version='0.2.0',
    version='0.3.0',
    description='CLI sub-command library',
    long_description=long_description,
    url='https://git.sr.ht/~brenns10/subc',

M subc.py => subc.py +11 -6
@@ 60,8 60,9 @@ class Command(ABC):
        return self.run()

    @classmethod
    def add_commands(cls, parser):
    def add_commands(cls, parser, default=None):
        # type: (argparse.ArgumentParser) -> None
        default_set = False
        subparsers = parser.add_subparsers(title='sub-command')
        subclasses = collections.deque(cls.__subclasses__())
        while subclasses:


@@ 78,16 79,20 @@ class Command(ABC):
                )
                cmd.add_args(cmd_parser)
                cmd_parser.set_defaults(func=cmd.base_run)
                if cmd.name == default:
                    parser.set_defaults(func=cmd.base_run)
                    default_set = True

        def default(*args, **kwargs):
            raise Exception('you must select a sub-command')
        parser.set_defaults(func=default)
        if not default_set:
            def default(*args, **kwargs):
                raise Exception('you must select a sub-command')
            parser.set_defaults(func=default)
        return parser

    @classmethod
    def main(cls, description):
    def main(cls, description, default=None):
        # type: (str) -> None
        parser = argparse.ArgumentParser(description=description)
        cls.add_commands(parser)
        cls.add_commands(parser, default=default)
        args = parser.parse_args()
        args.func(args)