File size: 1,513 Bytes
28a08e7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
"""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]]