refactor(settings): use SimpleConfigParser for KiauhSettings

Signed-off-by: Dominik Willner <th33xitus@gmail.com>
This commit is contained in:
dw-0
2024-06-19 20:12:39 +02:00
parent c2dfabb326
commit 5c090e88c3
8 changed files with 158 additions and 84 deletions

View File

@@ -121,7 +121,7 @@ def update_crowsnest() -> None:
Logger.print_status("Updating Crowsnest ...") Logger.print_status("Updating Crowsnest ...")
settings = KiauhSettings() settings = KiauhSettings()
if settings.get("kiauh", "backup_before_update"): if settings.kiauh.backup_before_update:
bm = BackupManager() bm = BackupManager()
bm.backup_directory( bm.backup_directory(
"crowsnest", "crowsnest",

View File

@@ -109,8 +109,8 @@ def install_klipper() -> None:
def setup_klipper_prerequesites() -> None: def setup_klipper_prerequesites() -> None:
settings = KiauhSettings() settings = KiauhSettings()
repo = settings.get("klipper", "repo_url") repo = settings.klipper.repo_url
branch = settings.get("klipper", "branch") branch = settings.klipper.branch
git_clone_wrapper(repo, KLIPPER_DIR, branch) git_clone_wrapper(repo, KLIPPER_DIR, branch)
@@ -144,13 +144,13 @@ def update_klipper() -> None:
return return
settings = KiauhSettings() settings = KiauhSettings()
if settings.get("kiauh", "backup_before_update"): if settings.kiauh.backup_before_update:
backup_klipper_dir() backup_klipper_dir()
instance_manager = InstanceManager(Klipper) instance_manager = InstanceManager(Klipper)
instance_manager.stop_all_instance() instance_manager.stop_all_instance()
git_pull_wrapper(repo=settings.get("klipper", "repo_url"), target_dir=KLIPPER_DIR) git_pull_wrapper(repo=settings.klipper.repo_url, target_dir=KLIPPER_DIR)
# install possible new system packages # install possible new system packages
install_klipper_packages(KLIPPER_DIR) install_klipper_packages(KLIPPER_DIR)

View File

@@ -124,7 +124,7 @@ def update_klipperscreen() -> None:
cmd_sysctl_service("KlipperScreen", "stop") cmd_sysctl_service("KlipperScreen", "stop")
settings = KiauhSettings() settings = KiauhSettings()
if settings.get("kiauh", "backup_before_update"): if settings.kiauh.backup_before_update:
backup_klipperscreen_dir() backup_klipperscreen_dir()
git_pull_wrapper(KLIPPERSCREEN_REPO, KLIPPERSCREEN_DIR) git_pull_wrapper(KLIPPERSCREEN_REPO, KLIPPERSCREEN_DIR)

View File

@@ -120,7 +120,7 @@ def update_mobileraker() -> None:
cmd_sysctl_service("mobileraker", "stop") cmd_sysctl_service("mobileraker", "stop")
settings = KiauhSettings() settings = KiauhSettings()
if settings.get("kiauh", "backup_before_update"): if settings.kiauh.backup_before_update:
backup_mobileraker_dir() backup_mobileraker_dir()
git_pull_wrapper(MOBILERAKER_REPO, MOBILERAKER_DIR) git_pull_wrapper(MOBILERAKER_REPO, MOBILERAKER_DIR)

View File

@@ -137,8 +137,8 @@ def check_moonraker_install_requirements() -> bool:
def setup_moonraker_prerequesites() -> None: def setup_moonraker_prerequesites() -> None:
settings = KiauhSettings() settings = KiauhSettings()
repo = settings.get("moonraker", "repo_url") repo = settings.moonraker.repo_url
branch = settings.get("moonraker", "branch") branch = settings.moonraker.branch
git_clone_wrapper(repo, MOONRAKER_DIR, branch) git_clone_wrapper(repo, MOONRAKER_DIR, branch)
@@ -200,14 +200,14 @@ def update_moonraker() -> None:
return return
settings = KiauhSettings() settings = KiauhSettings()
if settings.get("kiauh", "backup_before_update"): if settings.kiauh.backup_before_update:
backup_moonraker_dir() backup_moonraker_dir()
instance_manager = InstanceManager(Moonraker) instance_manager = InstanceManager(Moonraker)
instance_manager.stop_all_instance() instance_manager.stop_all_instance()
git_pull_wrapper( git_pull_wrapper(
repo=settings.get("moonraker", "repo_url"), target_dir=MOONRAKER_DIR repo=settings.moonraker.repo_url, target_dir=MOONRAKER_DIR
) )
# install possible new system packages # install possible new system packages

View File

@@ -102,7 +102,7 @@ def update_client_config(client: BaseWebClient) -> None:
return return
settings = KiauhSettings() settings = KiauhSettings()
if settings.get("kiauh", "backup_before_update"): if settings.kiauh.backup_before_update:
backup_client_config_data(client) backup_client_config_data(client)
git_pull_wrapper(client_config.repo_url, client_config.config_dir) git_pull_wrapper(client_config.repo_url, client_config.config_dir)

View File

@@ -94,28 +94,19 @@ class SettingsMenu(BaseMenu):
print(menu, end="") print(menu, end="")
def _load_settings(self): def _load_settings(self):
self.kiauh_settings = KiauhSettings() self.settings = KiauhSettings()
self._format_repo_str("klipper") self._format_repo_str("klipper")
self._format_repo_str("moonraker") self._format_repo_str("moonraker")
self.auto_backups_enabled = self.kiauh_settings.get( self.auto_backups_enabled = self.settings.kiauh.backup_before_update
"kiauh", self.mainsail_unstable = self.settings.mainsail.unstable_releases
"backup_before_update", self.fluidd_unstable = self.settings.fluidd.unstable_releases
)
self.mainsail_unstable = self.kiauh_settings.get(
"mainsail",
"unstable_releases",
)
self.fluidd_unstable = self.kiauh_settings.get(
"fluidd",
"unstable_releases",
)
def _format_repo_str(self, repo_name: str) -> None: def _format_repo_str(self, repo_name: str) -> None:
repo = self.kiauh_settings.get(repo_name, "repo_url") repo = self.settings.get(repo_name, "repo_url")
repo = f"{'/'.join(repo.rsplit('/', 2)[-2:])}" repo = f"{'/'.join(repo.rsplit('/', 2)[-2:])}"
branch = self.kiauh_settings.get(repo_name, "branch") branch = self.settings.get(repo_name, "branch")
branch = f"({COLOR_CYAN}@ {branch}{RESET_FORMAT})" branch = f"({COLOR_CYAN}@ {branch}{RESET_FORMAT})"
setattr(self, f"{repo_name}_repo", f"{COLOR_CYAN}{repo}{RESET_FORMAT} {branch}") setattr(self, f"{repo_name}_repo", f"{COLOR_CYAN}{repo}{RESET_FORMAT} {branch}")
@@ -156,9 +147,9 @@ class SettingsMenu(BaseMenu):
) )
if get_confirm("Apply changes?", allow_go_back=True): if get_confirm("Apply changes?", allow_go_back=True):
self.kiauh_settings.set(repo_name, "repo_url", repo_url) self.settings.set(repo_name, "repo_url", repo_url)
self.kiauh_settings.set(repo_name, "branch", branch) self.settings.set(repo_name, "branch", branch)
self.kiauh_settings.save() self.settings.save()
self._load_settings() self._load_settings()
Logger.print_ok("Changes saved!") Logger.print_ok("Changes saved!")
else: else:
@@ -189,8 +180,8 @@ class SettingsMenu(BaseMenu):
im = InstanceManager(_type) im = InstanceManager(_type)
im.stop_all_instance() im.stop_all_instance()
repo = self.kiauh_settings.get(name, "repo_url") repo = self.settings.get(name, "repo_url")
branch = self.kiauh_settings.get(name, "branch") branch = self.settings.get(name, "branch")
git_clone_wrapper(repo, target_dir, branch) git_clone_wrapper(repo, target_dir, branch)
im.start_all_instance() im.start_all_instance()
@@ -203,27 +194,15 @@ class SettingsMenu(BaseMenu):
def toggle_mainsail_release(self, **kwargs): def toggle_mainsail_release(self, **kwargs):
self.mainsail_unstable = not self.mainsail_unstable self.mainsail_unstable = not self.mainsail_unstable
self.kiauh_settings.set( self.settings.mainsail.unstable_releases = self.mainsail_unstable
"mainsail", self.settings.save()
"unstable_releases",
self.mainsail_unstable,
)
self.kiauh_settings.save()
def toggle_fluidd_release(self, **kwargs): def toggle_fluidd_release(self, **kwargs):
self.fluidd_unstable = not self.fluidd_unstable self.fluidd_unstable = not self.fluidd_unstable
self.kiauh_settings.set( self.settings.fluidd.unstable_releases = self.fluidd_unstable
"fluidd", self.settings.save()
"unstable_releases",
self.fluidd_unstable,
)
self.kiauh_settings.save()
def toggle_backup_before_update(self, **kwargs): def toggle_backup_before_update(self, **kwargs):
self.auto_backups_enabled = not self.auto_backups_enabled self.auto_backups_enabled = not self.auto_backups_enabled
self.kiauh_settings.set( self.settings.kiauh.backup_before_update = self.auto_backups_enabled
"kiauh", self.settings.save()
"backup_before_update",
self.auto_backups_enabled,
)
self.kiauh_settings.save()

