Update virtual_fs.py

This commit is contained in:
2026-06-04 19:19:40 +00:00
parent 696f296b99
commit 41474758a1
+23 -42
View File
@@ -1,58 +1,39 @@
"""Simple inmemory virtual file system. """
Virtual file system used by the deep agent.
The VFS is just a dictionary mapping file names to string content. It stores files in memory and can be dumped to the real file system.
It is shared between all tools and can be exported to the real
filesystem when requested.
""" """
from __future__ import annotations import os
from pathlib import Path from pathlib import Path
from typing import Dict, Iterable from typing import Dict, Optional
class VirtualFileSystem: class VirtualFileSystem:
"""Inmemory file system. """A simple inmemory file system.
Attributes Files are stored as a mapping from a relative path to its content.
----------
files : Dict[str, str]
Mapping of file names to file content.
""" """
def __init__(self) -> None: def __init__(self, base_dir: str = "virtual_fs"):
self.base_dir = Path(base_dir)
self.files: Dict[str, str] = {} self.files: Dict[str, str] = {}
def create_file(self, name: str, content: str) -> None: def write_file(self, path: str, content: str) -> None:
"""Create or overwrite a virtual file.""" norm_path = Path(path).as_posix()
self.files[name] = content self.files[norm_path] = content
def list_files(self) -> Iterable[str]: def read_file(self, path: str) -> Optional[str]:
"""Return an iterable of file names.""" norm_path = Path(path).as_posix()
return self.files.keys() return self.files.get(norm_path)
def read_file(self, name: str) -> str: def list_files(self) -> Dict[str, str]:
"""Return the content of a virtual file. return dict(self.files)
Raises ``KeyError`` if the file does not exist. def dump_to_real_fs(self, real_root: str = "real_fs") -> None:
""" real_root_path = Path(real_root)
return self.files[name] for rel_path, content in self.files.items():
file_path = real_root_path / rel_path
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.parent.mkdir(parents=True, exist_ok=True)
file_path.write_text(content, encoding="utf-8") file_path.write_text(content, encoding="utf-8")
def __repr__(self) -> str: # pragma: no cover def __repr__(self) -> str:
return f"VirtualFileSystem({len(self.files)} files)" return f"VirtualFileSystem(files={list(self.files.keys())})"