memory.py 1.5 KB

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