jw.util.Cmds, .Cmd, .App: Use jw.pkg.lib.App + .Cmd

This commit does a couple of things in one go:

- Move the implementations from jw.util.Cmds and jw.util.Cmd back to
  jwutils where they came from to remain backwards compatible for
  code still using jwutils.

- No code uses jw.util.Cmds and jw.util.Cmd yet, so remove them.

- Add new jw.util.App and jw.util.Cmd classes instead, which are
  re-exported modules from jw.pkg.lib. These implementations are very
  similar, but not identical to jwutils.Cmds and jwutils.App.

Originally, Cmds and Cmd had been copied from jw-python to jw-pkg App
and Cmd, respectively, because an App class proved indispensible in
jw-pkg.  The two classes have subsequently evolved in jw-pkg, and
re-using them here ends the fork and removes the redundancy.

This makes jw-python expose the same App / Cmd pair as jw.pkg does
for as long as Cmds is still in use. In the future, it might be a
good idea to remove Cmds, Cmd and App from jw-python entirely.

Signed-off-by: Jan Lindemann <jan@janware.com>
This commit is contained in:
Jan Lindemann 2026-06-13 10:43:41 +02:00 • committed by janware DevOps
commit 8681317e8c
Signed by: DevOps
SSH key fingerprint: SHA256:cZiw7ExG5q3KAVm7Jse3rGITowu0VjgUgNMPbifmY8g
5 changed files with 306 additions and 297 deletions

View file

@ -0,0 +1,7 @@
from jw.pkg.lib.App import App as App
from jw.pkg.lib.App import run_sub_commands
__all__ = [
"App", # export
"run_sub_commands",
]

View file

@ -1,71 +1,5 @@
from __future__ import annotations
from jw.pkg.lib.Cmd import Cmd as Cmd
import abc
import argparse
import inspect
import re
import sys
from argparse import ArgumentParser
from typing import TYPE_CHECKING
from . import log
if TYPE_CHECKING:
from .Cmds import Cmds
# full blown example of one level of nested subcommands
# git -C project remote -v show -n myremote
class Cmd(abc.ABC): # export
@abc.abstractmethod
async def run(self, args):
pass
def __init__(self, name: str, help: str) -> None:
self.name = name
self.help = help
self.parent = None
self.children: list[Cmd] = []
self.child_classes: list[type[Cmd]] = []
self.app: Cmds | None = None
async def _run(self, args):
pass
def add_parser(self, parsers) -> ArgumentParser:
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: str | type[Cmd] | list[type[Cmd]]) -> None:
if isinstance(cmd, str):
sc = []
for name, obj in inspect.getmembers(sys.modules[self.__class__.__module__]):
if inspect.isclass(obj):
if re.search(cmd, str(obj)):
sc.append(obj)
log.slog(log.DEBUG, f"Found subcommand {obj}")
self.add_subcommands(sc)
return
if isinstance(cmd, list):
for c in cmd:
self.add_subcommands(c)
return
self.child_classes.append(cmd)
# To be overridden by derived class in case the command does take arguments.
# Will be called from App base class constructor and set up the parser hierarchy
def add_arguments(self, parser: ArgumentParser) -> None:
pass
def conf_value(self, path, default = None):
ret = None if self.app is None else self.app.conf_value(path, default)
if ret is None and default is not None:
return default
return ret
__all__ = [
"Cmd",
]

View file

