data_paths.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. """Durable storage paths and one-time migration for the YaoYao plugin.
  2. Plugin installers replace ``<profile_home>/plugins/yaoyao`` atomically. Runtime
  3. state therefore lives under ``<profile_home>/plugin-data/yaoyao`` so installs,
  4. updates, and removals cannot delete user data.
  5. """
  6. from __future__ import annotations
  7. import os
  8. from dataclasses import dataclass
  9. from pathlib import Path
  10. DURABLE_DATA_SUBPATH = Path("plugin-data") / "yaoyao"
  11. LEGACY_DATA_SUBPATH = Path("plugins") / "yaoyao" / "data"
  12. @dataclass(frozen=True)
  13. class DataPathStatus:
  14. data_root: Path
  15. ready: bool
  16. migrated: bool
  17. legacy_present: bool
  18. conflict: bool
  19. def _has_entries(path: Path) -> bool:
  20. try:
  21. return next(path.iterdir(), None) is not None
  22. except FileNotFoundError:
  23. return False
  24. def ensure_durable_data_root(profile_home: Path) -> DataPathStatus:
  25. """Move the legacy data directory once, without merging ambiguous trees.
  26. The durable tree is always the runtime authority once it exists. When both
  27. locations contain data, keep both untouched and report a conflict so the
  28. install coordinator can refuse a full plugin replace without making the
  29. application silently fall back to stale legacy state.
  30. """
  31. home = Path(profile_home).expanduser().resolve()
  32. durable = home / DURABLE_DATA_SUBPATH
  33. legacy = home / LEGACY_DATA_SUBPATH
  34. legacy_present = legacy.exists()
  35. if not legacy_present:
  36. return DataPathStatus(durable, True, False, False, False)
  37. if legacy.is_symlink() or durable.is_symlink():
  38. return DataPathStatus(durable, False, False, True, True)
  39. if durable.exists():
  40. if _has_entries(legacy):
  41. return DataPathStatus(durable, False, False, True, True)
  42. return DataPathStatus(durable, True, False, True, False)
  43. durable.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
  44. os.replace(legacy, durable)
  45. return DataPathStatus(durable, True, True, False, False)