mdrs-client-python/mdrsclient/commands/config.py

70 lines
2.9 KiB
Python
Raw Normal View History

2023-05-01 20:00:32 +09:00
from argparse import Namespace, _SubParsersAction
from mdrsclient.commands.base import BaseCommand
from mdrsclient.commands.utils import parse_remote_host
from mdrsclient.config import ConfigFile
from mdrsclient.exceptions import IllegalArgumentException
class ConfigCommand(BaseCommand):
@staticmethod
def register(top_level_subparsers: _SubParsersAction) -> None:
# config
parser = top_level_subparsers.add_parser("config", help="configure remote hosts")
parser.set_defaults(func=lambda x: parser.print_help())
subparsers = parser.add_subparsers(title="config subcommands")
# config create
create_parser = subparsers.add_parser("create", help="create a new remote host")
create_parser.add_argument("remote", help="Label of remote host")
create_parser.add_argument("url", help="API entrypoint url of remote host")
create_parser.set_defaults(func=ConfigCommand.create)
# config update
update_parser = subparsers.add_parser("update", help="update a new remote host")
update_parser.add_argument("remote", help="Label of remote host")
update_parser.add_argument("url", help="API entrypoint url of remote host")
update_parser.set_defaults(func=ConfigCommand.update)
# config list
list_parser = subparsers.add_parser("list", help="list all the remote hosts")
list_parser.add_argument("-l", "--long", help="Show the api url", action="store_true")
list_parser.set_defaults(func=ConfigCommand.list)
# config delete
delete_parser = subparsers.add_parser("delete", help="delete an existing remote host")
delete_parser.add_argument("remote", help="Label of remote host")
delete_parser.set_defaults(func=ConfigCommand.delete)
@staticmethod
def create(args: Namespace) -> None:
remote = parse_remote_host(args.remote)
config = ConfigFile(remote=remote)
if config.url is not None:
raise IllegalArgumentException(f"Remote host `{remote}` is already exists.")
else:
config.url = args.url
@staticmethod
def update(args: Namespace) -> None:
remote = parse_remote_host(args.remote)
config = ConfigFile(remote=remote)
if config.url is None:
raise IllegalArgumentException(f"Remote host `{remote}` is not exists.")
else:
config.url = args.url
@staticmethod
def list(args: Namespace) -> None:
config = ConfigFile("")
for remote, url in config.list():
line = f"{remote}:"
if args.long:
line += f"\t{url}"
print(line)
@staticmethod
def delete(args: Namespace) -> None:
remote = parse_remote_host(args.remote)
config = ConfigFile(remote=remote)
if config.url is None:
raise IllegalArgumentException(f"Remote host `{remote}` is not exists.")
else:
del config.url