cli fixup

This commit is contained in:
Lex Berezhny 2019-01-24 18:22:53 -05:00
parent ed61c7feec
commit 7a601db23f
3 changed files with 87 additions and 14 deletions

View file

@ -52,10 +52,12 @@ HEADERS_FILE_SHA256_CHECKSUM = (
class Setting(typing.Generic[T]): class Setting(typing.Generic[T]):
def __init__(self, doc: str, default: typing.Optional[T] = None, def __init__(self, doc: str, default: typing.Optional[T] = None,
previous_names: typing.Optional[typing.List[str]] = None): previous_names: typing.Optional[typing.List[str]] = None,
metavar: typing.Optional[str] = None):
self.doc = doc self.doc = doc
self.default = default self.default = default
self.previous_names = previous_names or [] self.previous_names = previous_names or []
self.metavar = metavar
def __set_name__(self, owner, name): def __set_name__(self, owner, name):
self.name = name self.name = name
@ -343,7 +345,8 @@ class BaseConfig:
else: else:
parser.add_argument( parser.add_argument(
f"--{setting.name.replace('_', '-')}", f"--{setting.name.replace('_', '-')}",
help=setting.doc help=setting.doc,
metavar=setting.metavar
) )
def set_arguments(self, args): def set_arguments(self, args):
@ -371,7 +374,7 @@ class BaseConfig:
class CLIConfig(BaseConfig): class CLIConfig(BaseConfig):
api = String('Host name and port for lbrynet daemon API.', 'localhost:5279') api = String('Host name and port for lbrynet daemon API.', 'localhost:5279', metavar='HOST:PORT')
@property @property
def api_connection_url(self) -> str: def api_connection_url(self) -> str:

View file

@ -76,12 +76,77 @@ def set_kwargs(parsed_args):
return kwargs return kwargs
def split_subparser_argument(parent, original, name, condition):
new_sub_parser = argparse._SubParsersAction(
original.option_strings,
original._prog_prefix,
original._parser_class,
metavar=original.metavar
)
new_sub_parser._name_parser_map = original._name_parser_map
new_sub_parser._choices_actions = [
a for a in original._choices_actions if condition(original._name_parser_map[a.dest])
]
group = argparse._ArgumentGroup(parent, name)
group._group_actions = [new_sub_parser]
return group
class ArgumentParser(argparse.ArgumentParser): class ArgumentParser(argparse.ArgumentParser):
def __init__(self, *args, **kwargs): def __init__(self, *args, group_name=None, **kwargs):
super().__init__(*args, add_help=False, **kwargs) super().__init__(*args, formatter_class=HelpFormatter, add_help=False, **kwargs)
self.add_argument( self.add_argument(
'--help', dest='help', action='store_true', default=False, '--help', dest='help', action='store_true', default=False,
help='show this help message and exit' help='Show this help message and exit.'
)
self._optionals.title = 'Options'
if group_name is None:
self.epilog = (
f"Run 'lbrynet COMMAND --help' for more information on a command or group."
)
else:
self.epilog = (
f"Run 'lbrynet {group_name} COMMAND --help' for more information on a command."
)
self.set_defaults(group=group_name, group_parser=self)
def format_help(self):
formatter = self._get_formatter()
formatter.add_usage(
self.usage, self._actions, self._mutually_exclusive_groups
)
formatter.add_text(self.description)
# positionals, optionals and user-defined groups
for action_group in self._granular_action_groups:
formatter.start_section(action_group.title)
formatter.add_text(action_group.description)
formatter.add_arguments(action_group._group_actions)
formatter.end_section()
formatter.add_text(self.epilog)
return formatter.format_help()
@property
def _granular_action_groups(self):
if self.prog != 'lbrynet':
yield from self._action_groups
return
yield self._optionals
action: argparse._SubParsersAction = self._positionals._group_actions[0]
yield split_subparser_argument(
self, action, "Grouped Commands", lambda parser: 'group' in parser._defaults
)
yield split_subparser_argument(
self, action, "Commands", lambda parser: 'group' not in parser._defaults
)
class HelpFormatter(argparse.HelpFormatter):
def add_usage(self, usage, actions, groups, prefix='Usage: '):
super().add_usage(
usage, [a for a in actions if a.option_strings != ['--help']], groups, prefix
) )
@ -101,13 +166,13 @@ def add_command_parser(parent, command):
def get_argument_parser(): def get_argument_parser():
main = ArgumentParser('lbrynet') main = ArgumentParser('lbrynet')
main.add_argument( main.add_argument(
'--version', dest='cli_version', action="store_true", '-v', '--version', dest='cli_version', action="store_true",
help='Show lbrynet CLI version and exit.' help='Show lbrynet CLI version and exit.'
) )
main.set_defaults(group=None, command=None) main.set_defaults(group=None, command=None)
CLIConfig.contribute_args(main) CLIConfig.contribute_args(main)
sub = main.add_subparsers() sub = main.add_subparsers(metavar='COMMAND')
start = sub.add_parser('start', help='Start lbrynet server.') start = sub.add_parser('start', usage='lbrynet start [OPTIONS]', help='Start lbrynet API server.')
start.add_argument( start.add_argument(
'--quiet', dest='quiet', action="store_true", '--quiet', dest='quiet', action="store_true",
help='Disable all console output.' help='Disable all console output.'
@ -123,10 +188,15 @@ def get_argument_parser():
api = Daemon.get_api_definitions() api = Daemon.get_api_definitions()
groups = {} groups = {}
for group_name in sorted(api['groups']): for group_name in sorted(api['groups']):
group_parser = sub.add_parser(group_name, help=api['groups'][group_name]) group_parser = sub.add_parser(group_name, group_name=group_name, help=api['groups'][group_name])
group_parser.set_defaults(group=group_name, group_parser=group_parser) groups[group_name] = group_parser.add_subparsers(metavar='COMMAND')
groups[group_name] = group_parser.add_subparsers()
nicer_order = ['stop', 'get', 'publish', 'resolve', 'resolve_name']
for command_name in sorted(api['commands']): for command_name in sorted(api['commands']):
if command_name not in nicer_order:
nicer_order.append(command_name)
for command_name in nicer_order:
command = api['commands'][command_name] command = api['commands'][command_name]
if command['group'] is None: if command['group'] is None:
add_command_parser(sub, command) add_command_parser(sub, command)

View file

@ -583,7 +583,7 @@ class Daemon(metaclass=JSONRPCServerType):
def jsonrpc_stop(self): def jsonrpc_stop(self):
""" """
Stop lbrynet Stop lbrynet API server.
Usage: Usage:
stop stop
@ -688,7 +688,7 @@ class Daemon(metaclass=JSONRPCServerType):
def jsonrpc_version(self): def jsonrpc_version(self):
""" """
Get lbry version information Get lbrynet API server version information
Usage: Usage:
version version