mirror of
ssh://git.janware.com/srv/git/janware/proj/jw-python
synced 2026-01-15 09:53:32 +01:00
Add method jwutils.Cmd.add_subcommands(). cmd.add_subcommands(C) will parse and invoke C as a subcommand of cmd, if C is of type jwutils.cmd. Signed-off-by: Jan Lindemann <jan@janware.com>
42 lines
1 KiB
Python
42 lines
1 KiB
Python
import abc
|
|
import argparse
|
|
|
|
from jwutils import log
|
|
|
|
# compatible with Python 2 *and* 3
|
|
ABC = abc.ABCMeta('ABC', (object,), {'__slots__': ()})
|
|
|
|
# full blown example of one level of nested subcommands
|
|
# git -C project remote -v show -n myremote
|
|
|
|
class Cmd(ABC): # export
|
|
|
|
@abc.abstractmethod
|
|
async def run(self, args):
|
|
pass
|
|
|
|
def __init__(self, name, help):
|
|
self.name = name
|
|
self.help = help
|
|
self.parent = None
|
|
self.children = []
|
|
self.child_classes = []
|
|
|
|
async def _run(self, args):
|
|
pass
|
|
|
|
def add_parser(self, parsers):
|
|
r = parsers.add_parser(self.name, help=self.help,
|
|
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
|
|
r.set_defaults(func=self.run)
|
|
return r
|
|
|
|
def add_subcommands(self, cmd):
|
|
if isinstance(cmd, list):
|
|
for c in cmd:
|
|
self.add_subcommands(c)
|
|
return
|
|
self.child_classes.append(cmd)
|
|
|
|
def add_arguments(self, parser):
|
|
pass
|