improvement -> all suported types now display a 'Checking configuration file' task during the initialization process

This commit is contained in:
Vinicius Moreira
2020-12-30 13:35:15 -03:00
parent 01bd532465
commit c91e982243
69 changed files with 1059 additions and 561 deletions

57
bauh/commons/boot.py Normal file
View File

@@ -0,0 +1,57 @@
import time
from logging import Logger
from threading import Thread
from typing import Optional
from bauh.api.abstract.handler import TaskManager
from bauh.commons.config import ConfigManager
from bauh.view.util.translation import I18n
class CreateConfigFile(Thread):
"""
Generic initialization task to create a configuration file
"""
def __init__(self, configman: ConfigManager, taskman: TaskManager, task_icon_path: str, i18n: I18n, logger: Logger, config_instance: Optional[dict] = None):
super(CreateConfigFile, self).__init__(daemon=True)
self.configman = configman
self.taskman = taskman
self.logger = logger
self.config = config_instance
self.task_icon_path = task_icon_path
self.task_id = configman.__class__.__name__
self.i18n = i18n
self.task_name = self.i18n['task.checking_config']
self.taskman.register_task(self.task_id, self.task_name, self.task_icon_path)
def _log(self, msg: str):
self.logger.info('{}: {}'.format(self.configman.__class__.__name__, msg))
def run(self):
ti = time.time()
self.taskman.update_progress(self.task_id, 1, None)
self._log("Reading cached configuration file")
default_config = self.configman.get_default_config()
cached_config = self.configman.read_config()
self.taskman.update_progress(self.task_id, 50, None)
if cached_config:
self._log("Merging configuration file")
self.configman.merge_config(default_config, cached_config)
else:
self._log("No cached configuration file found")
self.config = default_config
self.taskman.update_progress(self.task_id, 75, self.i18n['task.checking_config.saving'])
self._log("Writing configuration file")
self.configman.save_config(default_config)
self.taskman.update_progress(self.task_id, 100, None)
self.taskman.finish_task(self.task_id)
tf = time.time()
self._log("Finished. Took {0:.2f} seconds".format(tf - ti))

View File

@@ -18,8 +18,8 @@ from bauh.commons.util import map_timestamp_file
class CategoriesDownloader(Thread):
def __init__(self, id_: str, http_client: HttpClient, logger: logging.Logger, manager: SoftwareManager,
url_categories_file: str, categories_path: str, expiration: int, internet_checker: InternetChecker,
internet_connection: Optional[bool] = True, before=None, after=None):
url_categories_file: str, categories_path: str, internet_checker: InternetChecker,
expiration: Optional[int] = None, internet_connection: Optional[bool] = True, before=None, after=None):
"""
:param id_:
:param http_client:
@@ -121,7 +121,7 @@ class CategoriesDownloader(Thread):
self.logger.warning(self._msg("No internet connection. The categories file '{}' cannot be updated.".format(self.categories_path)))
return False
if self.expiration <= 0:
if self.expiration is None or self.expiration <= 0:
self.logger.warning(self._msg("No expiration set for the categories file '{}'. It should be downloaded".format(self.categories_path)))
return True

View File

@@ -1,6 +1,9 @@
import os
import traceback
from abc import abstractmethod, ABC
from pathlib import Path
from threading import Thread
from typing import Optional
import yaml
@@ -31,3 +34,69 @@ def read_config(file_path: str, template: dict, update_file: bool = False, updat
def save_config(config: dict, file_path: str):
with open(file_path, 'w+') as f:
f.write(yaml.dump(config))
class ConfigManager(ABC):
@abstractmethod
def read_config(self) -> Optional[dict]:
pass
@abstractmethod
def get_default_config(self) -> dict:
pass
@abstractmethod
def is_config_cached(self) -> bool:
pass
def get_config(self) -> dict:
default_config = self.get_default_config()
if default_config:
cached_config = self.read_config()
if cached_config:
self.merge_config(default_config, cached_config)
return default_config
@staticmethod
def merge_config(base_config: dict, current_config: dict):
util.deep_update(base_config, current_config)
@abstractmethod
def save_config(self, config_obj: dict):
pass
class YAMLConfigManager(ConfigManager, ABC):
def __init__(self, config_file_path: str):
self.file_path = config_file_path
def is_config_cached(self) -> bool:
return os.path.exists(self.file_path)
def read_config(self) -> Optional[dict]:
if self.is_config_cached():
with open(self.file_path) as f:
local_config = yaml.safe_load(f.read())
if local_config is not None:
return local_config
def save_config(self, config_obj: dict):
if config_obj:
config_dir = os.path.dirname(self.file_path)
try:
Path(config_dir).mkdir(parents=True, exist_ok=True)
except OSError:
traceback.print_exc()
return
try:
with open(self.file_path, 'w+') as f:
f.write(yaml.dump(config_obj))
except:
traceback.print_exc()