Spaces:
No application file
No application file
| import os | |
| from pathlib import Path | |
| class FileWriter: | |
| BASE_DIR = Path("generated") | |
| def __init__(self): | |
| self.BASE_DIR.mkdir(exist_ok=True) | |
| def write(self, relative_path: str, content: str, overwrite=True): | |
| target_path = self.BASE_DIR / relative_path | |
| # Prevent directory traversal attack | |
| if not str(target_path.resolve()).startswith(str(self.BASE_DIR.resolve())): | |
| raise ValueError("Invalid path detected") | |
| target_path.parent.mkdir(parents=True, exist_ok=True) | |
| if target_path.exists() and not overwrite: | |
| return f"{relative_path} already exists" | |
| with open(target_path, "w", encoding="utf-8") as f: | |
| f.write(content) | |
| return f"Written: {relative_path}" | |
| def read(self, relative_path: str): | |
| target_path = self.BASE_DIR / relative_path | |
| if not target_path.exists(): | |
| return None | |
| with open(target_path, "r", encoding="utf-8") as f: | |
| return f.read() | |