2021-10-21 15:24:34 +03:00
|
|
|
import logging
|
|
|
|
import argparse
|
|
|
|
import sys
|
2022-11-02 18:15:40 +03:00
|
|
|
import colorlog
|
2021-10-21 15:24:34 +03:00
|
|
|
|
|
|
|
|
|
|
|
class App:
|
2022-04-13 23:50:25 +03:00
|
|
|
def __init__(self, no_exit=False):
|
2021-10-21 15:24:34 +03:00
|
|
|
# Argument Parser
|
2022-04-13 23:50:25 +03:00
|
|
|
self.no_exit = no_exit
|
2021-10-21 15:24:34 +03:00
|
|
|
self.parser = argparse.ArgumentParser()
|
|
|
|
self.parser.add_argument("-d", "--debug", action="store_true", help="Debug")
|
|
|
|
# Logging
|
2022-11-02 18:15:40 +03:00
|
|
|
self.logger = colorlog.getLogger()
|
2021-10-21 15:24:34 +03:00
|
|
|
# Application specific initialization
|
|
|
|
self.init()
|
|
|
|
|
2022-06-09 12:07:42 +03:00
|
|
|
def __call__(self, args=None, skip_logger_init=False):
|
2022-04-27 18:53:48 +03:00
|
|
|
self.args, self.other_args = self.parser.parse_known_args(args=args)
|
2021-10-21 15:24:34 +03:00
|
|
|
# configure log output
|
2022-06-09 12:07:42 +03:00
|
|
|
# if skip_logger_init:
|
2021-10-21 15:24:34 +03:00
|
|
|
self.log_level = logging.DEBUG if self.args.debug else logging.INFO
|
|
|
|
self.logger.setLevel(self.log_level)
|
2022-06-09 12:07:42 +03:00
|
|
|
if not self.logger.hasHandlers():
|
2022-11-02 18:15:40 +03:00
|
|
|
self.handler = colorlog.StreamHandler(sys.stdout)
|
2022-06-09 12:07:42 +03:00
|
|
|
self.handler.setLevel(self.log_level)
|
2022-11-02 18:15:40 +03:00
|
|
|
self.formatter = colorlog.ColoredFormatter(
|
|
|
|
"%(log_color)s%(asctime)s [%(levelname)s] %(message)s",
|
|
|
|
log_colors={
|
|
|
|
"DEBUG": "cyan",
|
|
|
|
# "INFO": "white",
|
|
|
|
"WARNING": "yellow",
|
|
|
|
"ERROR": "red",
|
|
|
|
"CRITICAL": "red,bg_white",
|
|
|
|
},
|
2022-06-09 12:07:42 +03:00
|
|
|
)
|
|
|
|
self.handler.setFormatter(self.formatter)
|
|
|
|
self.logger.addHandler(self.handler)
|
2021-10-21 15:24:34 +03:00
|
|
|
|
|
|
|
# execute requested function
|
|
|
|
self.before()
|
2022-03-03 12:48:56 +03:00
|
|
|
return_code = self.call()
|
2021-10-21 15:24:34 +03:00
|
|
|
self.after()
|
|
|
|
if isinstance(return_code, int):
|
2022-04-13 23:50:25 +03:00
|
|
|
return self._exit(return_code)
|
2021-10-21 15:24:34 +03:00
|
|
|
else:
|
|
|
|
self.logger.error(f"Missing return code")
|
2022-04-13 23:50:25 +03:00
|
|
|
return self._exit(255)
|
|
|
|
|
|
|
|
def _exit(self, code):
|
|
|
|
if self.no_exit:
|
|
|
|
return code
|
|
|
|
exit(code)
|
2021-10-21 15:24:34 +03:00
|
|
|
|
2022-03-03 12:48:56 +03:00
|
|
|
def call(self):
|
|
|
|
if "func" not in self.args:
|
|
|
|
self.parser.error("Choose something to do")
|
|
|
|
return self.args.func()
|
|
|
|
|
2021-10-21 15:24:34 +03:00
|
|
|
def init(self):
|
|
|
|
raise Exception("init() is not implemented")
|
|
|
|
|
|
|
|
def before(self):
|
|
|
|
pass
|
|
|
|
|
|
|
|
def after(self):
|
|
|
|
pass
|