kiwi-scp/src/kiwi/parser.py

64 lines
1.8 KiB
Python
Raw Normal View History

2020-08-12 15:46:50 +00:00
# system
2020-08-06 11:43:45 +00:00
import argparse
2020-08-18 15:50:13 +00:00
# local
from ._constants import COMMAND_HELP_TEXT_NAME
2020-08-06 11:43:45 +00:00
class Parser:
2020-08-13 08:48:01 +00:00
"""Singleton: Main CLI arguments parser"""
2020-08-10 13:21:39 +00:00
class __Parser:
2020-08-13 08:48:01 +00:00
"""Singleton type"""
# argparse objects
2020-08-10 13:21:39 +00:00
__parser = None
__subparsers = None
__args = None
2020-08-06 11:43:45 +00:00
2020-08-10 13:21:39 +00:00
def __init__(self):
2020-08-18 15:50:13 +00:00
# add version data from separate file (keeps default config cleaner)
with open(COMMAND_HELP_TEXT_NAME, 'r') as stream:
command_help_text = stream.read().strip()
# create main parser
2020-08-13 08:48:01 +00:00
self.__parser = argparse.ArgumentParser(
2020-08-18 15:50:13 +00:00
description='kiwi-config',
usage='%(prog)s [command]',
epilog=command_help_text,
2020-08-13 08:48:01 +00:00
)
2020-08-18 15:50:13 +00:00
self.__parser.formatter_class = argparse.RawDescriptionHelpFormatter
2020-08-06 11:43:45 +00:00
2020-08-13 08:48:01 +00:00
# main arguments
2020-08-11 12:03:00 +00:00
self.__parser.add_argument(
'-v', '--verbosity',
action='count', default=0
)
2020-08-13 08:48:01 +00:00
# attach subparsers
2020-08-10 13:21:39 +00:00
self.__subparsers = self.__parser.add_subparsers()
self.__subparsers.required = True
self.__subparsers.dest = 'command'
2020-08-06 11:43:45 +00:00
2020-08-10 13:21:39 +00:00
def get_subparsers(self):
return self.__subparsers
2020-08-06 11:43:45 +00:00
2020-08-10 13:21:39 +00:00
def get_args(self):
if self.__args is None:
2020-08-13 08:48:01 +00:00
# parse args if needed
self.__args, unknowns = self.__parser.parse_known_args()
self.__args.unknowns = unknowns
2020-08-06 11:43:45 +00:00
2020-08-10 13:21:39 +00:00
return self.__args
__instance = None
def __init__(self):
if Parser.__instance is None:
2020-08-13 08:48:01 +00:00
# create singleton
2020-08-10 13:21:39 +00:00
Parser.__instance = Parser.__Parser()
def __getattr__(self, item):
2020-08-13 08:48:01 +00:00
"""Inner singleton direct access"""
return getattr(self.__instance, item)