Coverage for sparkle/CLI/help/snapshot_help.py: 30%
44 statements
« prev ^ index » next coverage.py v7.6.1, created at 2024-09-27 09:10 +0000
« prev ^ index » next coverage.py v7.6.1, created at 2024-09-27 09:10 +0000
1#!/usr/bin/env python3
2# -*- coding: UTF-8 -*-
3"""Helper functions to record and restore a Sparkle platform."""
4import shutil
5import sys
6import os
7import time
8from pathlib import Path
9import zipfile
11from sparkle.CLI.help import global_variables as gv
12from sparkle.tools.general import get_time_pid_random_string
15def save_current_sparkle_platform() -> None:
16 """Store the current Sparkle platform in a .zip file."""
17 time_stamp = time.strftime("%Y-%m-%d-%H:%M:%S", time.localtime(time.time()))
18 snapshot_tmp_path = gv.settings().DEFAULT_snapshot_dir /\
19 f"Snapshot_{os.getlogin()}_{time_stamp}"
20 snapshot_tmp_path.mkdir(parents=True) # Create temporary directory for zip
21 for working_dir in gv.settings().DEFAULT_working_dirs:
22 if working_dir.exists():
23 shutil.copytree(working_dir, snapshot_tmp_path / working_dir.name)
24 shutil.make_archive(snapshot_tmp_path, "zip", snapshot_tmp_path)
25 shutil.rmtree(snapshot_tmp_path)
26 print(f"Snapshot file {snapshot_tmp_path}.zip saved successfully!")
29def remove_current_platform() -> None:
30 """Remove the current Sparkle platform."""
31 for working_dir in gv.settings().DEFAULT_working_dirs:
32 shutil.rmtree(working_dir, ignore_errors=True)
35def create_working_dirs() -> None:
36 """Create working directories."""
37 for working_dir in gv.settings().DEFAULT_working_dirs:
38 working_dir.mkdir(parents=True, exist_ok=True)
41def extract_snapshot(snapshot_file: Path) -> None:
42 """Restore a Sparkle platform from a snapshot.
44 Args:
45 snapshot_file: Path to the where the current Sparkle platform should be stored.
46 """
47 tmp_directory = Path(f"tmp_directory_{get_time_pid_random_string()}")
48 gv.settings().DEFAULT_tmp_output.mkdir(exist_ok=True)
49 with zipfile.ZipFile(snapshot_file, "r") as zip_ref:
50 zip_ref.extractall(tmp_directory)
51 shutil.copytree(tmp_directory, "./", dirs_exist_ok=True)
52 shutil.rmtree(tmp_directory)
55def load_snapshot(snapshot_file: Path) -> None:
56 """Load a Sparkle platform from a snapshot.
58 Args:
59 snapshot_file: File path to the file where the Sparkle platform is stored.
60 """
61 if not snapshot_file.exists():
62 print(f"ERROR: Snapshot file {snapshot_file} does not exist!")
63 sys.exit(-1)
64 if not snapshot_file.suffix == ".zip":
65 print(f"ERROR: File {snapshot_file} is not a .zip file!")
66 sys.exit(-1)
67 print("Cleaning existing Sparkle platform ...")
68 remove_current_platform()
69 print("Existing Sparkle platform cleaned!")
71 print(f"Loading snapshot file {snapshot_file} ...")
72 extract_snapshot(snapshot_file)
73 print(f"Snapshot file {snapshot_file} loaded successfully!")