""" id: files title: Files Ops (unsafe) author: admin description: Read/write/delete/move/copy files and list directories. version: 0.1.0 license: Proprietary """ import os import shutil import glob from pathlib import Path # Simplified guard_write_path for seeding context def guard_write_path(path: str) -> tuple[bool, str]: try: return True, str(Path(path).resolve()) except Exception: return True, path class Tools: def read(self, path: str, max_bytes: int = 1048576) -> dict: """Read file bytes (default 1MB cap).""" with open(path, "rb") as f: data = f.read(max_bytes) return { "path": path, "size": len(data), "content": data.decode("utf-8", errors="replace"), } def write(self, path: str, content: str, mode: str = "w") -> dict: """Write text to file with mode ('w' overwrite, 'a' append).""" os.makedirs(os.path.dirname(path) or ".", exist_ok=True) with open(path, mode, encoding="utf-8") as f: f.write(content) return {"path": path, "mode": mode, "bytes": len(content.encode("utf-8"))} def delete(self, path: str) -> dict: ok, msg = guard_write_path(path) if not ok: return {"ok": False, "error": msg} """Delete file or directory recursively.""" if os.path.isdir(path) and not os.path.islink(path): shutil.rmtree(path) else: os.remove(path) return {"deleted": path} def move(self, src: str, dst: str) -> dict: """Move/rename file or folder.""" os.makedirs(os.path.dirname(dst) or ".", exist_ok=True) shutil.move(src, dst) return {"moved": {"src": src, "dst": dst}} def copy(self, src: str, dst: str) -> dict: """Copy file or folder (recursive).""" if os.path.isdir(src): shutil.copytree(src, dst, dirs_exist_ok=True) else: os.makedirs(os.path.dirname(dst) or ".", exist_ok=True) shutil.copy2(src, dst) return {"copied": {"src": src, "dst": dst}} def mkdir(self, path: str, parents: bool = True) -> dict: """Create directory (parents by default).""" if parents: os.makedirs(path, exist_ok=True) else: os.mkdir(path) return {"created": path} def list(self, path: str) -> dict: """List directory entries.""" items = [] for name in os.listdir(path): p = os.path.join(path, name) try: st = os.stat(p) items.append( {"name": name, "is_dir": os.path.isdir(p), "size": st.st_size} ) except Exception: items.append({"name": name, "error": True}) return {"path": path, "items": items} def find(self, pattern: str) -> dict: """Glob search (e.g., '/data/**/*.py').""" matches = glob.glob(pattern, recursive=True) return {"pattern": pattern, "matches": matches}