Coverage for sparkle/CLI/help/snapshot_help.py: 84%

56 statements  

« prev     ^ index     » next       coverage.py v7.6.4, created at 2024-11-05 14:48 +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 

10 

11from sparkle.CLI.help import global_variables as gv 

12from sparkle.tools.general import get_time_pid_random_string 

13 

14 

15def save_current_platform(name: str = None) -> None: 

16 """Store the current Sparkle platform in a .zip file.""" 

17 if name is None: 

18 time_stamp = time.strftime("%Y-%m-%d-%H:%M:%S", time.localtime(time.time())) 

19 try: 

20 login = os.getlogin() 

21 except Exception: # Can fail on for example CI pipelines 

22 login = "unknown" 

23 name = f"Snapshot_{login}_{time_stamp}" 

24 snapshot_tmp_path = gv.settings().DEFAULT_snapshot_dir / name 

25 snapshot_tmp_path.mkdir(parents=True) # Create temporary directory for zip 

26 available_dirs = [p.name for p in Path.cwd().iterdir()] 

27 root_working_dirs = [p for p in gv.settings().DEFAULT_working_dirs 

28 if p.name in available_dirs] 

29 for working_dir in root_working_dirs: 

30 if working_dir.exists(): 

31 shutil.copytree(working_dir, snapshot_tmp_path / working_dir.name) 

32 shutil.make_archive(snapshot_tmp_path, "zip", snapshot_tmp_path) 

33 shutil.rmtree(snapshot_tmp_path) 

34 print(f"Snapshot file {snapshot_tmp_path}.zip saved successfully!") 

35 

36 

37def remove_current_platform() -> None: 

38 """Remove the current Sparkle platform.""" 

39 for working_dir in gv.settings().DEFAULT_working_dirs: 

40 shutil.rmtree(working_dir, ignore_errors=True) 

41 

42 

43def create_working_dirs() -> None: 

44 """Create working directories.""" 

45 for working_dir in gv.settings().DEFAULT_working_dirs: 

46 working_dir.mkdir(parents=True, exist_ok=True) 

47 

48 

49def extract_snapshot(snapshot_file: Path) -> None: 

50 """Restore a Sparkle platform from a snapshot. 

51 

52 Args: 

53 snapshot_file: Path to the where the current Sparkle platform should be stored. 

54 """ 

55 tmp_directory = Path(f"tmp_directory_{get_time_pid_random_string()}") 

56 gv.settings().DEFAULT_tmp_output.mkdir(exist_ok=True) 

57 with zipfile.ZipFile(snapshot_file, "r") as zip_ref: 

58 zip_ref.extractall(tmp_directory) 

59 shutil.copytree(tmp_directory, "./", dirs_exist_ok=True) 

60 shutil.rmtree(tmp_directory) 

61 

62 

63def load_snapshot(snapshot_file: Path) -> None: 

64 """Load a Sparkle platform from a snapshot. 

65 

66 Args: 

67 snapshot_file: File path to the file where the Sparkle platform is stored. 

68 """ 

69 if not snapshot_file.exists(): 

70 print(f"ERROR: Snapshot file {snapshot_file} does not exist!") 

71 sys.exit(-1) 

72 if not snapshot_file.suffix == ".zip": 

73 print(f"ERROR: File {snapshot_file} is not a .zip file!") 

74 sys.exit(-1) 

75 print("Cleaning existing Sparkle platform ...") 

76 remove_current_platform() 

77 print("Existing Sparkle platform cleaned!") 

78 

79 print(f"Loading snapshot file {snapshot_file} ...") 

80 extract_snapshot(snapshot_file) 

81 if any([not wd.exists() for wd in gv.settings().DEFAULT_working_dirs]): 

82 missing_dirs = [wd.name for wd in gv.settings().DEFAULT_working_dirs 

83 if not wd.exists()] 

84 print("ERROR: Failed to load Sparkle platform! The snapshot file may be outdated" 

85 " or corrupted. Missing the following directories: " 

86 f"{', '.join(missing_dirs)}") 

87 sys.exit(-1) 

88 print(f"Snapshot file {snapshot_file} loaded successfully!")