jwutils.Cmd: Add method add_subcommands()

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>
This commit is contained in:
Jan Lindemann 2020-04-04 16:32:39 +02:00
commit c5b964a5bb
2 changed files with 41 additions and 3 deletions

View file

@ -1,9 +1,14 @@
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
@ -13,6 +18,9 @@ class Cmd(ABC): # export
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
@ -23,3 +31,12 @@ class Cmd(ABC): # export
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