2021-10-21 12:24:34 +00:00
|
|
|
import logging
|
|
|
|
import argparse
|
|
|
|
import sys
|
|
|
|
|
|
|
|
|
|
|
|
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
|
|
|
|
self.logger = logging.getLogger()
|
|
|
|
# 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():
|
|
|
|
self.handler = logging.StreamHandler(sys.stdout)
|
|
|
|
self.handler.setLevel(self.log_level)
|
|
|
|
self.formatter = logging.Formatter(
|
|
|
|
"%(asctime)s [%(levelname)s] %(message)s"
|
|
|
|
)
|
|
|
|
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:
|
|
|
|
self.logger.error(f"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
|