refactor(BackupManager): rework backup structure and implement single file backup method

Signed-off-by: Dominik Willner <th33xitus@gmail.com>
This commit is contained in:
dw-0
2023-12-24 12:58:41 +01:00
parent b9479db766
commit 2f0feb317e
4 changed files with 40 additions and 47 deletions

View File

@@ -11,6 +11,7 @@
import shutil
from pathlib import Path
from typing import List
from kiauh import KIAUH_BACKUP_DIR
from kiauh.utils.common import get_current_date
@@ -19,51 +20,47 @@ from kiauh.utils.logger import Logger
# noinspection PyMethodMayBeStatic
class BackupManager:
def __init__(
self, backup_name: str, source: Path, backup_dir: Path = KIAUH_BACKUP_DIR
):
self._backup_name = backup_name
self._source = source
self._backup_dir = backup_dir
def __init__(self, backup_root_dir: Path = KIAUH_BACKUP_DIR):
self._backup_root_dir = backup_root_dir
@property
def backup_name(self) -> str:
return self._backup_name
def backup_root_dir(self) -> Path:
return self._backup_root_dir
@backup_name.setter
def backup_name(self, value: str):
self._backup_name = value
@backup_root_dir.setter
def backup_root_dir(self, value: Path):
self._backup_root_dir = value
@property
def source(self) -> Path:
return self._source
def backup_file(self, files: List[Path] = None, target: Path = None):
if not files:
raise ValueError("Parameter 'files' cannot be None or an empty List!")
@source.setter
def source(self, value: Path):
self._source = value
target = self.backup_root_dir if target is None else target
for file in files:
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}"
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
@property
def backup_dir(self) -> Path:
return self._backup_dir
@backup_dir.setter
def backup_dir(self, value: Path):
self._backup_dir = value
def backup(self) -> None:
if self._source is None or not Path(self._source).exists():
def backup_directory(self, name: str, source: Path, target: Path = None) -> None:
if source is None or not Path(source).exists():
raise OSError
target = self.backup_root_dir if target is None else target
try:
log = f"Creating backup of {self.backup_name} in {self.backup_dir} ..."
log = f"Creating backup of {name} in {target} ..."
Logger.print_status(log)
date = get_current_date()
dest = Path(
f"{self.backup_dir}/{self.backup_name}/{date.get('date')}-{date.get('time')}"
)
shutil.copytree(src=self.source, dst=dest)
date = get_current_date().get("date")
time = get_current_date().get("time")
shutil.copytree(source, Path(target, f"{name}-{date}-{time}"))
except OSError as e:
Logger.print_error(f"Unable to backup source directory. Not exist.\n{e}")
Logger.print_error(f"Unable to backup directory '{source}':\n{e}")
return
Logger.print_ok("Backup successfull!")

View File

@@ -264,11 +264,9 @@ def update_klipper() -> None:
cm = ConfigManager(cfg_file=KIAUH_CFG)
if cm.get_value("kiauh", "backup_before_update"):
backup_manager = BackupManager(source=KLIPPER_DIR, backup_name="klipper")
backup_manager.backup()
backup_manager.backup_name = "klippy-env"
backup_manager.source = KLIPPER_ENV_DIR
backup_manager.backup()
bm = BackupManager()
bm.backup_directory("klipper", KLIPPER_DIR)
bm.backup_directory("klippy-env", KLIPPER_ENV_DIR)
instance_manager = InstanceManager(Klipper)
instance_manager.stop_all_instance()

View File

@@ -290,11 +290,9 @@ def update_moonraker() -> None:
cm = ConfigManager(cfg_file=KIAUH_CFG)
if cm.get_value("kiauh", "backup_before_update"):
backup_manager = BackupManager(source=MOONRAKER_DIR, backup_name="moonraker")
backup_manager.backup()
backup_manager.backup_name = "moonraker-env"
backup_manager.source = MOONRAKER_ENV_DIR
backup_manager.backup()
bm = BackupManager()
bm.backup_directory("moonraker", MOONRAKER_DIR)
bm.backup_directory("moonraker-env", MOONRAKER_ENV_DIR)
instance_manager = InstanceManager(Moonraker)
instance_manager.stop_all_instance()

View File

@@ -1,5 +1,4 @@
#!/usr/bin/env python3
import subprocess
# ======================================================================= #
# Copyright (C) 2020 - 2023 Dominik Willner <th33xitus@gmail.com> #
@@ -10,6 +9,7 @@ import subprocess
# This file may be distributed under the terms of the GNU GPLv3 license #
# ======================================================================= #
import subprocess
from datetime import datetime
from pathlib import Path
from typing import Dict, Literal, List, Type
@@ -33,8 +33,8 @@ def get_current_date() -> Dict[Literal["date", "time"], str]:
:return: Dict holding a date and time key:value pair
"""
now: datetime = datetime.today()
date: str = now.strftime("%Y-%m-%d")
time: str = now.strftime("%H-%M-%S")
date: str = now.strftime("%Y%m%d")
time: str = now.strftime("%H%M%S")
return {"date": date, "time": time}