67 lines
2.6 KiB
Python
67 lines
2.6 KiB
Python
#!/usr/bin/env python3
|
|
|
|
# ======================================================================= #
|
|
# Copyright (C) 2020 - 2023 Dominik Willner <th33xitus@gmail.com> #
|
|
# #
|
|
# This file is part of KIAUH - Klipper Installation And Update Helper #
|
|
# https://github.com/dw-0/kiauh #
|
|
# #
|
|
# This file may be distributed under the terms of the GNU GPLv3 license #
|
|
# ======================================================================= #
|
|
|
|
import shutil
|
|
from pathlib import Path
|
|
from typing import List
|
|
|
|
from kiauh import KIAUH_BACKUP_DIR
|
|
from kiauh.utils.common import get_current_date
|
|
from kiauh.utils.logger import Logger
|
|
|
|
|
|
# noinspection PyMethodMayBeStatic
|
|
class BackupManager:
|
|
def __init__(self, backup_root_dir: Path = KIAUH_BACKUP_DIR):
|
|
self._backup_root_dir = backup_root_dir
|
|
|
|
@property
|
|
def backup_root_dir(self) -> Path:
|
|
return self._backup_root_dir
|
|
|
|
@backup_root_dir.setter
|
|
def backup_root_dir(self, value: Path):
|
|
self._backup_root_dir = value
|
|
|
|
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!")
|
|
|
|
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
|
|
|
|
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 {name} in {target} ..."
|
|
Logger.print_status(log)
|
|
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 directory '{source}':\n{e}")
|
|
return
|
|
|
|
Logger.print_ok("Backup successfull!")
|