local.py 1012 B

1234567891011121314151617181920212223242526272829303132333435
  1. import os
  2. from .files import FileStore
  3. class LocalFileStore(FileStore):
  4. root: str
  5. def __init__(self, root: str):
  6. self.root = root
  7. os.makedirs(self.root, exist_ok=True)
  8. def get_full_path(self, path: str) -> str:
  9. if path.startswith('/'):
  10. path = path[1:]
  11. return os.path.join(self.root, path)
  12. def write(self, path: str, contents: str) -> None:
  13. full_path = self.get_full_path(path)
  14. os.makedirs(os.path.dirname(full_path), exist_ok=True)
  15. with open(full_path, 'w') as f:
  16. f.write(contents)
  17. def read(self, path: str) -> str:
  18. full_path = self.get_full_path(path)
  19. with open(full_path, 'r') as f:
  20. return f.read()
  21. def list(self, path: str) -> list[str]:
  22. full_path = self.get_full_path(path)
  23. return [os.path.join(path, f) for f in os.listdir(full_path)]
  24. def delete(self, path: str) -> None:
  25. full_path = self.get_full_path(path)
  26. os.remove(full_path)