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

48 statements  

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

1""" 

2backup — Simple file/directory backup utility. 

3 

4Actions: backup, list_backups, restore_latest 

5Creates timestamped .tar.gz archives. 

6""" 

7 

8import os 

9import shutil 

10import glob 

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(archive_path, "gztar", os.path.dirname(source), os.path.basename(source)) 

44 final_path = archive_path + ".tar.gz" 

45 size = os.path.getsize(final_path) 

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

47 except Exception as e: 

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

49 

50 if action == "restore_latest": 

51 if not source: 

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

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

54 if not files: 

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

56 latest = files[0] 

57 try: 

58 shutil.unpack_archive(latest, source) 

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

60 except Exception as e: 

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

62 

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

64 

65 

66__all__ = ["run"]