@ -1,213 +0,0 @@
import argparse
import asyncio
import cProfile
import importlib
import inspect
import os
import re
import sys
from argparse import ArgumentParser
from pathlib import Path, PurePath
import argcomplete
from .log import DEBUG, ERR, NOTICE, add_log_file, set_flags, set_level, slog
from .stree import serdes
class Cmds: # export
def __instantiate(self, cls):
try:
r = cls()
except Exception as e:
slog(ERR, f'Failed to instantiate command of type {cls}: {e}')
raise
r.cmds = self # TODO: Rename Cmds class to App, "Cmds" isn't self-explanatory
r.app = self
return r
def __add_cmd_to_parser(self, cmd, parsers):
parser = cmd.add_parser(parsers)
cmd.add_arguments(parser)
if len(cmd.child_classes) > len(cmd.children):
for c in cmd.child_classes:
cmd.children.append(self.__instantiate(c))
if len(cmd.children) > 0:
subparsers = parser.add_subparsers(
title = 'Available subcommands of ' + cmd.name, metavar = ''
)
for sub_cmd in cmd.children:
self.__add_cmd_to_parser(sub_cmd, subparsers)
def __parse_config(self):
exe_stem = str(PurePath(sys.argv[0]).stem)
path = str(Path.home()) + '/.' + exe_stem + 'rc'
if not os.path.exists(path):
return None, []
slog(DEBUG, 'Reading configuration "{}"'.format(path))
return serdes.read(path, ''), [path]
def __init__(
self,
description: str = '',
filter: str = '^Cmd.*',
modules: None = None,
eloop: None = None
) -> None:
self.__description = description
self.__filter = filter
self.__modules = modules
self.__conf, self.__conf_paths = self.__parse_config()
self.__cmds = []
self.eloop = eloop
self.__own_eloop = False
if eloop is None:
self.eloop = asyncio.get_event_loop()
self.__own_eloop = True
log_level = "notice"
log_flags = 'stderr,position,prio,color'
log_file = None
# poor man's parsing in the absence of a complete command-line definition
for i in range(1, len(sys.argv)):
if i >= len(sys.argv) - 1:
break
arg = sys.argv[i]
if arg == '--log-level':
i += 1
log_level = sys.argv[i]
continue
if arg == '--log-flags':
log_flags = sys.argv[i]
continue
set_flags(log_flags)
set_level(log_level)
slog(DEBUG, "set log level to {}".format(log_level))
self.__parser = argparse.ArgumentParser(
usage = os.path.basename(sys.argv[0]) + ' [options]',
formatter_class = argparse.ArgumentDefaultsHelpFormatter,
description = self.__description
)
self.__parser.add_argument(
'--log-flags', help = 'Log flags', default = log_flags
)
self.__parser.add_argument(
'--log-level', help = 'Log level', default = log_level
)
self.__parser.add_argument(
'--backtrace',
help = 'Show exception backtraces',
action = 'store_true',
default = False
)
self.__parser.add_argument(
'--write-profile',
help = 'Profile code and store output to file',
default = None
)
self.__parser.add_argument('--log-file', help = 'Log file', default = log_file)
if self.__modules is None:
self.__modules = ['__main__']
subcmds = set()
slog(DEBUG, '-- searching for commands')
for m in self.__modules: # type: ignore
if m != '__main__':
importlib.import_module(m)
for name, c in inspect.getmembers(sys.modules[m], inspect.isclass):
if not re.match(self.__filter, name):
slog(DEBUG, 'o "{}.{}" has wrong name'.format(m, name))
continue
if inspect.isabstract(c):
slog(DEBUG, 'o "{}.{}" is abstract'.format(m, name))
continue
slog(DEBUG, 'o "{}.{}" is fine, instantiating'.format(m, name))
cmd = self.__instantiate(c)
#cmd.add_parser(subparsers)
self.__cmds.append(cmd)
subcmds.update(cmd.child_classes)
cmds = [cmd for cmd in self.__cmds if type(cmd) not in subcmds]
subparsers = self.__parser.add_subparsers(
title = 'Available commands', metavar = ''
)
for cmd in cmds:
slog(DEBUG, f'Adding top-level command {cmd} to parser')
self.__add_cmd_to_parser(cmd, subparsers)
# Run all sub-commands. Overwrite if you want to do anything before or after
async def _run(self, argv = None):
return await self.args.func(self.args)
async def __run(self, argv = None):
argcomplete.autocomplete(self.__parser)
self.args = self.__parser.parse_args(args = argv)
set_flags(self.args.log_flags)
set_level(self.args.log_level)
self.__back_trace = self.args.backtrace
exit_status = 0
# This is the toplevel parser, i.e. no func member has been added to the args
# yet, via
#
# Cmds.__init__()
# Cmds.__add_cmd_to_parser(cmd, subparsers)
# CmdXXX.add_parser(parsers)
# super().add_parser(parsers)
# Cmd.__parser.set_defaults(func=self.run)
#
if not hasattr(self.args, 'func'):
self.__parser.print_help()
return None
pr = None if self.args.write_profile is None else cProfile.Profile()
if pr is not None:
pr.enable()
if self.__conf:
self.__conf.dump(DEBUG, "Configuration")
if self.args.log_file is not None:
add_log_file(self.args.log_file)
try:
await self._run(self.args)
except Exception as e:
slog(ERR, f'Exception: {type(e)}: {str(e)}')
exit_status = 1
if self.__back_trace:
raise
finally:
if pr is not None:
assert self.args.write_profile is not None, 'args.write_profile'
pr.disable()
slog(NOTICE, f'Writing profile statistics to {self.args.write_profile}')
pr.dump_stats(self.args.write_profile)
if exit_status:
sys.exit(exit_status)
def __del__(self):
if self.__own_eloop:
if self.eloop is not None:
self.eloop.close()
self.eloop = None
self.__own_eloop = False
def conf_value(self, path, default = None):
ret = None if self.__conf is None else self.__conf.value(path)
if ret is None and default is not None:
return default
return ret
def parser(self) -> ArgumentParser:
return self.__parser
def run(self, argv = None) -> None:
#return self.__run()
return self.eloop.run_until_complete(self.__run(argv)) # type: ignore
def run_sub_commands( # export
description = '', filter = '^Cmd.*', modules = None, argv = None
):
cmds = Cmds(description, filter, modules)
return cmds.run(argv = argv)

