Coverage for agentos/marketplace/skills/backup/backup.py: 27%

48 statements  

« prev     ^ index     » next       coverage.py v7.14.3, created at 2026-07-06 12:29 +0800

1""" 

2backup — Simple file/directory backup utility. 

3 

4Actions: backup, list_backups, restore_latest 

5Creates timestamped .tar.gz archives. 

6""" 

7 

8import glob 

9import os 

10import shutil 

11from datetime import datetime 

12from typing import Any 

13 

14BACKUP_DIR = os.path.expanduser("~/.agentos_backups") 

15 

16 

17def run(action: str = "backup", source: str = "", target_name: str = "", **kwargs: Any) -> str: 

18 os.makedirs(BACKUP_DIR, exist_ok=True) 

19 

20 if action == "list_backups": 

21 files = sorted(glob.glob(os.path.join(BACKUP_DIR, "*.tar.gz")), reverse=True) 

22 if not files: 

23 return "[backup] No backups found." 

24 result = f"Backups ({len(files)}):\n" 

25 for f in files[:20]: 

26 name = os.path.basename(f) 

27 size = os.path.getsize(f) 

28 result += f" {name} ({size/1024:.1f} KB)\n" 

29 return result 

30 

31 if action == "backup": 

32 if not source: 

33 return "[backup] Source path required." 

34 if not os.path.exists(source): 

35 return f"[backup] Source not found: {source}" 

36 

37 base_name = target_name or os.path.basename(source.rstrip("/\\")) 

38 ts = datetime.now().strftime("%Y%m%d_%H%M%S") 

39 archive_name = f"{base_name}_{ts}" 

40 archive_path = os.path.join(BACKUP_DIR, archive_name) 

41 

42 try: 

43 shutil.make_archive( 

44 archive_path, "gztar", os.path.dirname(source), os.path.basename(source) 

45 ) 

46 final_path = archive_path + ".tar.gz" 

47 size = os.path.getsize(final_path) 

48 return f"[backup] Created: {os.path.basename(final_path)} ({size/1024:.1f} KB)" 

49 except Exception as e: 

50 return f"[backup] Error: {e}" 

51 

52 if action == "restore_latest": 

53 if not source: 

54 return "[backup] Destination path required for restore." 

55 files = sorted(glob.glob(os.path.join(BACKUP_DIR, "*.tar.gz")), reverse=True) 

56 if not files: 

57 return "[backup] No backups to restore." 

58 latest = files[0] 

59 try: 

60 shutil.unpack_archive(latest, source) 

61 return f"[backup] Restored {os.path.basename(latest)} to {source}" 

62 except Exception as e: 

63 return f"[backup] Restore error: {e}" 

64 

65 return f"[backup] Unknown action: {action}. Available: backup, list_backups, restore_latest" 

66 

67 

68__all__ = ["run"]