memory.py 1017 B

1234567891011121314151617181920212223242526272829303132333435363738
  1. import os
  2. from .files import FileStore
  3. class InMemoryFileStore(FileStore):
  4. files: dict[str, str]
  5. def __init__(self):
  6. self.files = {}
  7. def write(self, path: str, contents: str) -> None:
  8. self.files[path] = contents
  9. def read(self, path: str) -> str:
  10. if path not in self.files:
  11. raise FileNotFoundError(path)
  12. return self.files[path]
  13. def list(self, path: str) -> list[str]:
  14. files = []
  15. for file in self.files:
  16. if not file.startswith(path):
  17. continue
  18. suffix = file.removeprefix(path)
  19. parts = suffix.split('/')
  20. if parts[0] == '':
  21. parts.pop(0)
  22. if len(parts) == 1:
  23. files.append(file)
  24. else:
  25. dir_path = os.path.join(path, parts[0])
  26. if dir_path not in files:
  27. files.append(dir_path)
  28. return files
  29. def delete(self, path: str) -> None:
  30. del self.files[path]