lib.App: Add root command slot #66
1 changed files with 17 additions and 16 deletions
lib.App.add_cmd_to_parser -> .make_sub_parser()
Code beautification: add_cmd_to_parser() isn't very telling about its return type and the fact that it creates an object, hence the name change. Also, annotate its argument with a private argparse type to avoid a cast. My concern that argparse will break the private type at some point in the future is outweighed by the gained clode clarity in this function. Signed-off-by: Jan Lindemann <jan@janware.com>
commit
24e3059d92
|
|
@ -6,7 +6,9 @@ import os
|
|||
import sys
|
||||
import warnings
|
||||
|
||||
from argparse import ArgumentDefaultsHelpFormatter, ArgumentParser, Namespace
|
||||
from argparse import (
|
||||
ArgumentDefaultsHelpFormatter, ArgumentParser, Namespace, _SubParsersAction
|
||||
)
|
||||
from typing import TYPE_CHECKING, Any, NamedTuple, cast, override
|
||||
|
||||
from .AsyncRunner import AsyncRunner
|
||||
|
|
@ -151,21 +153,20 @@ class App: # export
|
|||
|
||||
def _build_parser(self, argv: list[str] | None = None) -> None:
|
||||
|
||||
def add_cmd_to_parser(cmd: AbstractCmd, parsers: Any) -> ArgumentParser:
|
||||
parser = cast(
|
||||
'ArgumentParser',
|
||||
parsers.add_parser(
|
||||
cmd.name,
|
||||
help = cmd.help,
|
||||
description = cmd.description,
|
||||
aliases = cmd.aliases,
|
||||
formatter_class = ArgumentDefaultsHelpFormatter,
|
||||
)
|
||||
def make_sub_parser(
|
||||
cmd: AbstractCmd, parsers: _SubParsersAction[ArgumentParser]
|
||||
) -> ArgumentParser:
|
||||
ret = parsers.add_parser(
|
||||
cmd.name,
|
||||
help = cmd.help,
|
||||
description = cmd.description,
|
||||
aliases = cmd.aliases,
|
||||
formatter_class = ArgumentDefaultsHelpFormatter,
|
||||
)
|
||||
parser.set_defaults(func = cmd.run)
|
||||
cmd.add_arguments(parser)
|
||||
cmd.set_parser(parser)
|
||||
return parser
|
||||
ret.set_defaults(func = cmd.run)
|
||||
cmd.add_arguments(ret)
|
||||
cmd.set_parser(ret)
|
||||
return ret
|
||||
|
||||
def add_cmds_to_parser(
|
||||
parent: AbstractCmd | App,
|
||||
|
|
@ -187,7 +188,7 @@ class App: # export
|
|||
cmd.set_parent(parent)
|
||||
if cmd.name in scs:
|
||||
log(WARNING, f'Duplicate subcommand name: {cmd.name}')
|
||||
scs[cmd.name] = _SubCommand(cmd, add_cmd_to_parser(cmd, subparsers))
|
||||
scs[cmd.name] = _SubCommand(cmd, make_sub_parser(cmd, subparsers))
|
||||
for alias in cmd.aliases:
|
||||
if alias != cmd.name and alias in scs:
|
||||
log(
|
||||
|
|
|
|||
Loading…
Reference in a new issue