View File

@@ -6,12 +6,16 @@
# # # #
# This file may be distributed under the terms of the GNU GPLv3 license # # This file may be distributed under the terms of the GNU GPLv3 license #
# ======================================================================= # # ======================================================================= #
from __future__ import annotations
import configparser
import textwrap import textwrap
from typing import Dict, Union from typing import Union
from core.config_manager.config_manager import CustomConfigParser from core.submodules.simple_config_parser.src.simple_config_parser.simple_config_parser import (
NoOptionError,
NoSectionError,
SimpleConfigParser,
)
from utils.constants import COLOR_RED, RESET_FORMAT from utils.constants import COLOR_RED, RESET_FORMAT
from utils.logger import Logger from utils.logger import Logger
from utils.sys_utils import kill from utils.sys_utils import kill
@@ -19,6 +23,35 @@ from utils.sys_utils import kill
from kiauh import PROJECT_ROOT from kiauh import PROJECT_ROOT
class AppSettings:
def __init__(self) -> None:
self.backup_before_update = None
class KlipperSettings:
def __init__(self) -> None:
self.repo_url = None
self.branch = None
class MoonrakerSettings:
def __init__(self) -> None:
self.repo_url = None
self.branch = None
class MainsailSettings:
def __init__(self) -> None:
self.port = None
self.unstable_releases = None
class FluiddSettings:
def __init__(self) -> None:
self.port = None
self.unstable_releases = None
# noinspection PyUnusedLocal # noinspection PyUnusedLocal
# noinspection PyMethodMayBeStatic # noinspection PyMethodMayBeStatic
class KiauhSettings: class KiauhSettings:
@@ -36,32 +69,69 @@ class KiauhSettings:
if self.__initialized: if self.__initialized:
return return
self.__initialized = True self.__initialized = True
self.config = CustomConfigParser() self.config = SimpleConfigParser()
self.settings: Dict[str, Dict[str, Union[str, int, bool]]] = {} self.kiauh = AppSettings()
self._load_settings() self.klipper = KlipperSettings()
self.moonraker = MoonrakerSettings()
self.mainsail = MainsailSettings()
self.fluidd = FluiddSettings()
self.kiauh.backup_before_update = None
self.klipper.repo_url = None
self.klipper.branch = None
self.moonraker.repo_url = None
self.moonraker.branch = None
self.mainsail.port = None
self.mainsail.unstable_releases = None
self.fluidd.port = None
self.fluidd.unstable_releases = None
self._load_config()
def get(self, section: str, option: str) -> Union[str, int, bool]: def get(self, section: str, option: str) -> Union[str, int, bool]:
return self.settings[section][option] """
Get a value from the settings state by providing the section and option name as strings.
Prefer direct access to the properties, as it is usually safer!
:param section: The section name as string.
:param option: The option name as string.
:return: The value of the option as string, int or bool.
"""
try:
section = getattr(self, section)
value = getattr(section, option)
return value
except AttributeError:
raise
def set(self, section: str, option: str, value: Union[str, int, bool]) -> None: def set(self, section: str, option: str, value: Union[str, int, bool]) -> None:
self.settings[section][option] = value """
Set a value in the settings state by providing the section and option name as strings.
Prefer direct access to the properties, as it is usually safer!
:param section: The section name as string.
:param option: The option name as string.
:param value: The value to set as string, int or bool.
"""
try:
section = getattr(self, section)
section.option = value
except AttributeError:
raise
def save(self) -> None: def save(self) -> None:
for section, option in self.settings.items(): self._set_config_options()
self.config[section] = option self.config.write(self._custom_cfg)
with open(self._custom_cfg, "w") as configfile: self._load_config()
self.config.write(configfile)
self._load_settings()
def _load_settings(self) -> None: def _load_config(self) -> None:
if self._custom_cfg.exists(): if not self._custom_cfg.exists() or not self._default_cfg.exists():
self.config.read(self._custom_cfg)
elif self._default_cfg.exists():
self.config.read(self._default_cfg)
else:
self._kill() self._kill()
cfg = self._custom_cfg if self._custom_cfg.exists() else self._default_cfg
self.config.read(cfg)
self._validate_cfg() self._validate_cfg()
self._parse_settings() self._read_settings()
def _validate_cfg(self) -> None: def _validate_cfg(self) -> None:
try: try:
@@ -80,11 +150,11 @@ class KiauhSettings:
err = f"Invalid value for option '{self._v_option}' in section '{self._v_section}'" err = f"Invalid value for option '{self._v_option}' in section '{self._v_section}'"
Logger.print_error(err) Logger.print_error(err)
kill() kill()
except configparser.NoSectionError: except NoSectionError:
err = f"Missing section '{self._v_section}' in config file" err = f"Missing section '{self._v_section}' in config file"
Logger.print_error(err) Logger.print_error(err)
kill() kill()
except configparser.NoOptionError: except NoOptionError:
err = f"Missing option '{self._v_option}' in section '{self._v_section}'" err = f"Missing option '{self._v_option}' in section '{self._v_section}'"
Logger.print_error(err) Logger.print_error(err)
kill() kill()
@@ -103,18 +173,43 @@ class KiauhSettings:
if v.isdigit() or v.lower() == "true" or v.lower() == "false": if v.isdigit() or v.lower() == "true" or v.lower() == "false":
raise ValueError raise ValueError
def _parse_settings(self): def _read_settings(self):
for s in self.config.sections(): self.kiauh.backup_before_update = self.config.getboolean(
self.settings[s] = {} "kiauh", "backup_before_update"
for o, v in self.config.items(s): )
if v.lower() == "true": self.klipper.repo_url = self.config.get("klipper", "repo_url")
self.settings[s][o] = True self.klipper.branch = self.config.get("klipper", "branch")
elif v.lower() == "false": self.moonraker.repo_url = self.config.get("moonraker", "repo_url")
self.settings[s][o] = False self.moonraker.branch = self.config.get("moonraker", "branch")
elif v.isdigit(): self.mainsail.port = self.config.getint("mainsail", "port")
self.settings[s][o] = int(v) self.mainsail.unstable_releases = self.config.getboolean(
else: "mainsail", "unstable_releases"
self.settings[s][o] = v )
self.fluidd.port = self.config.getint("fluidd", "port")
self.fluidd.unstable_releases = self.config.getboolean(
"fluidd", "unstable_releases"
)
def _set_config_options(self):
self.config.set(
"kiauh",
"backup_before_update",
str(self.kiauh.backup_before_update),
)
self.config.set("klipper", "repo_url", self.klipper.repo_url)
self.config.set("klipper", "branch", self.klipper.branch)
self.config.set("moonraker", "repo_url", self.moonraker.repo_url)
self.config.set("moonraker", "branch", self.moonraker.branch)
self.config.set("mainsail", "port", str(self.mainsail.port))
self.config.set(
"mainsail",
"unstable_releases",
str(self.mainsail.unstable_releases),
)
self.config.set("fluidd", "port", str(self.fluidd.port))
self.config.set(
"fluidd", "unstable_releases", str(self.fluidd.unstable_releases)
)
def _kill(self) -> None: def _kill(self) -> None:
l1 = "!!! ERROR !!!" l1 = "!!! ERROR !!!"