refactor(Mainsail): rework config.json backup

Signed-off-by: Dominik Willner <th33xitus@gmail.com>
This commit is contained in:
dw-0
2023-12-24 13:53:55 +01:00
parent 2f0feb317e
commit 7a6590e86a
3 changed files with 18 additions and 12 deletions

View File

@@ -31,22 +31,28 @@ class BackupManager:
def backup_root_dir(self, value: Path):
self._backup_root_dir = value
def backup_file(self, files: List[Path] = None, target: Path = None):
def backup_file(
self, files: List[Path] = None, target: Path = None, custom_filename=None
):
if not files:
raise ValueError("Parameter 'files' cannot be None or an empty List!")
target = self.backup_root_dir if target is None else target
for file in files:
Logger.print_status(f"Creating backup of {file} ...")
if Path(file).is_file():
date = get_current_date().get("date")
time = get_current_date().get("time")
filename = f"{file.stem}-{date}-{time}{file.suffix}"
filename = custom_filename if custom_filename is not None else filename
try:
Path(target).mkdir(exist_ok=True)
shutil.copyfile(file, Path(target, filename))
except OSError as e:
Logger.print_error(f"Unable to backup '{file}':\n{e}")
continue
else:
Logger.print_info(f"File '{file}' not found ...")
def backup_directory(self, name: str, source: Path, target: Path = None) -> None:
if source is None or not Path(source).exists():

View File

@@ -78,7 +78,7 @@ def run_mainsail_installation() -> None:
print_mainsail_already_installed_dialog()
do_reinstall = get_confirm("Re-install Mainsail?", allow_go_back=True)
if do_reinstall:
backup_config_json()
backup_config_json(is_temp=True)
else:
return

View File

@@ -15,20 +15,20 @@ import shutil
from pathlib import Path
from typing import List
from kiauh.core.backup_manager.backup_manager import BackupManager
from kiauh.modules.klipper.klipper import Klipper
from kiauh.modules.mainsail import MAINSAIL_CONFIG_JSON
from kiauh.utils.logger import Logger
# TODO: give this method an optional target dir to backup to
# alteratively use the BackupManager for handling this task (probably best)
def backup_config_json() -> None:
try:
Logger.print_status(f"Backup '{MAINSAIL_CONFIG_JSON}' ...")
target = os.path.join(Path.home(), "config.json.kiauh.bak")
shutil.copy(MAINSAIL_CONFIG_JSON, target)
except OSError:
Logger.print_info(f"Unable to backup config.json. Skipped ...")
def backup_config_json(is_temp=False) -> None:
Logger.print_status(f"Backup '{MAINSAIL_CONFIG_JSON}' ...")
bm = BackupManager()
if is_temp:
fn = Path(Path.home(), "config.json.kiauh.bak")
bm.backup_file([MAINSAIL_CONFIG_JSON], custom_filename=fn)
else:
bm.backup_file([MAINSAIL_CONFIG_JSON])
def restore_config_json() -> None:
@@ -37,7 +37,7 @@ def restore_config_json() -> None:
source = os.path.join(Path.home(), "config.json.kiauh.bak")
shutil.copy(source, MAINSAIL_CONFIG_JSON)
except OSError:
Logger.print_info(f"Unable to restore config.json. Skipped ...")
Logger.print_info("Unable to restore config.json. Skipped ...")
def enable_mainsail_remotemode() -> None: