memory.py 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. import os
  2. from openhands.core.logger import openhands_logger as logger
  3. from openhands.storage.files import FileStore
  4. IN_MEMORY_FILES: dict = {}
  5. class InMemoryFileStore(FileStore):
  6. files: dict[str, str]
  7. def __init__(self):
  8. self.files = IN_MEMORY_FILES
  9. def write(self, path: str, contents: str) -> None:
  10. self.files[path] = contents
  11. def read(self, path: str) -> str:
  12. if path not in self.files:
  13. raise FileNotFoundError(path)
  14. return self.files[path]
  15. def list(self, path: str) -> list[str]:
  16. files = []
  17. for file in self.files:
  18. if not file.startswith(path):
  19. continue
  20. suffix = file.removeprefix(path)
  21. parts = suffix.split('/')
  22. if parts[0] == '':
  23. parts.pop(0)
  24. if len(parts) == 1:
  25. files.append(file)
  26. else:
  27. dir_path = os.path.join(path, parts[0])
  28. if not dir_path.endswith('/'):
  29. dir_path += '/'
  30. if dir_path not in files:
  31. files.append(dir_path)
  32. return files
  33. def delete(self, path: str) -> None:
  34. try:
  35. keys_to_delete = [key for key in self.files.keys() if key.startswith(path)]
  36. for key in keys_to_delete:
  37. del self.files[key]
  38. logger.debug(f'Cleared in-memory file store: {path}')
  39. except Exception as e:
  40. logger.error(f'Error clearing in-memory file store: {str(e)}')