2021-10-21 12:24:34 +00:00
|
|
|
import logging
|
|
|
|
import argparse
|
|
|
|
import sys
|
2022-11-02 15:15:40 +00:00
|
|
|
import colorlog
|
2021-10-21 12:24:34 +00:00
|
|
|
|
|
|
|
|
|
|
|
class App:
|
2022-04-13 20:50:25 +00:00
|
|
|
def __init__(self, no_exit=False):
|
2021-10-21 12:24:34 +00:00
|
|
|
# Argument Parser
|
2022-04-13 20:50:25 +00:00
|
|
|
self.no_exit = no_exit
|
2021-10-21 12:24:34 +00:00
|
|
|
self.parser = argparse.ArgumentParser()
|
|
|
|
self.parser.add_argument("-d", "--debug", action="store_true", help="Debug")
|
|
|
|
# Logging
|
2022-11-02 15:15:40 +00:00
|
|
|
self.logger = colorlog.getLogger()
|
2021-10-21 12:24:34 +00:00
|
|
|
# Application specific initialization
|
|
|
|
self.init()
|
|
|
|
|
2022-06-09 09:07:42 +00:00
|
|
|
def __call__(self, args=None, skip_logger_init=False):
|
2022-04-27 15:53:48 +00:00
|
|
|
self.args, self.other_args = self.parser.parse_known_args(args=args)
|
2021-10-21 12:24:34 +00:00
|
|
|
# configure log output
|
2022-06-09 09:07:42 +00:00
|
|
|
# if skip_logger_init:
|
2021-10-21 12:24:34 +00:00
|
|
|
self.log_level = logging.DEBUG if self.args.debug else logging.INFO
|
|
|
|
self.logger.setLevel(self.log_level)
|
2022-06-09 09:07:42 +00:00
|
|
|
if not self.logger.hasHandlers():
|
2022-11-02 15:15:40 +00:00
|
|
|
self.handler = colorlog.StreamHandler(sys.stdout)
|
2022-06-09 09:07:42 +00:00
|
|
|
self.handler.setLevel(self.log_level)
|
2022-11-02 15:15:40 +00: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 09:07:42 +00:00
|
|
|
)
|
|
|
|
self.handler.setFormatter(self.formatter)
|
|
|
|
self.logger.addHandler(self.handler)
|
2021-10-21 12:24:34 +00:00
|
|
|
|
|
|
|
# execute requested function
|
|
|
|
self.before()
|
2022-03-03 09:48:56 +00:00
|
|
|
return_code = self.call()
|
2021-10-21 12:24:34 +00:00
|
|
|
self.after()
|
|
|
|
if isinstance(return_code, int):
|
2022-04-13 20:50:25 +00:00
|
|
|
return self._exit(return_code)
|
2021-10-21 12:24:34 +00:00
|
|
|
else:
|
2023-05-03 05:48:49 +00:00
|
|
|
self.logger.error("Missing return code")
|
2022-04-13 20:50:25 +00:00
|
|
|
return self._exit(255)
|
|
|
|
|
|
|
|
def _exit(self, code):
|
|
|
|
if self.no_exit:
|
|
|
|
return code
|
|
|
|
exit(code)
|
2021-10-21 12:24:34 +00:00
|
|
|
|
2022-03-03 09:48:56 +00:00
|
|
|
def call(self):
|
|
|
|
if "func" not in self.args:
|
|
|
|
self.parser.error("Choose something to do")
|
|
|
|
return self.args.func()
|
|
|
|
|
2021-10-21 12:24:34 +00:00
|
|
|
def init(self):
|
|
|
|
raise Exception("init() is not implemented")
|
|
|
|
|
|
|
|
def before(self):
|
|
|
|
pass
|
|
|
|
|
|
|
|
def after(self):
|
|
|
|
pass
|