File size: 2,398 Bytes
fbf3c28
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
"""
id: editor
title: File Editor
author: admin
description: Make in-place textual edits to files with guardrails.
version: 0.2.0
license: Proprietary
"""

import io
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 replace(self, path: str, search: str, replace: str, count: int = -1) -> dict:
        """Replace occurrences of search with replace. count=-1 for all."""
        ok, msg = guard_write_path(path)
        if not ok:
            return {"ok": False, "error": msg}
        with io.open(path, "r", encoding="utf-8", errors="replace") as f:
            data = f.read()
        new = data.replace(search, replace, count if count >= 0 else data.count(search))
        with io.open(path, "w", encoding="utf-8") as f:
            f.write(new)
        return {
            "path": path,
            "replaced": 1 if new != data else 0,
            "bytes": len(new.encode("utf-8")),
        }

    def insert_after(self, path: str, marker: str, text: str) -> dict:
        """Insert text after first marker occurrence."""
        ok, msg = guard_write_path(path)
        if not ok:
            return {"ok": False, "error": msg}
        with io.open(path, "r", encoding="utf-8", errors="replace") as f:
            data = f.read()
        idx = data.find(marker)
        if idx == -1:
            return {"path": path, "inserted": 0, "reason": "marker not found"}
        new = data[: idx + len(marker)] + text + data[idx + len(marker) :]
        with io.open(path, "w", encoding="utf-8") as f:
            f.write(new)
        return {"path": path, "inserted": len(text)}

    def ensure_line(self, path: str, line: str) -> dict:
        """Ensure a line exists in the file; append if missing."""
        ok, msg = guard_write_path(path)
        if not ok:
            return {"ok": False, "error": msg}
        with io.open(path, "r", encoding="utf-8", errors="replace") as f:
            lines = f.read().splitlines()
        if line not in lines:
            lines.append(line)
            with io.open(path, "w", encoding="utf-8") as f:
                f.write("\n".join(lines) + "\n")
            return {"path": path, "added": True}
        return {"path": path, "added": False}