View file

@ -1,6 +1,71 @@
# ruff: noqa: E501
from jw.util.Cmd import Cmd as Cmd
from __future__ import annotations
__all__ = [
"Cmd",
]
import abc
import argparse
import inspect
import re
import sys
from argparse import ArgumentParser
from typing import TYPE_CHECKING, Any
from . import log
if TYPE_CHECKING:
from .Cmds import Cmds
# full blown example of one level of nested subcommands
# git -C project remote -v show -n myremote
class Cmd(abc.ABC): # export
@abc.abstractmethod
async def run(self, args: Any) -> Any:
pass
def __init__(self, name: str, help: str) -> None:
self.name = name
self.help = help
self.parent = None
self.children: list[Cmd] = []
self.child_classes: list[type[Cmd]] = []
self.app: Cmds | None = None
async def _run(self, args: Any) -> Any:
pass
def add_parser(self, parsers: Any) -> ArgumentParser:
r = parsers.add_parser(
self.name,
help = self.help,
formatter_class = argparse.ArgumentDefaultsHelpFormatter
)
r.set_defaults(func = self.run)
return r # type: ignore[no-any-return]
def add_subcommands(self, cmd: str | type[Cmd] | list[type[Cmd]]) -> None:
if isinstance(cmd, str):
sc = []
for name, obj in inspect.getmembers(sys.modules[self.__class__.__module__]):
if inspect.isclass(obj):
if re.search(cmd, str(obj)):
sc.append(obj)
log.slog(log.DEBUG, f"Found subcommand {obj}")
self.add_subcommands(sc)
return
if isinstance(cmd, list):
for c in cmd:
self.add_subcommands(c)
return
self.child_classes.append(cmd)
# To be overridden by derived class in case the command does take arguments.
# Will be called from App base class constructor and set up the parser hierarchy
def add_arguments(self, parser: ArgumentParser) -> None:
pass
def conf_value(self, path: str, default: Any = None) -> Any:
ret = None if self.app is None else self.app.conf_value(path, default)
if ret is None and default is not None:
return default
return ret

View file

