Terminal / tools /file_editor.py
GitHub Action
sync: backend da GitHub 2026-05-18T11:59:53Z
e6fbc88
Raw
History Blame Contribute Delete
1.51 kB
"""file_editor.py — Applica modifiche a file con backup automatico."""
import shutil
from pathlib import Path
from datetime import datetime
BACKUP_DIR=Path(".agent_backups")
def _backup(filepath:str)->str:
BACKUP_DIR.mkdir(exist_ok=True); src=Path(filepath)
if not src.exists(): return ""
ts=datetime.now().strftime("%Y%m%d_%H%M%S"); bk=BACKUP_DIR/f"{src.stem}_{ts}{src.suffix}"
shutil.copy2(src,bk); return str(bk)
def apply_replace(filepath:str,old_code:str,new_code:str,backup:bool=True)->dict:
try:
p=Path(filepath)
if not p.exists(): return {"success":False,"error":"File non trovato"}
c=p.read_text(encoding="utf-8")
if old_code not in c: return {"success":False,"error":"Blocco non trovato"}
bk=_backup(filepath) if backup else ""
p.write_text(c.replace(old_code,new_code,1),encoding="utf-8")
return {"success":True,"backup":bk}
except Exception as e: return {"success":False,"error":str(e)}
def write_file(filepath:str,content:str,backup:bool=True)->dict:
try:
p=Path(filepath); bk=_backup(filepath) if backup and p.exists() else ""
p.parent.mkdir(parents=True,exist_ok=True); p.write_text(content,encoding="utf-8")
return {"success":True,"backup":bk,"path":filepath}
except Exception as e: return {"success":False,"error":str(e)}
def list_backups()->list[dict]:
if not BACKUP_DIR.exists(): return []
return [{"path":str(b),"name":b.name,"size":b.stat().st_size} for b in sorted(BACKUP_DIR.iterdir(),reverse=True)[:20]]