59 lines
1.7 KiB
Python
59 lines
1.7 KiB
Python
"""Simple in‑memory virtual file system.
|
||
|
||
The VFS is just a dictionary mapping file names to string content.
|
||
It is shared between all tools and can be exported to the real
|
||
filesystem when requested.
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
from pathlib import Path
|
||
from typing import Dict, Iterable
|
||
|
||
|
||
class VirtualFileSystem:
|
||
"""In‑memory file system.
|
||
|
||
Attributes
|
||
----------
|
||
files : Dict[str, str]
|
||
Mapping of file names to file content.
|
||
"""
|
||
|
||
def __init__(self) -> None:
|
||
self.files: Dict[str, str] = {}
|
||
|
||
def create_file(self, name: str, content: str) -> None:
|
||
"""Create or overwrite a virtual file."""
|
||
self.files[name] = content
|
||
|
||
def list_files(self) -> Iterable[str]:
|
||
"""Return an iterable of file names."""
|
||
return self.files.keys()
|
||
|
||
def read_file(self, name: str) -> str:
|
||
"""Return the content of a virtual file.
|
||
|
||
Raises ``KeyError`` if the file does not exist.
|
||
"""
|
||
return self.files[name]
|
||
|
||
def export_to_disk(self, root: str | Path = ".") -> None:
|
||
"""Export all virtual files to the real filesystem.
|
||
|
||
Parameters
|
||
----------
|
||
root : str | Path, optional
|
||
Root directory where the virtual files will be written.
|
||
Defaults to the current working directory.
|
||
"""
|
||
root_path = Path(root).expanduser().resolve()
|
||
root_path.mkdir(parents=True, exist_ok=True)
|
||
for name, content in self.files.items():
|
||
file_path = root_path / name
|
||
file_path.parent.mkdir(parents=True, exist_ok=True)
|
||
file_path.write_text(content, encoding="utf-8")
|
||
|
||
def __repr__(self) -> str: # pragma: no cover
|
||
return f"VirtualFileSystem({len(self.files)} files)"
|