local.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. import os
  2. import shutil
  3. from openhands.core.logger import openhands_logger as logger
  4. from openhands.storage.files import FileStore
  5. class LocalFileStore(FileStore):
  6. root: str
  7. def __init__(self, root: str):
  8. self.root = root
  9. os.makedirs(self.root, exist_ok=True)
  10. def get_full_path(self, path: str) -> str:
  11. if path.startswith('/'):
  12. path = path[1:]
  13. return os.path.join(self.root, path)
  14. def write(self, path: str, contents: str | bytes):
  15. full_path = self.get_full_path(path)
  16. os.makedirs(os.path.dirname(full_path), exist_ok=True)
  17. mode = 'w' if isinstance(contents, str) else 'wb'
  18. with open(full_path, mode) as f:
  19. f.write(contents)
  20. def read(self, path: str) -> str:
  21. full_path = self.get_full_path(path)
  22. with open(full_path, 'r') as f:
  23. return f.read()
  24. def list(self, path: str) -> list[str]:
  25. full_path = self.get_full_path(path)
  26. files = [os.path.join(path, f) for f in os.listdir(full_path)]
  27. files = [f + '/' if os.path.isdir(self.get_full_path(f)) else f for f in files]
  28. return files
  29. def delete(self, path: str) -> None:
  30. try:
  31. full_path = self.get_full_path(path)
  32. if not os.path.exists(full_path):
  33. logger.debug(f'Local path does not exist: {full_path}')
  34. return
  35. if os.path.isfile(full_path):
  36. os.remove(full_path)
  37. logger.debug(f'Removed local file: {full_path}')
  38. elif os.path.isdir(full_path):
  39. shutil.rmtree(full_path)
  40. logger.debug(f'Removed local directory: {full_path}')
  41. except Exception as e:
  42. logger.error(f'Error clearing local file store: {str(e)}')