forked from All-Hands-AI/OpenHands
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfileop.py
49 lines (36 loc) · 1.44 KB
/
fileop.py
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
import os
from dataclasses import dataclass
from opendevin.observation import FileReadObservation, FileWriteObservation
from opendevin.schema import ActionType
from .base import ExecutableAction
# This is the path where the workspace is mounted in the container
# The LLM sometimes returns paths with this prefix, so we need to remove it
PATH_PREFIX = "/workspace/"
def resolve_path(base_path, file_path):
if file_path.startswith(PATH_PREFIX):
file_path = file_path[len(PATH_PREFIX) :]
return os.path.join(base_path, file_path)
@dataclass
class FileReadAction(ExecutableAction):
path: str
action: str = ActionType.READ
def run(self, controller) -> FileReadObservation:
path = resolve_path(controller.workdir, self.path)
with open(path, "r", encoding="utf-8") as file:
return FileReadObservation(path=path, content=file.read())
@property
def message(self) -> str:
return f"Reading file: {self.path}"
@dataclass
class FileWriteAction(ExecutableAction):
path: str
content: str
action: str = ActionType.WRITE
def run(self, controller) -> FileWriteObservation:
whole_path = resolve_path(controller.workdir, self.path)
with open(whole_path, "w", encoding="utf-8") as file:
file.write(self.content)
return FileWriteObservation(content="", path=self.path)
@property
def message(self) -> str:
return f"Writing file: {self.path}"