41 lines
1.4 KiB
Python
41 lines
1.4 KiB
Python
import dataclasses
|
|
import typing
|
|
|
|
from failure import Failure
|
|
|
|
FILE_TOOLS = ("Edit", "MultiEdit", "Write")
|
|
|
|
|
|
@dataclasses.dataclass(frozen=True)
|
|
class Call:
|
|
tool: str
|
|
given: dict[str, typing.Any]
|
|
cwd: str
|
|
|
|
|
|
def parsed_call(hook_input: object) -> Call | Failure:
|
|
if not isinstance(hook_input, dict):
|
|
return Failure("the hook input is no object")
|
|
tool, given, cwd = hook_input.get("tool_name"), hook_input.get("tool_input"), hook_input.get("cwd")
|
|
if not isinstance(tool, str) or not isinstance(given, dict) or not isinstance(cwd, str):
|
|
return Failure("the hook input has no string tool_name and cwd and object tool_input")
|
|
return Call(tool, given, cwd)
|
|
|
|
|
|
def text(given: dict[str, typing.Any], key: str) -> str:
|
|
value = given.get(key)
|
|
return value if isinstance(value, str) else ""
|
|
|
|
|
|
def applied(call: Call, before: str) -> tuple[str, str]:
|
|
"""The text a file call writes, and the whole file it leaves."""
|
|
if call.tool == "Write":
|
|
content = text(call.given, "content")
|
|
return content, content
|
|
edits = [call.given] if call.tool == "Edit" else [edit for edit in call.given.get("edits") or [] if isinstance(edit, dict)]
|
|
after = before
|
|
for edit in edits:
|
|
old, new = text(edit, "old_string"), text(edit, "new_string")
|
|
after = after.replace(old, new) if edit.get("replace_all") else after.replace(old, new, 1)
|
|
return "\n".join(text(edit, "new_string") for edit in edits), after
|