@ -1,8 +1,223 @@
# ruff: noqa: E501
from jw.util.Cmds import Cmds as Cmds
from jw.util.Cmds import run_sub_commands as run_sub_commands
from __future__ import annotations
__all__ = [
"Cmds",
"run_sub_commands",
]
import argparse
import asyncio
import cProfile
import importlib
import inspect
import os
import re
import sys
from argparse import ArgumentParser
from pathlib import Path, PurePath
import argcomplete
from .log import DEBUG, ERR, NOTICE, add_log_file, set_flags, set_level, slog
from .stree import serdes
from typing import TYPE_CHECKING, Any
if TYPE_CHECKING:
from .Cmd import Cmd
class Cmds: # export
def __instantiate(self, cls: Any) -> Any:
try:
r = cls()
except Exception as e:
slog(ERR, f'Failed to instantiate command of type {cls}: {e}')
raise
r.cmds = self # TODO: Rename Cmds class to App, "Cmds" isn't self-explanatory
r.app = self
return r
def __add_cmd_to_parser(self, cmd: "Cmd", parsers: Any) -> None:
parser = cmd.add_parser(parsers)
cmd.add_arguments(parser)
if len(cmd.child_classes) > len(cmd.children):
for c in cmd.child_classes:
cmd.children.append(self.__instantiate(c))
if len(cmd.children) > 0:
subparsers = parser.add_subparsers(
title = 'Available subcommands of ' + cmd.name, metavar = ''
)
for sub_cmd in cmd.children:
self.__add_cmd_to_parser(sub_cmd, subparsers)
def __parse_config(self) -> tuple[Any, list[str]]:
exe_stem = str(PurePath(sys.argv[0]).stem)
path = str(Path.home()) + '/.' + exe_stem + 'rc'
if not os.path.exists(path):
return None, []
slog(DEBUG, 'Reading configuration "{}"'.format(path))
return serdes.read(path, ''), [path]
def __init__(
self,
description: str = '',
filter: str = '^Cmd.*',
modules: list[str] | None = None,
eloop: asyncio.AbstractEventLoop | None = None
) -> None:
self.__description = description
self.__filter = filter
self.__modules = modules
self.__conf, self.__conf_paths = self.__parse_config()
self.__cmds = []
self.eloop = eloop
self.__own_eloop = False
if eloop is None:
self.eloop = asyncio.get_event_loop()
self.__own_eloop = True
log_level = "notice"
log_flags = 'stderr,position,prio,color'
log_file = None
# poor man's parsing in the absence of a complete command-line definition
for i in range(1, len(sys.argv)):
if i >= len(sys.argv) - 1:
break
arg = sys.argv[i]
if arg == '--log-level':
i += 1
log_level = sys.argv[i]
continue
if arg == '--log-flags':
log_flags = sys.argv[i]
continue
set_flags(log_flags)
set_level(log_level)
slog(DEBUG, "set log level to {}".format(log_level))
self.__parser = argparse.ArgumentParser(
usage = os.path.basename(sys.argv[0]) + ' [options]',
formatter_class = argparse.ArgumentDefaultsHelpFormatter,
description = self.__description
)
self.__parser.add_argument(
'--log-flags', help = 'Log flags', default = log_flags
)
self.__parser.add_argument(
'--log-level', help = 'Log level', default = log_level
)
self.__parser.add_argument(
'--backtrace',
help = 'Show exception backtraces',
action = 'store_true',
default = False
)
self.__parser.add_argument(
'--write-profile',
help = 'Profile code and store output to file',
default = None
)
self.__parser.add_argument('--log-file', help = 'Log file', default = log_file)
if self.__modules is None:
self.__modules = ['__main__']
subcmds = set()
slog(DEBUG, '-- searching for commands')
for m in self.__modules:
if m != '__main__':
importlib.import_module(m)
for name, c in inspect.getmembers(sys.modules[m], inspect.isclass):
if not re.match(self.__filter, name):
slog(DEBUG, 'o "{}.{}" has wrong name'.format(m, name))
continue
if inspect.isabstract(c):
slog(DEBUG, 'o "{}.{}" is abstract'.format(m, name))
continue
slog(DEBUG, 'o "{}.{}" is fine, instantiating'.format(m, name))
cmd = self.__instantiate(c)
#cmd.add_parser(subparsers)
self.__cmds.append(cmd)
subcmds.update(cmd.child_classes)
cmds = [cmd for cmd in self.__cmds if type(cmd) not in subcmds]
subparsers = self.__parser.add_subparsers(
title = 'Available commands', metavar = ''
)
for cmd in cmds:
slog(DEBUG, f'Adding top-level command {cmd} to parser')
self.__add_cmd_to_parser(cmd, subparsers)
# Run all sub-commands. Overwrite if you want to do anything before or after
async def _run(self, args: Any) -> None:
return await self.args.func(self.args) # type: ignore[no-any-return]
async def __run(self, argv: list[str] | None = None) -> None:
argcomplete.autocomplete(self.__parser)
self.args = self.__parser.parse_args(args = argv)
set_flags(self.args.log_flags)
set_level(self.args.log_level)
self.__back_trace = self.args.backtrace
exit_status = 0
# This is the toplevel parser, i.e. no func member has been added to the args
# yet, via
#
# Cmds.__init__()
# Cmds.__add_cmd_to_parser(cmd, subparsers)
# CmdXXX.add_parser(parsers)
# super().add_parser(parsers)
# Cmd.__parser.set_defaults(func=self.run)
#
if not hasattr(self.args, 'func'):
self.__parser.print_help()
return None
pr = None if self.args.write_profile is None else cProfile.Profile()
if pr is not None:
pr.enable()
if self.__conf:
self.__conf.dump(DEBUG, "Configuration")
if self.args.log_file is not None:
add_log_file(self.args.log_file)
try:
await self._run(self.args)
except Exception as e:
slog(ERR, f'Exception: {type(e)}: {str(e)}')
exit_status = 1
if self.__back_trace:
raise
finally:
if pr is not None:
assert self.args.write_profile is not None, 'args.write_profile'
pr.disable()
slog(NOTICE, f'Writing profile statistics to {self.args.write_profile}')
pr.dump_stats(self.args.write_profile)
if exit_status:
sys.exit(exit_status)
def __del__(self) -> None:
if self.__own_eloop:
if self.eloop is not None:
self.eloop.close()
self.eloop = None
self.__own_eloop = False
def conf_value(self, path: str, default: Any = None) -> Any:
ret = None if self.__conf is None else self.__conf.value(path)
if ret is None and default is not None:
return default
return ret
def parser(self) -> ArgumentParser:
return self.__parser
def run(self, argv: list[str] | None = None) -> None:
#return self.__run()
self.eloop.run_until_complete(self.__run(argv)) # type: ignore[union-attr]
def run_sub_commands( # export
description: str = '',
filter: str = '^Cmd.*',
modules: list[str] | None = None,
argv: list[str] | None = None,
) -> None:
cmds = Cmds(description, filter, modules)
return cmds.run(argv = argv)