Skip to content

πŸ™Œ OpenHands: AI-Driven Development

handle not found errors inside fileop (#1188)

Robert Brennan74c9b58d1b85
diff --git a/opendevin/action/fileop.py b/opendevin/action/fileop.py
index ae7c2db655..24a5dd1657 100644
--- a/opendevin/action/fileop.py
+++ b/opendevin/action/fileop.py
@@ -38,21 +38,24 @@ class FileReadAction(ExecutableAction):
async def run(self, controller) -> FileReadObservation:
path = resolve_path(self.path)
self.start = max(self.start, 0)
- with open(path, 'r', encoding='utf-8') as file:
- if self.end == -1:
- if self.start == 0:
- code_view = file.read()
+ try:
+ with open(path, 'r', encoding='utf-8') as file:
+ if self.end == -1:
+ if self.start == 0:
+ code_view = file.read()
+ else:
+ all_lines = file.readlines()
+ code_slice = all_lines[self.start:]
+ code_view = ''.join(code_slice)
else:
all_lines = file.readlines()
- code_slice = all_lines[self.start:]
+ num_lines = len(all_lines)
+ begin = max(0, min(self.start, num_lines - 2))
+ end = -1 if self.end > num_lines else max(begin + 1, self.end)
+ code_slice = all_lines[begin:end]
code_view = ''.join(code_slice)
- else:
- all_lines = file.readlines()
- num_lines = len(all_lines)
- begin = max(0, min(self.start, num_lines - 2))
- end = -1 if self.end > num_lines else max(begin + 1, self.end)
- code_slice = all_lines[begin:end]
- code_view = ''.join(code_slice)
+ except FileNotFoundError:
+ raise FileNotFoundError(f'File not found: {self.path}')
return FileReadObservation(path=path, content=code_view)
@property
@@ -73,19 +76,22 @@ class FileWriteAction(ExecutableAction):
whole_path = resolve_path(self.path)
mode = 'w' if not os.path.exists(whole_path) else 'r+'
insert = self.content.split('\n')
- with open(whole_path, mode, encoding='utf-8') as file:
- if mode != 'w':
- all_lines = file.readlines()
- new_file = [''] if self.start == 0 else all_lines[:self.start]
- new_file += [i + '\n' for i in insert]
- new_file += [''] if self.end == -1 else all_lines[self.end:]
- else:
- new_file = insert
-
- file.seek(0)
- file.writelines(new_file)
- file.truncate()
- obs = f'WRITE OPERATION:\nYou have written to "{self.path}" on these lines: {self.start}:{self.end}.'
+ try:
+ with open(whole_path, mode, encoding='utf-8') as file:
+ if mode != 'w':
+ all_lines = file.readlines()
+ new_file = [''] if self.start == 0 else all_lines[:self.start]
+ new_file += [i + '\n' for i in insert]
+ new_file += [''] if self.end == -1 else all_lines[self.end:]
+ else:
+ new_file = insert
+
+ file.seek(0)
+ file.writelines(new_file)
+ file.truncate()
+ obs = f'WRITE OPERATION:\nYou have written to "{self.path}" on these lines: {self.start}:{self.end}.'
+ except FileNotFoundError:
+ raise FileNotFoundError(f'File not found: {self.path}')
return FileWriteObservation(content=obs + ''.join(new_file), path=self.path)
@property